Difficulty establishing a connection between Typescript and Postgres results in a prolonged

I am attempting to establish a connection to a Postgres database using typescript. For the ORM, I have opted for sequelize-typescript. The issue lies in the fact that the script seems to hang at await sequelize.sync();. Below is the content of the sequelize.ts file:

import {Sequelize} from 'sequelize-typescript';
import { config } from './config/config';


const c = config.dev;

// Initialize a new Sequelize instance!
export const sequelize = new Sequelize({
  "username": c.username,
  "password": c.password,
  "database": c.database,
  "host":     c.host,

  dialect: 'postgres',
  storage: ':memory:',
});

Moreover, here is the model class file named Product.ts:

  import {Table, Column, Model, HasMany, PrimaryKey, CreatedAt, UpdatedAt, ForeignKey} from 'sequelize-typescript';

@Table
export class Product extends Model<Product> {

    @Column
    public brand: string;

    @Column
    public price: number;

    @Column
    public description!: string;

    @Column
    public imgUrl!: string;

    @Column
    public cateogry: string;

  
}

Furthermore, let's delve into the contents of the server.ts, where I make use of sequelize:

    (async () => {
 

  
  await sequelize.addModels(V0MODELS);

  //The issue arises at this point
  await sequelize.sync();

  const app = express();
  const port =  8100; // default port to listen
  
  app.use(bodyParser.json());

  
  app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:8100");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    next();
  });

  app.use('/api/v0/', IndexRouter);

  // Root URI call
  app.get( "/", async ( req, res ) => {
    res.send( "/api/v0/" );
  } );
  

  // Start the Server
  app.listen( port, () => {
      console.log( `server running http://localhost:${ port }` );
      console.log( `press CTRL+C to stop server, please :)` );
  } );
})();

Finally, provided below is the content within the package.json file:

{
  "name": "bagsshoes-server",
  "version": "1.0.0",
  "description": "",
  "main": "src/server.js",
  "scripts": {
    …
  },
  "keywords": [],
  "author": "Fahima Mokhtari",
  "license": "ISC",
  "dependencies": {
    …
  },
  "devDependencies": {
    …
  }
}

Despite my attempts with try and catch, no errors were displayed, leaving me even more perplexed. Any form of assistance would be immensely appreciated!

PS:

For context, I am working on Windows with Node version V14.7.0

Answer №1

IMPORTANT NOTICE

TLDS (TOO LONG DO SKIM)! This answer is information-heavy but well-formatted, so feel free to skim through it! If you're in a rush, focus on the sections highlighted below for quicker insights:

If you are in a hurry, jump to the Authenticate, Sequelize-typescript (not sequelize), and HELL sections.

Better yet, head straight to the HELL section to understand nodejs v14 HELL! (Hint: go towards the end!)

Don't miss the FIX (Postgres v14 HELL) section as well!

As I delved into writing this, I realized it turned out longer than expected!

SUPER HELPFUL GUIDE

In essence, sequelize should throw errors instead of hanging indefinitely!

Code Analysis

Peek into the sync code source here

 async sync(options) {
    // ...

    if (!models.length) {
      await this.authenticate(options);
    } else {
      for (const model of models) await model.sync(options);
    }
    if (options.hooks) {
      await this.runHooks('afterBulkSync', options);
    }
    return this;
  }

It's clear where the potential issues lie!

Debugging with Logging

To troubleshoot such anomalies effectively, robust logging is key!

Refer to this guide to enhance your logging capabilities within sequelize!

const sequelize = new Sequelize('sqlite::memory:', {
  // Choose one of the logging options
});

Authentication Verification

If there seems to be no logging activity, test the authentication process separately for clues!

Try verifying with the authenticate method detailed here

try {
  console.log('Gonna authenticate');
  await sequelize.authenticate();
  console.log('Connection has been established successfully.');
} catch (error) {
  console.error('Unable to connect to the database:', error);
}

No logs? Hanging at authenticate? These insights suggest an issue with authentication!

Credentials and Connectivity Check

  • Review credentials for accuracy!
  • Test connectivity using external tools like psql!

Driver Installation Reminder

Ensure that you have the appropriate driver installed per the documentation here

# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server

Enhanced Debugging Techniques

Node js VERSION (V14 HELL)

Could Node version compatibility be causing the problem? Explore how Node v14 or v15 may impact your application's functionality!

Consider checking out my experience regarding v14 HELL with Nodejs here

I'm using sequelize-typescript (not sequelize)

Delve into the nuances of working with Sequelize-typescript over native Sequelize implementations!

Sequelize-typescript Version Match

Ensure that versions of sequelize-typescript and sequelize align correctly for seamless integration!

npm install sequelize@5 sequelize-typescript@1

Making Wise Choices

Contemplate whether utilizing Sequelize-typescript offers distinct advantages over standard methods! Share any observations about its benefits!

Project Configuration Reminder

Crucial settings in the project's tsconfig file can influence its behavior significantly!

Addressing V14 HELL Issues

Anomalies & Exits

Discover why applications might exit unexpectedly in Node v14 due to peculiar changes in Openssl and API modifications!

Actual log examples from different Node versions showcase eccentric behaviors dependent on the environment setting. For more details on the relevance and scope of these changes, visit relevant GitHub PRs linked throughout the text.

The Fix: Overcoming Postgres V14 HELL

The solution resides in upgrading the pg driver to version >=8.0.3. Simply execute:

npm install pg@latest --save

Resolving Nodejs Exit Mystery

Understand the reasons behind abrupt exits caused by unresolved promises or event callbacks within the Nodejs runtime.

This section elaborates on the technical aspects of how changes in Node versions lead to unexpected application terminations.

Optimizing NVM Usage

Deploying nvm can streamline testing across varied Node versions efficiently, ensuring optimal compatibility!

Note About sequelize.sync()

Avoid relying on sync function for production setups! Embrace migrations for long-term data integrity and consistency.

Further insights on why migrations trump synchronization operations here!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Contrast between utilizing and publishing, demanding and bringing in within Express

I have recently started learning Typescript and Express. I have a simple exported function that looks like this: export function testFunction(req: any, res: any) { console.log(req.body); return res.status(200).send('OK'); }; And ...

Display an image on an HTML page based on the TypeScript data in an Ionic Angular application

After retrieving user profile data from the database and storing it in an observable, I am able to access properties such as profileData.username, profileData.msgnumber, and more. When profileData.avatar returns the name of the avatar the user is using, I ...

Adding Postgres Full Text Search field using Django migration process

After following a tutorial on adding PostgreSQL FTS capability to my Django project (using version 1.8.1), I successfully included an additional fts_document field in the my_table of the my_app app. To maintain updated databases across multiple machines, ...

Utilizing JSON object nesting to organize the results of PostgreSQL relational queries

There are three tables in my database: "parent", "children", and "grandchildren". These tables have many-to-many relationships. In addition to the main tables, there are also two relational tables. I want to create a query that will return all parent elem ...

Transfer all the child nodes to the parent using the spread operator or Object.assign while preventing duplicate properties from being overwritten

I'm trying to transfer all the nodes of a child node to the parent using the spread operator or Object.assign (without relying on Lodash) while avoiding overwriting existing properties. My initial thought was to simply append the childArray to the ro ...

Using Vue-router and Typescript with beforeEnter guard - utilizing validated data techniques

As I utilize Vue along with vue-router and typescript, a common scenario arises where a single page is dedicated to displaying a Photo component. A route includes a beforeEnter guard that checks my store to verify the existence of the requested photo. ...

PostgreSQL Unicode problem: Dealing with SQLAlchemy

I am facing an issue where I am unable to insert non-ASCII characters into a PostgreSQL 9.2 database using SQLAlchemy, despite successfully creating the full db in UTF-8. This is how I establish the connection: url = URL(drivername=s'postgresql&apo ...

Configuring global runtime variables in NextJS for server-side operations

Currently, I am utilizing the instrumentation.ts file in NextJS to retrieve configuration dynamically when the server starts up. My goal is to have this configuration accessible during runtime for all API routes and server-side components. What would be th ...

The call to the hooks is not valid. Hooks must be called within the body of a functional component

Could you please take a moment to review the validate method within the elfe-if condition in the code snippet below? I am encountering an issue when trying to invoke the useLocation method from react-router-dom. Upon researching online, I came across simil ...

Please place the accurate image inside the designated box based on the corresponding ID number

I am currently working on a function that retrieves image data from a database and displays it in HTML using *ngFor directive. In order to display the correct image, I need to fetch the ID associated with the image data and use it to retrieve the correspo ...

The Error message "Property 'data' is not present in Type <void> | AxiosHttpResponse<any>" is indicating that the data property is missing on

When I fetch data for a specific user, I have a promise that I use to setState. Below is the implementation: getUserUsername = (): string => { const { match } = this.props; return match.params.username; }; onFetchUser = () => getUse ...

How to Stop Browser Tooltip from Displaying HTML Tags within "innerHtml" in Angular 6

In my Angular application, a template is using the following code snippet: ... <span [innerHtml]="textVar"></span> ... The textVar variable is created to allow for special styling on certain characters or strings. It's formatted using th ...

Exploring the method to retrieve a dynamically added property in Typescript

My React Component Loader receives certain props. The contentAlign property is only available when the local property exists and its value is 'relative'. I am encountering an error when trying to include contentAlign in the props, and I cannot ...

What event type should be used for handling checkbox input events in Angular?

What is the appropriate type for the event parameter? I've tried using InputEvent and HTMLInputElement, but neither seems to be working. changed(event) { //<---- event?? console.log({ checked: event.target.checked }); } Here's the com ...

Transforming SQL statement into TypeORM query

Here is a simple SQL query that I have: SELECT c.name, c.planned, ( SELECT COALESCE(SUM(t.amount), 0) FROM public.transaction AS t WHERE t."categoryId" = c.id ) AS actual, c.type, c.id, c."userId" FROM public.category AS c; I am attempting to ...

Tips for merging DTO (Data Transfer Object) with non-DTO objects

I'm currently working on a new endpoint and I need to validate only two parameters (limit and offset) with the dto. The third parameter is not supposed to be checked. My controller test code is not functioning as expected. When I try to use it, the e ...

Explore the functionality of a TypeScript-created Vue component by testing it with Vue-test-utils

In my attempt to validate props with various data types in a Vue component (built using TypeScript), I utilized the Vue-test-utils package. Despite implementing expect().tobe(), there remains an untested line: DropDownList.vue <template> <v-sel ...

The Angular Service code cannot be accessed

Currently, I am utilizing Local Storage in an Angular 5 Service by referencing https://github.com/cyrilletuzi/angular-async-local-storage. My goal is to retrieve data from storage initially. In case the value is not present, I intend to fetch data from fir ...

React - The `component` prop you have supplied to ButtonBase is not valid. Please ensure that the children prop is properly displayed within this customized component

I am attempting to use custom SVG icons in place of the default icons from Material UI's Pagination component (V4). However, I keep encountering this console error: Material-UI: The component prop provided to ButtonBase is invalid. Please ensure tha ...

The data structure '{ variableName: string; }' cannot be directly assigned to a variable of type 'string'

When I see this error, it seems to make perfect sense based on what I am reading. However, the reason why I am getting it is still unclear to me. In the following example, myOtherVariable is a string and variableName should be too... Or at least that&apos ...