So I'm trying to fetch a row from my Postgres db table by id. In the function that calls the query there is data, but in the controller I'm getting a null. Seems like the controller is resolving before my query, but not sure why since I have await. My code is as follows:
TripQuery.ts
const Pool = require('pg').Pool
const pool = new Pool({
user: process.env.PG_USER,
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
password: process.env.PG_PASSWORD,
port: process.env.PG_PORT,
})
const dbGetTripById = async (id: string) => {
try {
await pool.query('SELECT * FROM trips WHERE id = $1', [id], (error: Error, results: QueryResult) => {
if (error) {
throw error
}
if (results.rows.length > 0) {
const trip: Trip = {
id: results.rows[0].id,
userId: results.rows[0].user_id,
name: results.rows[0].name,
}
console.log('from db:')
console.log(trip)
return trip
} else {
return null
}
})
} catch (e) {
console.log(e)
}
return null
}
TripController.ts
const getTrip = async (req: Request, res: Response) => {
const id = req.params.id
try {
const trip = await dbGetTripById(id)
console.log('from controller')
console.log(trip)
if (trip != null) {
res.status(200).json(trip)
} else {
res.status(404).send(`Trip with ID: ${id} does not exist`)
}
} catch (e) {
console.log(e)
}
}
TripRoutes.ts
import * as express from 'express'
import { addTrip, getTrips, getTrip, updateTrip } from '../controllers/TripController'
const router = express.Router()
router.get('/:id', getTrip)
export default router
When I call my endpoint http://localhost:3000/trips/123
I get the following logs:
Application is running on port 3000.
from controller
null
from db:
{ id: '123', userId: 'u123', name: 'trippy' }
And get the 404 error back even though the database query has fetched a value.
What am I doing wrong?