【问题标题】:where clause in serverless framework + postgresql无服务器框架+ postgresql中的where子句
【发布时间】:2019-10-21 11:05:44
【问题描述】:

我是一名移动开发人员,尝试使用无服务器框架和 postgresql 部署 Restful Api 以进行测试。我设法让它工作,但只能使用简单的 CRUD(getAll、getById、delete、insert)那些在 postgresql 上找到的函数。如果我需要执行“Select * from table_name where x = xx”之类的查询,该怎么办?

这是我在 handler.js 中通过 Id 获取用户的方法

module.exports.getUser = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  db.getById('users', event.pathParameters.id)
    .then(res => {      
      callback(null,{
        statusCode: 200,
        headers: {
          "Content-Type": "application/json"
      },
        body: JSON.stringify(res)
      })
    })
    .catch(e => {
      callback(null,{
        statusCode: e.statusCode || 500,
        body: "Could not find User " + e
      })
    })
};

如果我需要将用户带到他们属于 A 类的位置怎么办?我需要编写普通查询并传递它以便执行。

【问题讨论】:

    标签: node.js postgresql rest serverless-framework serverless


    【解决方案1】:

    我想您正在使用 ORM 进行 postgress。您可以查看您正在使用的 ORM 提供者的文档。

    对于使用查询,我建议node-postgress

    node-postgres 是 node.js 模块的集合,用于与您的 PostgreSQL 数据库交互。

    然后是使用 node-postgress 的示例:

    exports.handler = async (event) => {
      const { Client } = require('pg')  //  Needs the nodePostgres Lambda Layer
      const client = new Client()
      await client.connect()
    
      const res = await client.query(
        'SELECT $1::text as message', 
        ['Hello world!'])
      console.log(res.rows[0].message)  // Shows "Hello world!""
      await client.end()
    
      const response = {
          statusCode: 200,
          result: res.rows[0].message
      };
      return response;
    };
    

    注意:您可以编写任何查询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多