Managing database downtime with TypeORM

In the event that my MSSQL server experiences a crash and an app client makes a request to the API, the current behavior is for it to endlessly spin until Express times out the unanswered request.

By enabling logging in TypeORM, I am able to observe the execution of the relevant query.

Rather than allow the request to time out, I would prefer to return an API response notifying the client that the database is currently unreachable.

This snippet below showcases the code present in my user controller:

public static listAll = async (req: Request, res: Response) => {
    const userRepository = getRepository(User);
    const users = await userRepository
        .find()
    res.send(users);
};

I attempted to use `.catch` on the request being utilized in the corresponding controller, but unfortunately, this did not yield any changes. An example is provided below:

const users = await userRepository
    .find()
    .catch(error => {
        console.log(error); // this is never triggered
});

No error message appeared in the console despite these efforts.

The following are the connection options specified in TypeORM:

createConnection({
    type: 'mssql',
    host: process.env.TYPEORM_HOST,
    port: parseInt(process.env.TYPEORM_PORT, 0),
    username: process.env.TYPEORM_USERNAME,
    password: process.env.TYPEORM_PASSWORD,
    database: process.env.TYPEORM_DATABASE,
    synchronize: true,
    logging: true,
    entities: models,
    cli: {
        entitiesDir: 'src/entity',
        migrationsDir: 'src/migration',
        subscribersDir: 'src/subscriber',
    },
})
    .then(connection => {
        const server = http.createServer(App);
        server.listen({ port: `${process.env.APP_PORT}` }, () => {
            console.log(`🚀 Server ready at http://${process.env.TYPEORM_HOST}:${process.env.APP_PORT}`);
        });

        if (connection.isConnected) {
            console.log(`Database ${connection.options.database} connected`);
        }
    })
    .catch(error => console.log(error));

I also experimented with setting `requestTimeout` in `createConnection` to 1000 milliseconds, with no change in outcome.

Answer â„–1

class MyApplication {

  constructor() {
    this.app = express();
    this.configureApp();
  }

  async configureApp() {

    try {
      this.dbConnection = await Database.initialize();

      // Enable JSON Body parsing
      this.app.use(bodyParser.json());

      // Initialize Routes
      Routes.setup(this.app);
      
    } catch(error) {
      console.log('There was an error connecting to the database:', error)
    };

  }

  getAppInstance(): express.Application {
    return this.app;
  }

}

The Database.initialize() method is used to establish a connection with the database:

class Database {

  static initialize() {

    return createConnection({
      type: "postgres",
      host: process.env.TYPEORM_HOST,
      port: parseInt(process.env.TYPEORM_PORT),
      database: process.env.TYPEORM_DATABASE,
      username: process.env.TYPEORM_USERNAME,
      password: process.env.TYPEORM_PASSWORD,
      entities: [
        User
      ],
      synchronize: process.env.TYPEORM_SYNCHRONIZE == "true" ? true : false,
      logging: process.env.TYPEORM_LOGGING == "true" ? true : false
    });

  }

}

If you change the database name to a random one, error messages will be displayed in the console:

[nodemon] starting `ts-node src/server.ts`
Server running on port 5000
Error connecting to database:
{ error: database "random_db_name" does not exist
    at Connection.parseE 
    at Connection.parseMessage 
    at Socket.<anonymous> 
    at Socket.emit (events.js:198:13)
    at Socket.EventEmitter.emit (domain.js:448:20)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  name: 'error',
  length: 106,
  severity: 'FATAL',
  code: '3D000',
  detail: undefined,
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'postinit.c',
  line: '890',
  routine: 'InitPostgres' }

Is this the desired outcome?

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

The module 'node:fs' could not be located. Stack required:

I've been developing a Teams app with my tab in React and TypeScript. (In case you're unfamiliar, the tab can be seen as an individual React app) Currently, I'm setting up linting using ESLint and Prettier. I have successfully run the scri ...

Error with tsc rootDir due to Docker's installation of yarn in root directory

I am encountering a problem with my node project which serves a simple "hello world" server. Everything runs smoothly when I run it locally, but when I try to run it inside Docker, a /opt/yarn-v1.21.1 folder is created which leads to a rootDir error: erro ...

Create a .d.ts file for a custom JavaScript file

I am working on an application written in JavaScript and considering incorporating TypeScript for a new feature. Currently, I have a base class defined in JavaScript as shown below: // base.js module.exports = function BaseClass () { // ... ... }; M ...

Error in cypress configuration occurs when a plug is mistakenly defined as an import instead of a const within the cypress.config.ts file

Hello, I am new to using Cypress so please bear with me if this seems like a trivial issue. Below you will find my cypress.config.ts file where I am attempting to integrate the cypress esbuild preprocessor into the configuration. import cypress_esbuild_pre ...

What is the best way to transform an Observable array containing objects into an Observable that emits the data contained within those objects?

Encountering an error: Error: Type 'Observable<Country[]>' is not assignable to type 'Observable'. Type 'Country[]' is missing properties like name, tld, alpha2Code, alpha3Code and more.ts(2322 The issue might be due ...

essential elements for mapping an array using typescript

Struggling to iterate through an array of objects, each with a unique id created by uuidv4(), resulting in a string type. TypeScript is giving errors (( Type 'String' is not assignable to type 'Key | null | undefined')) due to the &apos ...

What is the best way to set the first option in a mat-select to be

My approach to date selection involves using 3 mat-select components for day, month, and year. You can view a demo of this setup here. In an attempt to improve the code, I decided to set the initial options as null by modifying the following lines: allDat ...

Why aren't the child elements in my React / Framer Motion animation staggered as expected?

In my finance application, I am creating a balance overview feature. To display the content, I pass props into a single <BalanceEntry> component and then map all entries onto the page. With Framer Motion, my goal is to animate each rendered <Bala ...

Using a function to implement *ngFor results in generating a loop

When using *ngFor in Angular with a function that returns data, the function gets called multiple times and can sometimes result in a loop: app.component.ts export class AppComponent { getArray(): string[] { //I can track when this function is c ...

Tips for importing a .ts file into another .ts file within an Angular 5 application

I have a bunch of utility methods stored in a file called utils.ts that I want to reuse across multiple components. I'm not sure if it's even possible, and if it is, where should I place the import statement and what would be the correct syntax. ...

Solving issues with malfunctioning Angular Materials

I'm facing an issue with using angular materials in my angular application. No matter what I try, they just don't seem to work. After researching the problem online, I came across many similar cases where the solution was to "import the ...

I am having trouble getting ngFor to properly render my accessible data. Whenever I attempt to use it, it ends up breaking my code. Can someone please

When using *ngFor to iterate through data, everything appears to be working fine until attempting to access nested data within an object inside another object. For example: { "tvshow": [ { "id": "value", "time": { "clock": "valu ...

Error with constructor argument in NestJS validator

I've been attempting to implement the nest validator following the example in the 'pipes' document (https://docs.nestjs.com/pipes) under the "Object schema validation" section. I'm specifically working with the Joi example, which is fun ...

The operation failed with a TypeError because the object does not allow the addition of the newField property

I encountered an error that says: TypeError: Cannot add property newField, object is not extensible Whenever I try to add a new key or change a value, it doesn't work and I'm not sure what the issue is. dynamicFilter; public ionViewWillEnte ...

The method of evaluating in-line is distinct from evaluating outside of the

What causes the compiler to produce different results for these two mapped types? type NonNullableObj1<O> = {[Key in keyof O] : O[Key] extends null ? never : O[Key]} type NotNull<T> = T extends null ? never : T; type NonNullableObj2<T> = ...

It seems that Ionic 2 does not support the registration of custom HTML tags

Encountering a problem with Ionic 2 and custom components. Developed a component to show in a list, serving as the list item. However, my app crashes when attempting to use the custom HTML tag. The stack trace is provided below. Uncertain about the issue. ...

Encountering a "ReferenceError: global is not defined" in Angular 8 while attempting to establish a connection between my client application and Ethereum blockchain

I'm trying to configure my web3 provider using an injection token called web3.ts. The token is imported in the app.component.ts file and utilized within the async ngOnInit() method. I've attempted various solutions such as: Medium Tutorial ...

NextJS API routes consistently provide a status code of 200 upon execution

I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET reque ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

Using multiple MaterialUI components in a JavaScript page with React can pose challenges

Incorporating multiple MaterialUI Cards in my project, I encountered an issue where all the cards would expand or the select values would change simultaneously. Despite using unique key values and mapped components with distinct keys, the problem persisted ...