Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot access 'User' before initialization #60

Open
n00el opened this issue Mar 7, 2024 · 2 comments · May be fixed by #66
Open

Cannot access 'User' before initialization #60

n00el opened this issue Mar 7, 2024 · 2 comments · May be fixed by #66

Comments

@n00el
Copy link

n00el commented Mar 7, 2024

I got Cannot access 'User' before initialization because of a relation? Circular import, or what?
A relation is pretty basic in sql, how to solve this?

schema.prisma:

generator client {
  provider = "prisma-client-js"
}

generator prismaClassGenerator {
  provider = "prisma-class-generator"
  output   = "../src/_gen/prisma-class"
  dryRun   = "false"
  // separateRelationFields = "false"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean? @default(false)
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}

Generated output:

import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { User } from './user';

export class Post {
	@ApiProperty({ type: Number })
	id: number;

	@ApiProperty({ type: String })
	title: string;

	@ApiPropertyOptional({ type: String })
	content?: string;

	@ApiPropertyOptional({ type: Boolean })
	published?: boolean;

	@ApiPropertyOptional({ type: () => User })
	author?: User;

	@ApiPropertyOptional({ type: Number })
	authorId?: number;
}

import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Post } from './post';

export class User {
	@ApiProperty({ type: Number })
	id: number;

	@ApiProperty({ type: String })
	email: string;

	@ApiPropertyOptional({ type: String })
	name?: string;

	@ApiProperty({ isArray: true, type: () => Post })
	posts: Post[];
}
@joao-moonward
Copy link
Contributor

Hey! Have you tried to add this option to your tsconfig.json?

{
  "compilerOptions": {
    "strictPropertyInitialization": false
   }
}

@rhyek rhyek linked a pull request Jun 3, 2024 that will close this issue
@wxs77577
Copy link

Maybe it's better to use Type<T> of nestjs:

import { type Type } from '@nestjs/common';
// ...
user: Type<User>;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants