You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Hydro/packages/hydrooj/src/model/system.ts

69 lines
1.6 KiB
TypeScript

import Lru from 'lru-cache';
import * as db from '../service/db';
5 years ago
const coll = db.collection('system');
const cache = new Lru<string, string | number>({
maxAge: 5000,
});
export async function get(_id: string): Promise<string | number> {
const res = cache.get(_id);
if (res !== undefined) return res;
5 years ago
const doc = await coll.findOne({ _id });
if (doc) {
cache.set(_id, doc.value);
return doc.value;
}
5 years ago
return null;
}
4 years ago
export async function getMany(keys: string[]): Promise<any[]> {
const r = [];
let success = true;
for (const key of keys) {
const res = cache.get(key);
if (res !== undefined) r.push(res);
else success = false;
}
if (success) return r;
4 years ago
const docs = await coll.find({ _id: { $in: keys } }).toArray();
const dict = {};
const res = [];
for (const doc of docs) {
dict[doc._id] = doc.value;
}
for (const key of keys) {
res.push(dict[key] || null);
}
return res;
}
export async function set(_id: string, value: any) {
cache.set(_id, value);
const res = await coll.findOneAndUpdate(
{ _id },
{ $set: { value } },
{ upsert: true, returnOriginal: false },
);
return res.value.value;
}
export async function inc(_id: string) {
const res = await coll.findOneAndUpdate(
{ _id },
// FIXME NumberKeys<>
// @ts-ignore
{ $inc: { value: 1 } },
{ upsert: true, returnOriginal: false },
);
cache.set(_id, res.value.value);
return res.value.value as number;
}
4 years ago
global.Hydro.model.system = {
get,
4 years ago
getMany,
inc,
set,
};