diff --git a/modules/malte.nix b/modules/malte.nix index c97e189..0ef4973 100644 --- a/modules/malte.nix +++ b/modules/malte.nix @@ -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; diff --git a/pkgs/api.nix b/pkgs/api.nix new file mode 100644 index 0000000..6de16b7 --- /dev/null +++ b/pkgs/api.nix @@ -0,0 +1,15 @@ +{ + writeShellApplication, + nushell, + ... +}: +writeShellApplication { + name = "api"; + text = '' + nu ${../scripts/api.nu} "$@" + ''; + runtimeInputs = [ + nushell + ]; +} + diff --git a/scripts/api.nu b/scripts/api.nu new file mode 100644 index 0000000..57e28c8 --- /dev/null +++ b/scripts/api.nu @@ -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} +}