feat(user/malte): new api tool for beste.schule

This commit is contained in:
Malte Tammena 2024-08-09 16:09:04 +02:00
parent aba39dce48
commit bd3f6996d6
3 changed files with 51 additions and 0 deletions

View file

@ -52,6 +52,7 @@ in {
# TODO: Remove after switching occupation
services.clamav.daemon.enable = true;
services.clamav.updater.enable = true;
environment.systemPackages = [inputs.self.packages.x86_64-linux.api];
services.flatpak.enable = true;

15
pkgs/api.nix Normal file
View file

@ -0,0 +1,15 @@
{
writeShellApplication,
nushell,
...
}:
writeShellApplication {
name = "api";
text = ''
nu ${../scripts/api.nu} "$@"
'';
runtimeInputs = [
nushell
];
}

35
scripts/api.nu Normal file
View file

@ -0,0 +1,35 @@
#!/usr/bin/env nu
# Ensure that the input starts with a slash
def ensure_leading_slash [] {
if ($in | str starts-with "/") { echo $in } else { echo $"/($in)" }
}
# Apply the given `func` if `ok` is true and just pass the input if not
def maybe_apply [ ok: bool func: closure ] {
if $ok { do $func $in } else { $in }
}
# Main function
def main [ path: string ...select: cell-path --token (-t): string --explore (-x) --host: string = "http://localhost:8000" --raw (-r) ] {
# Extract token from environment if not passed explicitely
let token = if $token != null {
echo $token
} else if "TOKEN_L2" in $env {
echo $env.TOKEN_L2
} else {
error make { msg: "TOKEN_L2 environment variable is not set. Provide a token with `--token TOKEN`" label: { span: (metadata $token).span, text: "--token TOKEN not provided" }}
}
# Construct the url
let url = $"($host)/api($path | ensure_leading_slash)"
# Fetch from the api!
http get $url --allow-errors --full --headers [
"Accept" "application/json"
"Authorization" $"Bearer ($token)"
]
| if $in.status == 200 {
$in.body.data | maybe_apply ($select != null) { select ...$select }
} else {
$in.body.message
}
| maybe_apply $explore { explore }
| maybe_apply $raw {to json}
}