mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-18 01:36:08 +08:00
29 lines
906 B
JavaScript
29 lines
906 B
JavaScript
const { OpcountExceededError } = require('../error');
|
|
const db = require('../service/db.js');
|
|
|
|
const coll = db.collection('opcount');
|
|
|
|
module.exports = {
|
|
/**
|
|
* @param {string} op
|
|
* @param {string} ident
|
|
* @param {number} period_secs
|
|
* @param {number} max_operations
|
|
*/
|
|
async inc(op, ident, periodSecs, maxOperations) {
|
|
const curTime = new Date().getTime();
|
|
const beginAt = new Date(curTime - (curTime % (periodSecs * 1000)));
|
|
const expireAt = new Date(beginAt.getTime() + periodSecs * 1000);
|
|
try {
|
|
await coll.findOneAndUpdate({
|
|
ident,
|
|
beginAt,
|
|
expireAt,
|
|
op: { $not: { $gte: maxOperations } },
|
|
}, { $inc: { op: 1 } }, { upsert: true });
|
|
} catch (e) {
|
|
throw new OpcountExceededError(op, periodSecs, maxOperations);
|
|
}
|
|
},
|
|
};
|