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.