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.
67 lines
1.5 KiB
TypeScript
67 lines
1.5 KiB
TypeScript
4 years ago
|
import Lru from 'lru-cache';
|
||
4 years ago
|
import * as db from '../service/db';
|
||
5 years ago
|
|
||
|
const coll = db.collection('system');
|
||
4 years ago
|
const cache = new Lru({
|
||
|
maxAge: 5000,
|
||
|
});
|
||
5 years ago
|
|
||
4 years ago
|
export async function get(_id: string) {
|
||
4 years ago
|
const res = cache.get(_id);
|
||
|
if (res !== undefined) return res;
|
||
5 years ago
|
const doc = await coll.findOne({ _id });
|
||
4 years ago
|
if (doc) {
|
||
|
cache.set(_id, doc.value);
|
||
|
return doc.value;
|
||
|
}
|
||
5 years ago
|
return null;
|
||
5 years ago
|
}
|
||
4 years ago
|
|
||
4 years ago
|
export async function getMany(keys: string[]): Promise<any[]> {
|
||
4 years ago
|
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;
|
||
|
}
|
||
|
|
||
4 years ago
|
export async function set(_id: string, value: any) {
|
||
4 years ago
|
cache.set(_id, value);
|
||
|
const res = await coll.findOneAndUpdate(
|
||
|
{ _id },
|
||
|
{ $set: { value } },
|
||
|
{ upsert: true, returnOriginal: false },
|
||
|
);
|
||
|
return res.value.value;
|
||
5 years ago
|
}
|
||
4 years ago
|
|
||
4 years ago
|
export async function inc(_id: string) {
|
||
|
const res = await coll.findOneAndUpdate(
|
||
|
{ _id },
|
||
|
{ $inc: { value: 1 } },
|
||
|
{ upsert: true, returnOriginal: false },
|
||
|
);
|
||
|
cache.set(_id, res.value.value);
|
||
|
return res.value.value;
|
||
5 years ago
|
}
|
||
4 years ago
|
|
||
4 years ago
|
global.Hydro.model.system = {
|
||
5 years ago
|
get,
|
||
4 years ago
|
getMany,
|
||
5 years ago
|
inc,
|
||
|
set,
|
||
5 years ago
|
};
|