Encountered a bug in the findUnique function within the services of a Nest JS and Prisma project

I have a question about using Prisma with Nest. I keep encountering this error:

src/modules/auth/auth.service.ts:28:63 - error TS2322: Type 'UserWhereUniqueInput' is not assignable to type 'string'.
28     const user = await this.prisma.user.findUnique({ where: { email } });
                                                                 ~~~~~

  node_modules/.prisma/client/index.d.ts:1521:5
    1521     email?: string
             ~~~~~
    The expected type comes from property 'email' which is declared here on type 'UserWhereUniqueInput'
[11:50:56 PM] Found 1 error. Watching for file changes

Prisma error

in auth.service.ts

...
@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService, private prisma: PrismaService) {}

  async signIn({
    email,
    password,
  }: {
    email: Prisma.UserWhereUniqueInput;
    password: string;
  }) {
    const user = await this.prisma.user.findUnique({ where: { email } });
...

This is my User schema:

model User {
 id         Int      @id @default(autoincrement())
 email      String   @unique
 password   String
 lastName   String?
 firstName  String?
 roles      String[]
}

The controller that's calling the service looks like this:

...
@Post('sign-in')
  signIn(@Body() signinAuthDto: any) {
    return this.authService.signIn(signinAuthDto);
  }

Despite changing to SigninAuthDto, the issue persists:

export class SigninAuthDto {
  email: string;
  password: string;
}

Answer №1

Is it possible to simply specify the property email in the signIn method as just a string? The issue arises when attempting to assign a type of email, which is a string, to an object like Prisma unique input.

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService, private prisma: PrismaService) {}

  async signIn({
    email,
    password,
  }: {
    email: string;
    password: string;
  }) {
    const user = await this.prisma.user.findUnique({ where: { email } });

I hope this clarifies things for you!

Answer №2

I found myself in a similar position before, and the solution lies in making the user field unique. To achieve this, simply include @unique before the email attribute in your schema.prisma file.

model User {
 id       String @id @default(cuid())
 name     String
 email    String @unique
 username String
 password String
}

By doing this, you are instructing prisma to designate the email field as a unique identifier in the UserWhereUniqueInput type mentioned in the error message.

Answer №3

Encountered a similar issue but found that reopening vscode resolved the problem for me.

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

Form submission returns JSON data with an undefined value from the server

I've been following a tutorial here but ran into some issues due to using newer versions of Angular and Ionic. This is an excerpt from my code: createReview(review){ let headers = new HttpHeaders(); headers.append('Content-Type&apo ...

When testing my POST request online, it functions properly. However, I am facing difficulties in getting it to work in next.js as I keep receiving a 405

I am currently working on establishing a connection to Zoho Creator in order to retrieve some data. After successfully testing the request on and receiving the correct response, I encountered an issue while trying to implement it within a next.js applicat ...

Utilize mapGetter and mapMutations in Vuex with TypeScript without the need for class-style components syntax

After completing a project in Vue, I found myself getting a bit confused without static types. To address this, I decided to incorporate TypeScript into my project while still maintaining the traditional way of writing code, without classes and decorators. ...

Tips for receiving string body parameters from Express routes in TypeScript instead of using the 'any' type?

I have a situation where I am passing a unique identifier called productId as a hidden input within a form: <form action="/cart" method="POST"> <button class="btn" type="submit">Add to Cart</button ...

Error: Angular - encountering undefined response when making HTTP request

When making a HTTP GET request to my backend, it returns the following JSON data: "{\"instID\":\"2018#10#30\",\"procID\":1161006,\"threadNum\":0,\"status\":2}", "{\"instID\":\"2018#1 ...

Utilize various interfaces for a single object

I'm working on a Typescript project where I need to pass the same object between multiple functions with different interfaces. These are the interfaces: export interface TestModel { fileName:string, year:number, country:string } export interfac ...

React Native: Picker value remains static

I'm encountering an issue where the value of the picker does not change when I select a new value from it. This problem started occurring after I added the onValueChange function. If anyone has any insights or suggestions on how to resolve this, I wou ...

Currently experimenting with optimal strategies for implementing useReducer and context hooks

Currently exploring the most effective approach for utilizing useReducer + context hooks. Which method is considered more optimal? Implementing one useReducer in the provider with a large initial state and multiple combined reducers. Utilizing multiple ...

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 e ...

rxjs - monitoring several observables and triggering a response upon any alteration

Is there a way to watch multiple observables and execute a function whenever any of them change? I am looking for a solution similar to the functionality of zip, but without requiring every observable to update its value. Also, forkJoin isn't suitable ...

Creating an array with varying types for the first element and remaining elements

Trying to properly define an array structure like this: type HeadItem = { type: "Head" } type RestItem = { type: "Rest" } const myArray = [{ type: "Head" }, { type: "Rest" }, { type: "Rest" }] The number of rest elements can vary, but the first element ...

Is it possible to attach "traits" to a current array of objects using TypeScript?

I have a variety of object types that I need to manipulate within an array consisting of those object types. type AB = { a:number, b:number} type CD = { c:number, d:string} type DE = { d:number, e:boolean} let state: AB[] = [] function onStateChange(newSt ...

Verify if a particular string is present within an array

I am in possession of the key StudentMembers[1].active, and now I must verify if this particular key exists within the following array const array= ["StudentMembers.Active", "StudentMembers.InActive"] What is the method to eliminate the index [1] from Stu ...

React with Typescript allows us to refine the callback type depending on the presence of an optional boolean prop

In my project, there's a component <Selector /> that can optionally accept a parameter called isMulti: boolean. It also requires another parameter called onSelected, whose signature needs to change depending on the value of isMulti (whether it i ...

React, redux, and redux observable are all essential tools for developing web applications. They

I am currently working on determining the type of a promise's resolve function. Here is a snippet of the code, or you can find it on GitHub: https://github.com/Electra-project/Electra-Desktop/blob/master/src/app/header/epics.ts export function getSt ...

What causes interface to generate TS2345 error, while type does not?

In the code below: type FooType = { foo: string } function fooType(a: FooType & Partial<Record<string, string>>) { } function barType(a: FooType) { fooType(a) } interface FooInterface { foo: string } function fooInterface(a: FooInt ...

Creating a data structure that consists of pairs of elements, inspired by the alignment of domino bricks, using TypeScript syntax

My goal is to establish a type alias in TypeScript that allows all values which are arrays of Domino pairs, where each pair connects like domino bricks: Pair<A,B> connects with Pair<C,D> only if B = C. For example: const chain1: DominoChain = ...

Converting input dates in nest.js using TypeScript formatting

Is it possible to set a custom date format for input in nest.js API request body? For example, like this: 12.12.2022 @ApiProperty({ example: 'ADMIN', description: 'Role name', }) readonly value: string; @ApiProperty({ ...

Having trouble importing .task files in a Next.js project with TypeScript?

I encountered an issue when trying to import a model.task file into my App.tsx file. After training a hand gesture recognition model in Python, I exported it to a model.task file. Now, I am attempting to import this file into my Next.js + Typescript proje ...

Issue: StaticInjectorError(DynamicTestModule)[CityService -> Http]: Http provider not found

I am working on a service that retrieves all cities from a web service. @Injectable() export class CityService { constructor(private http: Http, private router: Router, private auth: AuthService) { } public getAllCity(): Observable<City[]> { ...