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.
64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
4 years ago
|
import moment from 'moment-timezone';
|
||
|
import { ObjectID } from 'mongodb';
|
||
|
import * as db from '../service/db';
|
||
5 years ago
|
|
||
|
const coll = db.collection('task');
|
||
|
|
||
4 years ago
|
export async function add(task: any) {
|
||
4 years ago
|
const t = { ...task };
|
||
|
if (typeof t.executeAfter === 'object') t.executeAfter = t.executeAfter.getTime();
|
||
4 years ago
|
t.count = t.count || 1;
|
||
4 years ago
|
t.executeAfter = t.executeAfter || new Date().getTime();
|
||
|
const res = await coll.insertOne(t);
|
||
5 years ago
|
return res.insertedId;
|
||
|
}
|
||
|
|
||
4 years ago
|
export function get(_id: ObjectID) {
|
||
5 years ago
|
return coll.findOne({ _id });
|
||
|
}
|
||
|
|
||
4 years ago
|
export function count(query: any) {
|
||
5 years ago
|
return coll.find(query).count();
|
||
|
}
|
||
|
|
||
4 years ago
|
export function del(_id: ObjectID) {
|
||
5 years ago
|
return coll.deleteOne({ _id });
|
||
|
}
|
||
|
|
||
4 years ago
|
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 });
|
||
4 years ago
|
if (res[0].interval) {
|
||
|
await coll.insertOne({
|
||
|
...res[0], executeAfter: moment().add(...res[0].interval).toDate(),
|
||
|
});
|
||
|
}
|
||
5 years ago
|
return res[0];
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
|
||
4 years ago
|
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);
|
||
5 years ago
|
}
|
||
|
|
||
4 years ago
|
global.Hydro.model.task = {
|
||
5 years ago
|
add, get, del, count, getFirst, consume,
|
||
5 years ago
|
};
|