prisma-nestjs-graphql icon indicating copy to clipboard operation
prisma-nestjs-graphql copied to clipboard

JSON type with arrays

Open marcalj opened this issue 3 years ago • 1 comments
trafficstars

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! ❤️

marcalj avatar Jan 22 '22 13:01 marcalj

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

unlight avatar Jan 24 '22 16:01 unlight