无服务器框架 + postgresql 中的 where 子句

where clause in serverless framework + postgresql

我是一名移动开发人员,尝试使用无服务器框架和 postgresql 部署 Restful Api 以进行测试。我设法让它工作,但只能使用简单的 CRUD(getAll、getById、删除、插入)那些在 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
      })
    })
};

如果我需要获取属于 class A 的用户怎么办?我需要编写普通查询并传递它以便它可以执行。

我想您正在使用 ORM 进行后期处理。您可以查看您使用的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 ::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;
};

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