knex——nodejs连接数据库及异常处理
前言:最近用到了新工具knex——nodejs连接数据库,感觉很不错的库,记录一下使用过程。
一、介绍
英文版文档:https://knexjs.org/guide/
中文版文档:https://knex.nodejs.cn/guide/
二、配置
import dotenv from 'dotenv' dotenv.config() const Config = { client: 'pg', connection: process.env.DB_URL, acquireConnectionTimeout: 5000, pool: { min: 2, // Minimum number of connections in the pool max: 20, // Maximum number of connections in the pool // propagateCreateError: false, // enabling knex to automatically reconnect on create connection failure instead of throwing the error. }, migrations: { directory: './migrations', }, seeds: { directory: './seeds' }, } const knexConfig = { Dev: Config, Beta: Config, Prod: Config } export default knexConfig
1,dotenv
npm 官方文档的这样介绍 dotenv: Dotenv 是一个零依赖的模块,它能将环境变量中的变量从 .env 文件加载到 process.env 中。将环境相关的配置独立于代码之外亦是 The Twelve-Factor App 的要素之一。
使用 dotenv 可以让我们免于在各个文件中引入配置文件,也可以很好的解决敏感信息的泄漏,利于后期代码维护,快用起来吧!
2,knex配置
import knexfile from './knexfile.js' import knex from 'knex' const configOptions = knexfile[process.env.STAGE] const knexWithConfig = knex(configOptions) export default knexWithConfig
knexfile就是上面的配置文件
const knexWithConfig = knex(configOptions)
这句才是实例化。
三、使用
异常处理
router.post('/:tick', async(ctx, next) => { // 特定tick
const params = ctx.request.params;
const ids = params.tick
let sql = `
SELECT src20_tick_v4.*, src20_mint_progress_v4.*
FROM ${SRC20_TICK_TABLE} s, ${SRC20_MINT_PROGRESS_TABLE}
WHERE s.id=src20_mint_progress_v4.id and src20_tick_v4.id='${ids}'
`
let res = []
try {
res = await knex.raw(sql).asCallback(function(err) {
if (err) {
// console.log(false, err, err.message);
// ctx.body = fail(err.message);
// throw err;
// console.log(false, err);
// 这里的err,与try catch捕获的完全一样。
} else {
console.log(true);
const resMap = []
for (let each of res.rows) {
resMap.push({
tick: each.tick,
stamp_url: each.stamp_url,
max: each.max ? each.max : "",
lim: each.lim ? each.lim : "",
amt: new Decimal(each.amt),
dec: each.dec ? each.dec : 18,
creator: each.creator,
tx_hash: each.tx_hash,
block_index: each.block_index,
block_time: each.block_time,
})
}
ctx.body = success(resMap.length ? resMap[0] : {})
}
})
} catch (e) {
// console.log('---------', e.status, e.statusCode, e.message);
ctx.body = fail(e.message);
}
})

浙公网安备 33010602011771号