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/record.js

121 lines
2.8 KiB
JavaScript

5 years ago
const _ = require('lodash');
const { ObjectID } = require('bson');
const { STATUS_WAITING } = require('./builtin').STATUS;
const task = require('./task');
const problem = require('./problem');
const { RecordNotFoundError } = require('../error');
5 years ago
const db = require('../service/db.js');
const coll = db.collection('record');
/**
5 years ago
* @param {import('../interface').Record} data
*/
async function add(data) {
_.defaults(data, {
status: STATUS_WAITING,
score: 0,
time: 0,
memory: 0,
rejudged: false,
judgeTexts: [],
compilerTexts: [],
testCases: [],
judger: null,
5 years ago
judgeAt: null,
});
5 years ago
const res = await coll.insertOne(data);
return res.insertedId;
}
/**
5 years ago
* @param {string} rid
* @returns {import('../interface').Record}
*/
async function get(rid) {
5 years ago
const _id = new ObjectID(rid);
const rdoc = await coll.findOne({ _id });
if (!rdoc) throw new RecordNotFoundError(rid);
return rdoc;
}
5 years ago
function getMany(query, sort, page, limit) {
return coll.find(query).sort(sort).skip((page - 1) * limit).limit(limit)
.toArray();
}
5 years ago
async function update(rid, $set, $push) {
5 years ago
const _id = new ObjectID(rid);
5 years ago
const upd = {};
if ($set && Object.keys($set).length) upd.$set = $set;
if ($push && Object.keys($push).length) upd.$push = $push;
await coll.findOneAndUpdate({ _id }, upd);
5 years ago
const rdoc = await coll.findOne({ _id });
if (!rdoc) throw new RecordNotFoundError(rid);
return rdoc;
}
5 years ago
function reset(rid) {
return update(rid, {
score: 0,
status: STATUS_WAITING,
time: 0,
memory: 0,
testCases: [],
judgeTexts: [],
compilerTexts: [],
judgeAt: null,
judger: null,
5 years ago
rejudged: true,
});
}
5 years ago
function count(query) {
return coll.find(query).count();
}
5 years ago
async function getList(rids) {
5 years ago
const r = {};
for (const rid of rids) r[rid] = await get(rid); // eslint-disable-line no-await-in-loop
5 years ago
return r;
}
function getUserInProblemMulti(uid, pid) {
return coll.find({ owner: uid, pid });
}
async function judge(rid) {
const rdoc = await get(rid);
const pdoc = await problem.getById(rdoc.pid);
await task.add({
event: 'judge',
rid,
type: 0,
pid: rdoc.pid,
data: pdoc.data,
lang: rdoc.lang,
code: rdoc.code,
});
}
async function rejudge(rid) {
await reset(rid);
const rdoc = await get(rid);
const pdoc = await problem.getById(rdoc.pid);
await task.add({
event: 'judge',
rid,
type: 0,
pid: rdoc.pid,
data: pdoc.data,
lang: rdoc.lang,
code: rdoc.code,
});
}
module.exports = {
add,
get,
getMany,
update,
count,
5 years ago
reset,
getList,
5 years ago
getUserInProblemMulti,
judge,
rejudge,
5 years ago
};