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