'use strict'; const assert = require('assert'); const Service = require('egg').Service; class PaperService extends Service { constructor(ctx) { super(ctx); this.model = this.ctx.model.Paper; this.bankModel = this.ctx.model.Bank; } async create({ userName, userId, list }) { assert(userName, '用户名不存在'); assert(userId, '用户ID不存在'); assert(list, '内容不存在'); try { let fraction = 0; for (let i = 0; i < list.length; i++) { const data = await this.bankModel.findById({ _id: list[i]._id }); if (data.answer === list[i].answer) { fraction += data.fraction; } } await this.model.create({ userName, userId, list, fraction }); return { errcode: 0, errmsg: 'ok', data: { fraction } }; } catch (error) { throw error; } } async update({ id, userName, userId, list, fraction }) { assert(id, 'id不存在'); try { await this.model.updateOne({ _id: id }, { userName, userId, list, fraction }); return { errcode: 0, errmsg: 'ok', data: '' }; } catch (error) { throw error; } } async delete({ id }) { assert(id, 'id不存在'); try { await this.model.deleteOne({ _id: id }); return { errcode: 0, errmsg: 'ok', data: '' }; } catch (error) { throw error; } } async query({ skip, limit, userName, fraction }) { const filter = {}; const arr = { userName, fraction }; for (const e in arr) { const data = `{ "${e}": { "$regex": "${arr[e]}" } }`; if (arr[e]) { filter.$or = []; filter.$or.push(JSON.parse(data)); } } try { const total = await this.model.find({ ...filter }); let res; if (skip && limit) { res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit)); } else { res = await this.model.find({ ...filter }); } return { errcode: 0, errmsg: 'ok', data: res, total: total.length }; } catch (error) { throw error; } } async setTopic({ isRandom, total }) { try { let data; const list = []; if (!isRandom) { // 不随机 data = await this.bankModel.find({}, { answer: false }).skip(0).limit(Number(total)); } else { // 随机 const totals = await this.bankModel.find(); const arr = []; for (let i = 0; i < total; i++) { const num = Math.floor(Math.random() * totals.length); if (!arr.includes(num)) { arr.push(num); const res = await this.bankModel.find({}, { answer: false }).skip(Number(num)).limit(1); list.push(...res); } } } return { errcode: 0, errmsg: 'ok', data: !isRandom ? data : list, total }; } catch (error) { throw error; } } } module.exports = PaperService;