nlw-api/flake.nix

103 lines
2.9 KiB
Nix

{
description = "nlw-api";
inputs = {
flake-utils.url = "github:numtide/flake-utils";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-23.11";
};
outputs = { self, nixpkgs, flake-utils }:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = nixpkgs.legacyPackages.${system};
package = builtins.fromJSON (builtins.readFile ./package.json);
in
rec {
packages = flake-utils.lib.flattenTree rec {
nlw-api = pkgs.buildNpmPackage rec {
pname = "nlw-api";
inherit (package) version;
npmDepsHash = "sha256-doKVsiMdaDi8I8ivAnilSguv7xGcixAaSVh23YDoHE4=";
doCheck = false;
nativeBuildInputs = [ pkgs.makeWrapper ];
dontNpmBuild = true;
installPhase = ''
mkdir -p $out
mv ./* $out/
makeWrapper ${pkgs.nodejs-slim}/bin/node $out/bin/nlw-api \
--add-flags $out/index.js \
--chdir $out/
'';
src = ./.;
};
};
defaultPackage = packages.nlw-api;
}) // {
nixosModules = {
nlw-api = { config, lib, pkgs, ... }:
with lib;
let
cfg = config.services.nlw-api;
in {
options.services.nlw-api = {
enable = mkEnableOption "Enables the nlw-api server";
domain = mkOption {
type = types.nullOr types.str;
default = null;
description = "Which domain to host the server under; if disabled, NGINX is not used";
};
port = mkOption {
type = types.port;
default = 3500;
};
apiKey = mkOption {
type = types.str;
description = "Google Sheets API key (https://theoephraim.github.io/node-google-spreadsheet/#/guides/authentication?id=api-key)";
};
package = mkOption {
type = types.package;
default = self.defaultPackage.${pkgs.system};
};
};
config = mkIf cfg.enable {
systemd.services."nlw-api" = {
wantedBy = [ "multi-user.target" ];
environment = {
PORT = toString cfg.port;
API_KEY = cfg.apiKey;
CACHE_DIR = "/var/lib/nlw-api";
};
serviceConfig = {
Restart = "on-failure";
ExecStart = "${getExe cfg.package}";
DynamicUser = "yes";
StateDirectory = "nlw-api";
StateDirectoryMode = "0755";
};
};
services.nginx = mkIf (cfg.domain != null) {
virtualHosts."${cfg.domain}" = {
enableACME = true;
forceSSL = true;
locations."/" = {
proxyPass = "http://127.0.0.1:${toString cfg.port}/";
};
};
};
};
};
};
};
}