如何使用express.js pg.Pool调用Postgres函数

时间:2020-07-30 07:24:22

标签: javascript postgresql express

我编写了以下代码。我不确定它是否有效,但基本上是在尝试创建一个功能来插入带有说明的新待办事项,除非该说明为bad todo。显然,这只是为了测试,但我想调用我在Express应用程序中创建的此函数。

BEGIN;

CREATE OR REPLACE FUNCTION perntodo.createTodo(
  description perntodo.todoDescription%Type)

RETURNS VARCHAR AS
$$
DECLARE
BEGIN
  IF description == 'bad todo' THEN
    RAISE EXCEPTION 'Cannot post this todo!';
  ELSE
    INSERT INTO TODO VALUES(description);
  END IF;
END;

COMMIT;

我的控制器看起来像这样...

router.post('/', async (req, res) => {
  try {
    const { description } = req.body;
    // const newTodo = await pool.query(
    //   'INSERT INTO todo (description) VALUES($1) RETURNING *',
    //   [description]
    // );

    const newTodo = await pool.func('perntodo.createTodo', [description]);

    res.json(newTodo.rows[0]);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error...');
  }
});

注释掉的代码起作用。但是pool.func说这不是一个函数。我在做什么错了。

这就是我连接到数据库的方式

const Pool = require('pg').Pool;
const user = './user';
const DBPASSWORD = './pass';

const pool = new Pool({
  user: user,
  password: DBPASSWORD,
  host: 'localhost',
  port: 5432,
  database: 'perntodo',
});

module.exports = pool;

0 个答案:

没有答案