前言
由于工作需要,設計到了阿里云的彈性計算,這里便記錄下來
技術棧
node.js postgresql nodemailercontroller + services
編寫postgresql lib
不管異常還是正常都返回resolve,在resolve中處理結果,通過success字段去處理
const { Pool } = require('pg');const config = require('../config/default.js');const { database: { HOST, PORT, DATABASE, USERNAME, PASSWORD, },} = config;const pool = new Pool({ port: PORT, host: HOST, user: USERNAME, password: PASSWORD, database: DATABASE,});/** * * @param sql 接收的sql語句 * @param {Array} values sql語句參數 * @return { Object } { success: boolean, err || data } */const query = async function( sql = 'select NOW()', values = []) { return new Promise(resolve => { pool.connect((err, client, release) => { if (err) { return console.error('Error acquiring client', err.stack) } const params = Array.isArray(values) ? [...values] : [values]; client.query(sql, params, (error, result) => { release(); if (error) { console.error('Error executing query', error.stack); resolve({ success: false, error, }); } resolve({ success: true, data: result.rows, }); }); }); });}module.exports = { query,}config配置文件如下
const config = { // 數據庫配置 database: { DATABASE: 'databasename', USERNAME: 'root', PASSWORD: '123456', PORT: '3433', HOST: 'localhost', },};module.exports = config;Controller
BaseController
首先編寫一個基類,用于封裝一些通用的方法
const pool = require('../lib/postgre'); // 導入封裝好的mysql庫const { query } = pool; // 導入query方法class BaseController { constructor() { } // 查詢表內所有數據(非刪除) async list() { const sql = `select * from ${this.table}`; return await query(sql); } async excute(sql, vals = []) { // 執行方法 return await query(sql, vals); } // log 方法 log({func, err}) { console.log(`excute function[${func}] occured error : ${err.message || err}`); }}module.exports = BaseController;InqueryController
具體的業務邏輯Controller類
const BaseController = require('./BaseController'); // 獲得基類// 繼承基類class InqueryController extends BaseController { 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
統一封裝的方法,基類
新聞熱點
疑難解答
圖片精選