Home > other >  "Cannot read property 'connect' of undefined
"Cannot read property 'connect' of undefined

Time:01-25

I am getting an error on pg.connect not defined. In the Handler module.


I am trying to create a table using postgres in fastify. I have and handle routes folder that handles the routes and sends API requests. When I hit the http://localhost:3000/initDB route the error says

{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "Cannot read property 'connect' of undefined"
}

this is my Table module, looks like Table module is not getting fastify instance how can i solve this issue.

const fastify = require("../server");

const Table = async (req, reply) => {
  await fastify.pg.connect(onConnect);
  function onConnect(err, client, release) {
    if (err) return reply.send(err);
    client.query(
      'CREATE TABLE IF NOT EXISTS "users" ("id" SERIAL PRIMARY KEY,"name" varchar(30),"lastname" varchar(30));',
      function onResult(err, result) {
        release();
        reply.send(err || result);
      }
    );
  }
};

module.exports = {
  Table,
};

Routes file,

I have handled routes here,

//const fastify = require("fastify");
const { Table } = require("./Handler/CreateTable");
const { GetUsers, PostUsers } = require("./Handler/Handler");
const CreateTable = {
  handler: Table,
};
const getUsers = {
  handler: GetUsers,
};

const postUsers = {
  handler: PostUsers,
};

async function routes(fastify, options) {
  fastify.get("/initDB", Table);
  fastify.get("/users", getUsers);
  fastify.post("/users/create", postUsers);
}

module.exports = routes;

server.js file,

const fastify = require("fastify")({ logger: true });
fastify.register(require("fastify-postgres"), {
  connectionString: `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_SERVICE}:${process.env.POSTGRES_PORT}/${process.env.POSTGRES_DB}`,
});

module.exports = fastify;
fastify.register(require("./routes"));

// Run the server
const start = () => {
  fastify.listen(3000, "0.0.0.0", (err, address) => {
    if (err) {
      fastify.log.error(err);
      process.exit(1);
    }
  });
};
start();

enter image description here This is error, please tell me how can I solve this error.

pg connect error to be solved

type here

CodePudding user response:

  1. Check if fastify has pg property by CTRL clicking on it on the line where you imported it. fastify class/module should be opened. There you can check the class's properties and methods.

  2. You are passing onConnect variable as a parameter to the function. This variable is not defined anywhere:

const fastify = require("../server");

const Table = async (req, reply) => {
  await fastify.pg.connect(onConnect); // <= Check if you have defined onConnect variable anywhere.
  function onConnect(err, client, release) {
    if (err) return reply.send(err);
    client.query(
      'CREATE TABLE IF NOT EXISTS "users" ("id" SERIAL PRIMARY KEY,"name" varchar(30),"lastname" varchar(30));',
      function onResult(err, result) {
        release();
        reply.send(err || result);
      }
    );
  }
};

module.exports = {
  Table,
};

CodePudding user response:

In general exporting a global variable like this, is a bad practice. The application will be extremely hard to test

const fastify = require("fastify")({ logger: true });

module.exports = fastify;

So, I would suggest to read this article about it


Regarding your issue instead, you need to change the code to:

const Table = async function (req, reply) {
  await this.pg.connect(onConnect);
  // ...
}

Note that, when you use named functions (instead of anonymous functions) the this context is the fastify instance.

You are getting undefined because the fastify variable you are referring to does not have that decorator loaded yet, so fastify.pg in that file returns undefined.

Finally, you should install @fastify/postgres instead of fastify-postgress because the last one is deprecated.

  • Related