0

I'm new to postgres and promises, I'm doing this for a class where we can't use express. I have a server that allows interactions with a Heroku node pg-promise database. I'm trying to insert data with a post request, and while that is working, I can't get the endpoint to return the resulting query after inserting into the DB.

Here is my endpoint:

var server = http.createServer(function(req, res){
let uri = url.parse(req.url, true)
switch(uri.pathname){
    case '/':
        sendFile(res, 'public/index.html')
        break
    case '/index.html':
        sendFile(res, 'public/index.html')
        break
    case '/getRows':
        getRows().then((rows) => {
            res.end(JSON.stringify(rows))
        })
        break
    case '/addRow':
        console.log("adding row")
        addRow(req).then((rows) => {
            console.log('adding: ' + JSON.stringify(rows))
            console.log('\nadding: ' + rows.id)
            res.end(JSON.stringify(rows))
        })
            .catch(e =>{
            console.log(e.stack)
            return {'status': 'failure', 'message': e.stack}
        })
        break
    default:
        console.log("default path")
        res.end('404 not found')
}

And here are the DB functions:

async function getRows(){
try{
    return await db.any('SELECT * from grades')
} catch(e){
    console.log(e.stack)
}}

async function addRow(req){
let body = []
req.on('data', (chunk) => {
    body.push(chunk)
}).on('end', () => {
    body = Buffer.concat(body).toString()
    return process(JSON.parse(body))
})
async function process(obj) {
    console.log("before generating id")
    let id = generateId()
    return await db.one('INSERT INTO grades VALUES($1, $2, $3, $4) RETURNING *',
        [id, obj.student, obj.item, obj.grade])
}}

The "RETURNING *" should return the row I've inserted, however my console.logs tell me that the "rows" object in the /addRow endpoint is undefined, or if I try to access 'id' it returns undefined. The /getRows endpoint works correctly and even shows the row that was inserted. How can I get the /addRow endpoint to return the row I added? My understanding is the .then() is the callback for when the query is returned, and it even works for getRows, so why isn't it working for this one?

EDIT: I think it has to do with the fact that when I'm done processing the req body, I don't return 'await process(...)' in the anonymous function. I tried making that async and returning await process() but I still got the same error.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • 1
    `addRow` does not `return` anything. Seems like you will need to [promisify](https://stackoverflow.com/q/22519784/1048572) the event listener. – Bergi Sep 18 '18 at 18:31
  • `getRows` should not handle the error by logging and then just return `undefined`. Presumably you will want to send a different response in case of an error - so catch the error in the server callback. – Bergi Sep 18 '18 at 18:32
  • In case `addRow()` returns a rejected promise, the `.catch()` callback will just log the error but not send any response. – Bergi Sep 18 '18 at 18:33
  • To re-iterate what was said above, `addRow` doesn't return anything. And the issue is not related to `pg-promise`, more to the use of events and promises. – vitaly-t Sep 19 '18 at 00:58

0 Answers0