unlight / prisma-nestjs-graphql

Generate object types, inputs, args, etc. from prisma schema file for usage with @nestjs/graphql module
MIT License
540 stars 79 forks source link

JSON type with arrays #83

Open marcalj opened 2 years ago

marcalj commented 2 years ago

I'm using a MariaDB JSON field to store an array of CandleInfo, which is not created in Prisma schema. CandleInfo is created manually in a dedicated file. The problem is that I can't set array types correctly using @FieldType and @PropertyType.

For @PropertyType, I've solved creating a custom type Array<CandleInfo>, but can't figure it out a way to fix @FieldType array definition:

Prisma schema:

model Order {
  /// @FieldType({ name: '[CandleInfo]', from: 'src/orders/entities/candle-info.entity', input: true, output: true })
  /// @PropertyType({ name: 'CandleInfoArray', from: 'src/orders/entities/candle-info.entity', namedImport: true })
  CandlesInfo Json
}

Generated file order.model.ts:

import { [CandleInfo] } from 'src/orders/entities/candle-info.entity'; // <-- This is not valid!
import { CandleInfoArray } from 'src/orders/entities/candle-info.entity'; // <-- This was initially `import { CandleInfo[] } from ...` which is also invalid.

@ObjectType()
export class Order {
    /** List of candles details */
    @Field(() => [CandleInfo], {nullable:false})
    CandlesInfo!: CandleInfoArray;
}

File: src/orders/entities/candle-info.entity.ts

export type CandleInfoArray = Array<CandleInfo>;

@ObjectType()
export class CandleInfo { // <-- Created manually since it's not stored as a DB table.
    ...
}

Any chance to detect/parse [typeNameExample] in @FieldType.name as an array automatically or provide a new parameter to flag as an array? Thanks!

PD: I'm new to GraphQL and Prisma, so maybe there's a workaround I can't find and I would appreciate any guidance.

Thanks for creating this project! ❤️

unlight commented 2 years ago

If you are adding new field which is not in prisma schema, I think it's better to generate abstract object https://github.com/unlight/prisma-nestjs-graphql#objecttype, than inherit it and add your additional fields, see https://docs.nestjs.com/graphql/resolvers#generics