首页 > 解决方案 > 使用 Node + Knex + Postgres 处理模型和模型方法

问题描述

我希望能得到一些帮助。我刚开始在我的 Node 应用程序中使用 Postgres,很想知道如何处理模型和模型方法。在模型和方法方面使用 Node 和 Postgres 时的最佳实践是什么?我环顾四周,我只能找到一种叫做异议的东西,但我绝对有必要走那条路吗?

理想情况下,我希望每个组件都有一个 model.js 文件,但我没有看到在处理 Postgres + Node 时使用它们。

任何帮助是极大的赞赏。谢谢大家,希望大家感恩节过得愉快!

标签: node.jspostgresql

解决方案


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;

推荐阅读