Implementing NestJS: Integrating TypeORM Datasource without relying on class dependency injection

I have a unique situation that requires some help. Our team is in the process of integrating nestjs into our current express codebase. Previously, we were using Typeorm 0.2 and recently upgraded to 0.3. Due to the fact that we utilize functions instead of classes, making use of datasource dependency injection without extensive refactoring is not feasible for us. Our objective is to access the datasource without relying on nestjs dependency injection.

Previously, we constructed transactions in the following manner:

import { getManager } from 'typeorm';
    
return getManager().transaction((manager) => {
  // perform actions
});

With the upgrade to TypeOrm 0.3, the usage of getManager has been deprecated. The code compiles successfully and all requests not involving the getManager function operate as intended. However, when the function containing getManager is executed, the following error occurs:

ConnectionNotFoundError: Connection "default" was not found.

I attempted to work directly with the datasource, but the dreaded "metadata not found" error surfaces and the code fails to compile at all.

import { getManager } from 'typeorm';

return AppDataSource.transaction((manager) => {
  // perform actions
});
Entity metadata for BuyerIndustry#companies was not found. Check if you specified a correct entity object and if it's connected in the connection options.

This is how we configured the datasource and imported it in the AppModule:

import { ConfigService } from '@nestjs/config';
import { DataSource } from 'typeorm';
import { repositories } from './repositories';

const configService = new ConfigService();

export const AppDataSource = new DataSource({
    type: 'postgres',
    host: configService.get('POSTGRES_HOST'),
    port: configService.get('POSTGRES_PORT'),
    username: configService.get('POSTGRES_USER'),
    password: configService.get('POSTGRES_PASSWORD'),
    database: configService.get('POSTGRES_DB'),
    migrations: [__dirname + '/src/database/migrations/*{.ts,.js}'],
    entities: repositories,
    synchronize: false,
});
// repositories.ts
export const repositories = [
    BuyerIndustry,
    Company,
    // and all other entities in the application
];
// typeorm.module.ts
import { Global, Module } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { AppDataSource } from './datasource';

@Global()
@Module({
    imports: [],
    providers: [
        {
            provide: DataSource,
            useFactory: async () => {
                await AppDataSource.initialize();

                return AppDataSource;
            },
        },
    ],
    exports: [DataSource],
})
export class CustomTypeOrmModule {}
// main.module.ts

@Module({
    imports: [
        CustomTypeOrmModule,
        // other modules
    ]
export class AppModule {
    constructor(private dataSource: DataSource) {}
}

I am absolutely sure that I have imported ALL entities in the repositories.ts. Do you have any suggestions on how we can directly access the DataSource within functions without the need for a class with the datasource injected? Any assistance would be greatly appreciated, thank you!

Answer №1

To begin with, ensure that the AppDataSource has been properly initialized. This step can be accomplished within the main.ts file.

// main.ts
import {AppDataSource } from "..." // Your datasource file

 if (!AppDataSource.isInitialized) {
    await AppDataSource.initialize();
  }

Following that, you can utilize it in any service by following this format:


const someRepo = AppDataSource.getRepository(SomeRepoEntity);

someRepo.findOne({where:{id:someId}})

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

Vuetify's v-data-table is experiencing issues with displaying :headers and :items

I'm facing an issue while working on a Vue project with typescript. The v-data-table component in my Schedule.vue file is not rendering as expected. Instead, all I can see is the image below: https://i.sstatic.net/AvjwA.png Despite searching extensi ...

Tips for creating an effective unit test using Jest for this specific controller

I'm currently grappling with the task of unit testing my Controller in an express app, but I seem to be stuck. Here are the code files I've been working with: // CreateUserController.ts import { Request, Response } from "express"; impor ...

Props used in styled components are effective, although they may trigger a warning message stating, "Warning: Received `true` for a non-boolean attribute `cen`."

Caution: A non-boolean attribute "cen" received a value of "true". If you intend to render it in the DOM, provide a string instead: cen="true" or cen={value.toString()}. While using Props in Styled-Component with TypeScript and Material-UI, everything func ...

How can I use a string variable in Angular 2 to create a dynamic template URL

@Component({ selector: 'bancaComponent', templateUrl: '{{str}}' }) export class BancaComponent implements OnInit { str: String; constructor(private http: Http) { } ngOnInit(): void { this.str = "./file.component.html"; } An ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

How come TypeScript doesn't recognize my MongoDB ObjectID as a valid type?

Currently, I am working with Node.js, MongoDB, and TypeScript. The code snippet below is error-free: const ObjectID = require("mongodb").ObjectID; const id = new ObjectID("5b681f5b61020f2d8ad4768d"); However, upon modifying the second line as follows: ...

Can I modify the cookie domain for NestJS SessionModule on a per-request basis?

I am currently using NestJS with SessionModule to handle user cookies successfully. However, I have a requirement to override the domain name for certain requests. I am uncertain about how to achieve this within NestJS, as the domain setting appears to b ...

Unable to create resource in nestjs due to typeScript compatibility issue

Encountered an Error: TypeError: Cannot access 'properties' property of undefined Failed to execute command: node @nestjs/schematics:resource --name=post --no-dry-run --language="ts" --sourceRoot="src" --spec Attempts made ...

How can I run a TypeScript function within a JavaScript file?

I am working with a typescript file named file1.ts export function Hello(str: string) { console.log(str); } In addition, I have another file called index.js { require('./some.js'); } Furthermore, there is a script defined in the pack ...

Angular 6 does not automatically include the X-XSRF-TOKEN header in its HTTP requests

Despite thoroughly reading the documentation and searching for answers on various platforms, I am still facing issues with Angular's XSRF mechanism. I cannot seem to get the X-XSRF-TOKEN header automatically appended when making a POST request. My si ...

Delete an entry in a singular mapping in a one-to-one connection [TypeORM]

Is there a way to remove an index from a one-to-one relationship in TypeORM? @OneToOne(() => Customer, { cascade: true }) @JoinColumn({ name: 'customer', referencedColumnName: 'uid' }) customer: Customer I searched the d ...

Angular 13's APP_INITIALIZER doesn't wait as expected

Recently, I have been in the process of upgrading from okta/okta-angular version 3.x to 5.x and encountered an unexpected bug. Upon startup of the application, we utilized APP_INITIALIZER to trigger appInitializerFactory(configService: ConfigService), whi ...

Error: Module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef' does not export 'ProSidebar' as requested

Using the pro-side-bar library in React is causing an issue for me. When I run the code, the console shows the following error using the dev tools: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef& ...

The functionality of TypeScript's .entries() method is not available for the type 'DOMTokenList'

I'm currently working with a stack that includes Vue3, Vite, and TypeScript. I've encountered an issue related to DOMTokenList where I'm trying to utilize the .entries() method but TypeScript throws an error saying Property 'entries&apo ...

Exploring the concept of converting a data type into an interface using map operations

Recently, I started learning Angular and I've been trying to wrap my head around how mapping from a response to an interface actually works. Let's take a look at the API response I received: [ { "id": 2, "name" : &qu ...

Exploring the world of unit testing in aws-cdk using TypeScript

Being a newcomer to aws-cdk, I have recently put together a stack consisting of a kinesis firehose, elastic search, lambda, S3 bucket, and various roles as needed. Now, my next step is to test my code locally. While I found some sample codes, they did not ...

Is there a way to include the present date and time within a mat-form-field component in Angular?

I'm working on a mat-form-field to display the current time inside an input field. I've managed to insert it, but I'm struggling with the styling. Here's the snippet of code I'm using: <mat-label>Filing Time:</mat-label> ...

Issues with typescript compiler when using React-beautiful-dnd

I recently updated react and react-beautiful-dnd to the newest versions and now I am encountering many type errors in my code: {sortedDimensions.map((dimension: any, index: number) => ( <Draggable key={index} ...

Apply a border to the div that has been selected

I have a tool for storing information and I am using *ngFor to display each instance in a line. Is there a way to add a border when clicking on a line? The border should only appear on the clicked line, disappearing from the previous one if another line i ...

NPM Package: Accessing resources from within the package

My Current Setup I have recently developed and published an npm package in typescript. This package contains references to font files located within a folder named public/fonts internally. Now, I am in the process of installing this package into an Angul ...