Compare commits
10 commits
6648294566
...
64affde372
Author | SHA1 | Date | |
---|---|---|---|
64affde372 | |||
7151c77d15 | |||
6dfb8ce705 | |||
aaed9e854d | |||
6de8f5bcdb | |||
2c42cf9dc8 | |||
146e05751d | |||
1906580fb4 | |||
37177e391d | |||
361ab5e8f4 |
1 changed files with 49 additions and 0 deletions
49
index.js
49
index.js
|
@ -68,6 +68,55 @@ async function get_counter_value(ns_name, key) {
|
|||
}
|
||||
}
|
||||
|
||||
async function counter_increment(ns_name, key, offset, create = false) {
|
||||
var nsid = await get_namespace_id(ns_name);
|
||||
return await sql.begin(async (sql) => {
|
||||
if (offset == 0) return true;
|
||||
if (create) {
|
||||
var existence_res =
|
||||
await sql`SELECT value FROM keys WHERE name = ${key} AND namespace_id = ${nsid}`;
|
||||
if (existence_res.length == 0) {
|
||||
if (
|
||||
!(await add_counter({
|
||||
namespace: ns_name,
|
||||
key: key,
|
||||
value: 1,
|
||||
enable_reset: false,
|
||||
update_lowerbound: 0,
|
||||
update_upperbound: 1,
|
||||
}))
|
||||
)
|
||||
return null;
|
||||
else return 1; // We know the key value will be 1 here, just return it explicitly (Ending early to save some SQL calls)
|
||||
}
|
||||
}
|
||||
var sql_res = await sql`UPDATE keys SET value = value + ${offset} WHERE
|
||||
namespace_id = ${nsid} AND
|
||||
name = ${key} AND
|
||||
${offset < 0 ? sql`update_lowerbound <= ${offset}` : sql`update_upperbound >= ${offset}`}
|
||||
RETURNING value`;
|
||||
if (sql_res.length == 1) return parseInt(sql_res[0].value);
|
||||
else return null;
|
||||
});
|
||||
}
|
||||
|
||||
app.get("/hit/:ns/:key", async function (req, res) {
|
||||
var counter_res = await counter_increment(
|
||||
req.params.ns,
|
||||
req.params.key,
|
||||
1,
|
||||
true,
|
||||
);
|
||||
return res
|
||||
.status(counter_res == null ? 403 : 200)
|
||||
.json({ value: counter_res });
|
||||
});
|
||||
app.get("/hit/:key", async function (req, res) {
|
||||
var counter_res = await counter_increment("default", req.params.key, 1, true);
|
||||
return res
|
||||
.status(counter_res == null ? 403 : 200)
|
||||
.json({ value: counter_res });
|
||||
});
|
||||
app.get("/get/:ns/:key", async function (req, res) {
|
||||
var e = await get_counter_value(req.params.ns, req.params.key);
|
||||
return res.status(e == null ? 404 : 200).json({ value: e });
|
||||
|
|
Loading…
Reference in a new issue