node.js - 使用 Node + Knex + Postgres 处理模型和模型方法
问题描述
我希望能得到一些帮助。我刚开始在我的 Node 应用程序中使用 Postgres,很想知道如何处理模型和模型方法。在模型和方法方面使用 Node 和 Postgres 时的最佳实践是什么?我环顾四周,我只能找到一种叫做异议的东西,但我绝对有必要走那条路吗?
理想情况下,我希望每个组件都有一个 model.js 文件,但我没有看到在处理 Postgres + Node 时使用它们。
任何帮助是极大的赞赏。谢谢大家,希望大家感恩节过得愉快!
解决方案
This is my model.js file
module.exports = ({
knex = require('./connection'),
name = '',
tableName = '',
selectableProps = [],
timeout = 1000
}) => {
const query = knex.from(tableName)
const create = props => {
delete props.id
return knex.insert(props)
.returning(selectableProps)
.into(tableName)
.timeout(timeout)
}
const findAll = () => {
return knex.select(selectableProps)
.from(tableName)
.timeout(timeout)
}
const find = filters => {
return knex.select(selectableProps)
.from(tableName)
.where(filters)
.timeout(timeout)
}
const update = (id, props) => {
delete props.id
return knex.update(props)
.from(tableName)
.where({
id
})
.returning(selectableProps)
.timeout(timeout)
}
const destroy = id => {
return knex.del()
.from(tableName)
.where({
id
})
.timeout(timeout)
}
return {
query,
name,
tableName,
selectableProps,
timeout,
create,
findAll,
find,
update,
destroy
}
}
This is my controller.js file
const model = require('./model');
const user = model({
name: "users",
tableName: "tbl_users",
});
const getAllUsers = async (req, res, next)=>{
let result = await user.findAll();
res.send(result);
}
module.exports = { getAllUsers }
And Lastly a the connection.js file
const knex = require('knex')({
client: 'pg',
connection: {
host: 'YOUR_HOST_ADDR',
user: 'YOUR_USERNAME',
password: 'YOUR_PASS',
database: 'YOUR_DB_NAME'
},
pool: {
min: 0,
max: 7
}
});
module.exports = knex;
推荐阅读
- javascript - 如何使用 jquery 将类添加到所有 li 但不单击 li
- android - 为什么具有相同屏幕尺寸和密度的 2 个不同设备的 UI 呈现不同?
- ionic4 - Ionic 3 ion-title 无法对齐中心
- php - Symfony 不验证表单
- ios - 如何从模态返回到主视图控制器
- php - 页、行和列中的块数组
- html - 如何在 VSC 中自动生成的每个结束标记之前强制换行?
- react-native - Redux-saga:配置商店时出错
- python - Python 正则表达式 - 替换基于字符串的重复模式
- javascript - 在 Vue 中使用 D3/没有选择器?