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/hydro/model/task.ts

64 lines
1.7 KiB
TypeScript

import moment from 'moment-timezone';
import { ObjectID } from 'mongodb';
import * as db from '../service/db';
const coll = db.collection('task');
export async function add(task: any) {
4 years ago
const t = { ...task };
if (typeof t.executeAfter === 'object') t.executeAfter = t.executeAfter.getTime();
t.count = t.count || 1;
4 years ago
t.executeAfter = t.executeAfter || new Date().getTime();
const res = await coll.insertOne(t);
return res.insertedId;
}
export function get(_id: ObjectID) {
return coll.findOne({ _id });
}
export function count(query: any) {
return coll.find(query).count();
}
export function del(_id: ObjectID) {
return coll.deleteOne({ _id });
}
export async function getFirst(query: any) {
4 years ago
const q = { ...query };
q.executeAfter = q.executeAfter || { $lt: new Date().getTime() };
const res = await coll.find(q).sort('_id', 1).limit(1).toArray();
4 years ago
if (res.length) {
4 years ago
await coll.deleteOne({ _id: res[0]._id });
if (res[0].interval) {
await coll.insertOne({
...res[0], executeAfter: moment().add(...res[0].interval).toDate(),
});
}
5 years ago
return res[0];
}
return null;
}
export async function consume(query, cb: Function) {
4 years ago
let isRunning = false;
const interval = setInterval(async () => {
if (isRunning) return;
isRunning = true;
5 years ago
const res = await getFirst(query);
4 years ago
if (res) {
try {
await cb(res);
} catch (e) {
clearInterval(interval);
}
}
isRunning = false;
5 years ago
}, 100);
}
global.Hydro.model.task = {
5 years ago
add, get, del, count, getFirst, consume,
};