// 需要绑定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);
}
});
const lastestTime = iterateList[0].created_at;
if (errorList.length === 0) {
return {
code: 200,
message: 'Success',
};
}
} else {
return {
code: 204,
message: 'No user found',
};
}
}
}
module.exports = new InqueryService();
index.js
函数计算的逻辑
const inqueryService = require('./services/InqueryService');
exports.handler = async function(event, context, callback) {
const result = await inqueryService.unsendUser();
callback(null, result);
};
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。










