PostgreSQL Node.js实现函数计算方法示例
前言
由于工作需要,设计到了阿里云的弹性计算,这里便记录下来
技术栈
- node.js
- postgresql
- nodemailer
controller+ services
编写postgresqllib
不管异常还是正常都返回resolve,在resolve中处理结果,通过success字段去处理
const{Pool}=require('pg');
constconfig=require('../config/default.js');
const{
database:{
HOST,
PORT,
DATABASE,
USERNAME,
PASSWORD,
},
}=config;
constpool=newPool({
port:PORT,
host:HOST,
user:USERNAME,
password:PASSWORD,
database:DATABASE,
});
/**
*
*@paramsql接收的sql语句
*@param{Array}valuessql语句参数
*@return{Object}{success:boolean,err||data}
*/
constquery=asyncfunction(sql='selectNOW()',values=[]){
returnnewPromise(resolve=>{
pool.connect((err,client,release)=>{
if(err){
returnconsole.error('Erroracquiringclient',err.stack)
}
constparams=Array.isArray(values)?[...values]:[values];
client.query(sql,params,(error,result)=>{
release();
if(error){
console.error('Errorexecutingquery',error.stack);
resolve({
success:false,
error,
});
}
resolve({
success:true,
data:result.rows,
});
});
});
});
}
module.exports={
query,
}
config配置文件如下
constconfig={
//数据库配置
database:{
DATABASE:'databasename',
USERNAME:'root',
PASSWORD:'123456',
PORT:'3433',
HOST:'localhost',
},
};
module.exports=config;
Controller
BaseController
首先编写一个基类,用于封装一些通用的方法
constpool=require('../lib/postgre');//导入封装好的mysql库
const{query}=pool;//导入query方法
classBaseController{
constructor(){
}
//查询表内所有数据(非删除)
asynclist(){
constsql=`select*from${this.table}`;
returnawaitquery(sql);
}
asyncexcute(sql,vals=[]){
//执行方法
returnawaitquery(sql,vals);
}
//log方法
log({func,err}){
console.log(`excutefunction[${func}]occurederror:${err.message||err}`);
}
}
module.exports=BaseController;
InqueryController
具体的业务逻辑Controller类
constBaseController=require('./BaseController');//获得基类
//继承基类
classInqueryControllerextendsBaseController{
constructor(){
super();
this.table='data_table';//赋值table
}
//可以重写基类的方法,如果有业务需要
asynclist(){
constsql=`select*from${this.table}ORDERBYcreated_atDESC`;
returnawaitthis.excute(sql);
}
asyncgetUnsendCustomer(vals){
constsql=`select*from${this.table}wherecreated_at>$1ORDERBYcreated_atDESC`;
//统一在基类调用sql参数
returnawaitthis.excute(sql,vals);
}
}
module.exports=InqueryController;
Service
BaseService
统一封装的方法,基类
//需要绑定this的方法
constfuncs=[
'list',
]
classBaseService{
constructor(){
this.controller=null;
//循环遍历绑定this,在koa绑定route的时可用到
funcs.forEach(item=>{
this[item]=this[item].bind(this)
});
}
//查询方法
asynclist(ctx){
if(!ctx){
returnawaitthis.controller.list();
}
//controller返回的是一个对象,success(成功为true,失败为false),data(成功则有此数据),err(失败则有此对象)
const{success:flag,data,error}=awaitthis.controller.list();
if(flag){
//success
ctx.body={
data,
code:200,
}
}else{
//failed
ctx.body={
code:500,
error,
};
}
}
}
module.exports=BaseService
InqueryService
具体的业务逻辑
//导入基类
constBaseService=require('./BaseService');
//导入对应的controller
constController=require('../controller/InqueryController');
//获取MailSenderService
constMailService=require('./MailSender');
constHelper=require('../util/Helper');
constfuncs=[
'unsendUser',
];
//生成一次controller
constcontroller=newController();
classInqueryServiceextendsBaseService{
constructor(){
super()
//绑定对应的controller
this.controller=controller;
funcs.forEach(item=>{
this[item]=this[item].bind(this);
});
}
getMailOpts(i){
//youcanusethedatafromdatabasetocombinethemessage
constmessage='Helloworld!';
returnreturn{
message,
//可以从配置文件读取或者oss
to:'xxxx@gmail.com',
subject:'HelloWorld',
};
}
asyncunsendUser(){
constlist=awaitthis.controller.list();
if(list.length>0){
constmailer=newMailService();
consterrorList=[];
iterateList.forEach(asynci=>{
constmailerOption=this.getMailOpts(i);
const{success,...rest}=awaitmailer.sendToAuitAdmin(mailerOption);
if(!success){
errorList.push(rest);
}
});
constlastestTime=iterateList[0].created_at;
if(errorList.length===0){
return{
code:200,
message:'Success',
};
}
}else{
return{
code:204,
message:'Nouserfound',
};
}
}
}
module.exports=newInqueryService();
index.js
函数计算的逻辑
constinqueryService=require('./services/InqueryService');
exports.handler=asyncfunction(event,context,callback){
constresult=awaitinqueryService.unsendUser();
callback(null,result);
};
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。