I’m trying to make an API that uses PostgreSQL to store shortened links. However, when trying to execute a query to the database, postgreClient
is undefined every time.
short.controller.ts:
import { Request, Response, NextFunction } from "express";
import client from "../Database";
export default class ShortController {
private postgreClient;
constructor() {
this.postgreClient = client;
}
async post(request: Request, response: Response, next: NextFunction) {
const url = request.query.url;
const randomString = Math.random().toString(36).substring(2, 7);
const shortUrl = `${process.env.API_URL}/api/short/${randomString}`;
try {
const sql = "INSERT INTO short (short_url, url) VALUES ($1, $2)";
await this.postgreClient.query(sql, [shortUrl, url]);
await response.json({ shortUrl });
} catch (exception) {
console.error(exception);
await response.json({ message: "Error" });
}
}
}
Database.ts:
import { Client } from "pg";
import * as dotenv from "dotenv";
dotenv.config();
const dbHost = process.env.DB_HOST || "localhost";
const dbPort = process.env.DB_PORT || 5432;
const dbUser = process.env.DB_USER || "postgres";
const dbPassword = process.env.DB_PASSWORD || "password";
const dbDatabase = process.env.DB_DATABASE || "kyowakoku";
const connectionString = `postgres://${dbUser}:${dbPassword}@${dbHost}:${dbPort}/${dbDatabase}`;
const client = new Client({ connectionString });
export default client;
I tried rewriting to a especially class thinking it would do something, but without result.
2
Answers
The only issue I see is that you did not call connect() on the postgres client . This means you’ve built a connection string and failed to do the actual connection to the DB.
There are 2 ways you can solve this.
Other general rules
I assume that the
TypeError: Cannot read properties of undefined (reading 'postgresClient')
error occurs around these lines:That means that
this
refers to anundefined
value, in other words, the context of the function has been lost. So i’d suggest you to check where and how the methodShortController#post
is being called.I can assume that the method was called without it’s context. Maybe somewhere in your code you passed the method to the express instance in such a manner:
To fix this you need to explicitly bind the function to the correct context:
This probably will fix the issue with lost function’s context, but for further checks see @big-bob-little’s answer also.
Note that it is just an assumption based on the amount of code provided by you. It is always better to post the whole reproduction code. Also the entire error message with the stack trace is also helpful.