countify/index.js
2024-05-24 07:16:03 +00:00

72 lines
2.1 KiB
JavaScript

import sql from "./db.js";
import express from "express";
import { unlink } from "fs/promises";
import { randomUUID } from "crypto";
const app = express();
function notImplementedHandler(req, res, next) {
res.sendStatus(418);
}
async function get_namespace_id(name) {
return await sql.begin(async (sql) => {
var potential_res = await sql`
INSERT INTO namespaces(name) VALUES (${name}) ON CONFLICT DO NOTHING RETURNING id;
`;
if (potential_res.length == 0) {
var e = await sql`SELECT id FROM namespaces WHERE name = ${name} LIMIT 1`;
console.log("e", e, e[0], e[0].id);
return e[0].id;
} else {
console.log("p", potential_res);
return potential_res[0].id;
}
});
}
async function add_counter(opts) {
const { key, value, enable_reset, update_lowerbound, update_upperbound } =
opts;
const nsid = await get_namespace_id(opts.namespace);
console.log(nsid);
await sql`
INSERT INTO keys(
name,
value,
namespace_id,
enable_reset,
update_lowerbound,
update_upperbound
) VALUES (
${key},
${parseInt(value)},
${nsid},
${enable_reset},
${parseInt(update_lowerbound)},
${parseInt(update_upperbound)}
)
`;
return;
}
app.get("/create", async function (req, res) {
var sane_query;
sane_query = req.query;
if (!sane_query?.namespace) sane_query.namespace = "default";
if (!sane_query?.key) sane_query.key = randomUUID();
if (!sane_query?.enable_reset) sane_query.enable_reset = false;
else sane_query.enable_reset = !!sane_query.enable_reset;
if (!sane_query?.update_lowerbound) sane_query.update_lowerbound = "-1";
if (!sane_query?.update_upperbound) sane_query.update_upperbound = "1";
if (!sane_query?.value) sane_query.value = "0";
const add_counter_res = await add_counter(req.query);
return res.json({
namespace: sane_query.namespace,
key: sane_query.key,
value: sane_query.value,
});
});
const listen_path =
process.env?.LISTEN_PATH || process.env?.NODE_ENV == "production"
? "/run/user/2123/countify/webserver.sock"
: "/run/user/2123/countify-dev.sock";
if (listen_path[0] == "/") {
await unlink(listen_path);
}
app.listen(listen_path);