constructor() {
super();
this.table = 'data_table'; // 赋值table
}
// 可以重写基类的方法,如果有业务需要
async list() {
const sql = `select * from ${this.table} ORDER BY created_at DESC `;
return await this.excute(sql);
}
async getUnsendCustomer(vals) {
const sql = `select * from ${this.table} where created_at > $1 ORDER BY created_at DESC`;
// 统一在基类调用sql参数
return await this.excute(sql, vals);
}
}
module.exports = InqueryController;
Service
BaseService
统一封装的方法,基类
// 需要绑定this的方法
const funcs = [
'list',
]class BaseService {
constructor() {
this.controller = null;
// 循环遍历绑定this, 在koa绑定route的时可用到
funcs.forEach(item => {
this[item] = this[item].bind(this)
});
} // 查询方法
async list(ctx) {
if (!ctx) {
return await this.controller.list();
}
// controller返回的是一个对象,success(成功为true, 失败为false), data(成功则有此数据), err(失败则有此对象)
const { success: flag, data, error } = await this.controller.list();
if (flag) {
// success
ctx.body = {
data,
code: 200,
}
} else {
// failed
ctx.body = {
code: 500,
error,
};
}
}
}
module.exports = BaseService
InqueryService
具体的业务逻辑
// 导入基类
const BaseService = require('./BaseService');
// 导入对应的controller
const Controller = require('../controller/InqueryController');
// 获取MailSender Service
const MailService = require('./MailSender');
const Helper = require('../util/Helper');const funcs = [
'unsendUser',
];
// 生成一次controller
const controller = new Controller();
class InqueryService extends BaseService {
constructor() {
super()
// 绑定对应的controller
this.controller = controller;
funcs.forEach(item => {
this[item] = this[item].bind(this);
});
}
getMailOpts(i) {
// you can use the data from database to combine the message
const message = 'Hello world!';
return return {
message,
// 可以从配置文件读取或者oss
to: 'xxxx@gmail.com',
subject: 'Hello World',
};
}
async unsendUser() {
const list = await this.controller.list();
if (list.length > 0) {
const mailer = new MailService();
const errorList = [];
iterateList.forEach(async i => {
const mailerOption = this.getMailOpts(i);
const { success, ...rest } = await mailer.sendToAuitAdmin(mailerOption);
if (!success) {
errorList.push(rest);









