I'm at a loss as to why the NestJS provider is showing as undefined in my code

Prisma.service.ts

import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'
import { PrismaClient } from '@prisma/client'

@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit, OnModuleDestroy
{
  constructor() {
    super({
      log: ['warn', 'error'],
    })
  }

  onModuleInit() {
    return this.$connect()
  }

  onModuleDestroy() {
    return this.$disconnect()
  }
}

users-repository.ts

import { UserRepository } from "src/application/repositories/users-repository";
import { PrismaService } from "../prisma.service";
import { CreateUserDTO, FindUserDTO, UpdateUserDTO } from "src/core/dtos/user.dto";
import { User, UserWithoutPassword } from "src/core/entities/user.entity"



export class PrismaUserRepository implements UserRepository {
    constructor(private prisma: PrismaService) { }

    async create(user: CreateUserDTO): Promise<User> {
        
        const createdUser = await this.prisma.user.create({ data: user })

        if (createdUser) {
            return null;
        }


        return createdUser;
    }
}

abstract-user-repository.ts


import { User, UserWithoutPassword } from 'src/core/entities/user.entity';
import {CreateUserDTO, FindUserDTO, UpdateUserDTO} from '../../core/dtos/user.dto'

export abstract class UserRepository {
    abstract create(user: CreateUserDTO): Promise<User | null>

    abstract findByEmail(email: string): Promise<User | null>

    abstract findAll(query: FindUserDTO): Promise<UserWithoutPassword[]>

    abstract findOne(id: string): Promise<UserWithoutPassword | null>

    abstract update(id: string, user: UpdateUserDTO): Promise<UserWithoutPassword | null>

    abstract remove(id: string): Promise<UserWithoutPassword | null>
}

database.module.ts


import { Module } from "@nestjs/common";
import { PrismaService } from "./prisma/prisma.service";
import { UserRepository } from "../../application/repositories/users-repository";
import { PrismaUserRepository } from "./prisma/repositories/users-repository";


@Module({
    providers: [
        PrismaService,
        {
            provide: UserRepository,
            useClass: PrismaUserRepository,
        },
    ],
    exports: [
        UserRepository
    ],
})
export class DatabaseModule { }

While attempting to initialize a user creation process, an error message is displayed stating that the prisma object is undefined.

TypeError: Cannot read properties of undefined (reading 'user') at PrismaUserRepository.create (\src\infra\database\prisma\repositories\users-repository.ts:13:47)

I meticulously investigated the imports and cross-checked for any missing nestJS decorators without identifying any discrepancies. Additionally, I ensured that Prisma was properly connected during npm startup.

Answer №1

It seems the reason for this issue is likely due to overlooking the @Injectable() decorator on the PrismaUserRepository class, which has a dependency that needs to be resolved by Nestjs DI container.

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

Determining the parent type in Typescript by inferring it from a nested member

Typescript has the ability to infer the type of a value based on queries made within if statements. For instance, the type of one member of an object can be deduced based on another: type ChildType = 'a' | 'b'; type Child<T extends ...

Ways to transfer specific properties from one object to another in TypeScript

I'm currently working on a function that selectively copies key-value pairs from one object to another in order to remove certain properties. The code snippet for this function is shown below: sanitizeData: function (sourceObject: object, ...allowedKe ...

What is the best way to access a component's data within its method using Vue and Typescript?

Starting a Vue.js project with TypeScript and using single file components instead of class-styled ones has been my goal. However, I have encountered a recurring issue where I get error TS2339 when trying to reference my components' data using the "th ...

Service consuming in Angular 2 using Stomp protocol

Why am I seeing responseBody as undefined, but I am able to see the subscribe response in msg_body? What could be causing this issue with responseBody? let stomp_subscription = this._stompService.subscribe('/topic/queue'); stomp_subscription.ma ...

Creating a function that can have either one or two arguments, with the types of the arguments determined by a specific string literal

I am looking to create a function called emitEvent(event, extra?), which will be restricted by a string literal enum of known strings such as POPUP_OPEN and POPUP_CLOSED. The function will accept a second argument that is a specifically defined dictionary ...

Personalized style for text overflow property

The application is created using Angular. Within a component, we have a div containing some text: <div>abcdefghijklmnop<div> Depending on the screen size, the text should either be fully displayed or clipped. I discovered the property 'te ...

Receiving an eslint error while trying to integrate Stripe pricing table into a React web application

If you're looking to incorporate a Stripe documentation code snippet for adding a stripe-pricing-table element, here's what they suggest: import * as React from 'react'; // If you're using TypeScript, don't forget to include ...

Having trouble triggering a click event with React testing library?

I am working with a <Select/> component as shown in the image below. App.tsx import React, { useState, ChangeEvent } from "react"; import MySelect from "./MySelect"; export default function App() { const [countryCode, setCoun ...

Challenges with implementing asynchronous functions in NestJS controllers

Currently, I am in the process of developing a finance tracker application that involves importing data from a CSV file. The import functionality checks if an entry already exists in the database, adds a specific category to it if not found, and then saves ...

The lib.dom.d.ts file is seriously lacking in many key components

Are there any updated versions of lib.dom.d.ts? The current one is missing a lot of essential information, causing numerous compilation errors. For example, consider this line: window.File && window.FileReader && window.FileList && ...

Passing a method from a component to a service in Angular 9

Recently, I've been working on some websocket code that involves sending a message to the server and receiving a reply. The current implementation is functional, but I'm looking to refactor it by encapsulating it within a service and then callin ...

Encountering an HTTP parsing failure while sending XML through Angular 5's HttpClient

Struggling to access a local webservice through XML: Take a look at the code below: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'text/xml', 'Accept': 'text/xml', 'Response- ...

I have a Visual Studio 2019 solution that consists of two projects - one is an Angular project and the other is written in TypeScript. I have successfully configured

We are currently utilizing Visual Studio 2019 (not the VS Code version) for our project. Within this solution, we have multiple projects included. One of these projects contains Angular code that we compile using the traditional 'ng build' comma ...

Typescript does not process and compile files located within a specified directory

Recently, I embarked on a small TypeScript project and took the time to create the tsconfig.json configuration file. { "compilerOptions": { "target": "es5", "module": "commonjs", "sourceMap": true }, "files": [ "./typings/index.d.ts" ...

What steps can be taken to resolve the error message "Property does not have an initializer and is not definitively assigned in the constructor"?

I'm encountering an issue with these classes. I want to utilize the doSomething() method that is exclusive to class B without having to type cast it each time. However, when I specify property a to be of type B, it gives me an error saying it's n ...

Struggling with continuously re-rendering a color background when using useMemo in React?

After every re-render, a new color is generated. Is there a way to store the initial color and reuse it in subsequent renders? const initialColor = generateNewColor(); // some random color const backgroundColor = React.useMemo(() => { return ...

Inject the data within Observable<Object> into Observable<Array>

I'm faced with a situation where I have two distinct API endpoints. One endpoint returns a single Card object, while the other endpoint returns an Array of Card objects. My goal is to retrieve the first Card from the single Card endpoint and place it ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

Fetching User Details Including Cart Content Upon User Login

After successfully creating my e-commerce application, I have managed to implement API registration and login functionalities which are working perfectly in terms of requesting and receiving responses. Additionally, I have integrated APIs for various produ ...

Transforming the data type of a variable

Recently, I decided to switch my file name from index.js to index.ts. Here's an example of the issue I'm facing: let response = "none" let condition = true if(condition){ response = {id: 123 , data: []} } console.log(response) Howev ...