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.
61 lines
1.4 KiB
TypeScript
61 lines
1.4 KiB
TypeScript
4 years ago
|
import { ObjectID, QuerySelector } from 'mongodb';
|
||
|
import { MessageNotFoundError } from '../error';
|
||
|
import * as db from '../service/db';
|
||
5 years ago
|
|
||
|
const coll = db.collection('message');
|
||
|
|
||
4 years ago
|
export async function send(from: number, to: number, content: string) {
|
||
4 years ago
|
const res = await coll.insertOne({
|
||
4 years ago
|
from, to, content, unread: true,
|
||
5 years ago
|
});
|
||
4 years ago
|
return {
|
||
|
from, to, content, unread: true, _id: res.insertedId,
|
||
|
};
|
||
5 years ago
|
}
|
||
|
|
||
4 years ago
|
export async function get(_id: ObjectID) {
|
||
5 years ago
|
const doc = await coll.findOne({ _id });
|
||
4 years ago
|
if (!doc) throw new MessageNotFoundError(_id);
|
||
5 years ago
|
return doc;
|
||
|
}
|
||
|
|
||
4 years ago
|
export function getByUser(uid: number) {
|
||
4 years ago
|
return coll.find({ $or: [{ from: uid }, { to: uid }] }).sort('_id', 1).toArray();
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
export function getMany<T>(query: QuerySelector<T>, sort, page: number, limit: number) {
|
||
5 years ago
|
return coll.find(query).sort(sort)
|
||
|
.skip((page - 1) * limit).limit(limit)
|
||
|
.toArray();
|
||
|
}
|
||
|
|
||
4 years ago
|
export function del(_id: ObjectID) {
|
||
5 years ago
|
return coll.deleteOne({ _id });
|
||
|
}
|
||
|
|
||
4 years ago
|
export function count<T>(query: QuerySelector<T>) {
|
||
5 years ago
|
return coll.find(query).count();
|
||
|
}
|
||
|
|
||
4 years ago
|
export function getMulti(uid: number) {
|
||
5 years ago
|
return coll.find({ $or: [{ from: uid }, { to: uid }] });
|
||
|
}
|
||
|
|
||
4 years ago
|
export function ensureIndexes() {
|
||
5 years ago
|
return Promise.all([
|
||
|
coll.createIndex({ to: 1, _id: -1 }),
|
||
|
coll.createIndex({ from: 1, _id: -1 }),
|
||
|
]);
|
||
|
}
|
||
|
|
||
4 years ago
|
global.Hydro.model.message = {
|
||
5 years ago
|
count,
|
||
|
get,
|
||
4 years ago
|
getByUser,
|
||
5 years ago
|
del,
|
||
|
getMany,
|
||
|
getMulti,
|
||
5 years ago
|
send,
|
||
4 years ago
|
ensureIndexes,
|
||
5 years ago
|
};
|