nestjs : 定义 map/array 用于 mongoose 和 graphql

nestjs : Define map/array to be used in mongoose and graphql

我正在使用 nestJs,我正在尝试创建一个突变,它接收一个键值数组作为参数。 此外,我正在定义一个 ObjectType,它将定义 mongoose 模式和 graphql objectType。

  1. CarName:数组的数据。
  2. SetCarParams:突变的输入。
  3. Car: mongoose+graphql 模式定义
import { Field, InputType, ObjectType } from '@nestjs/graphql';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@ObjectType()
export class CarName {
  @Field()
  key: string;

  @Field()
  value: string;
}

@InputType()
export class SetCarParams {
  @Field(() => [CarName])
  names: CarName[];
}

@Schema()
@ObjectType()
export class Car {
  @Prop({ type: [CarName] })
  @Field(() => [CarName])
  names: CarName[];
}

export type CarDocument = Car & Document;
export const CarDto = SchemaFactory.createForClass(Car);

@Mutation(() => Car)
  setCar(@Args(camelCase(Car.name)) carParams: SetCarParams) {
    console.log('do something');
}

我收到的错误:CannotDetermineInputTypeError: Cannot determine a GraphQL input type for the "names". Make sure your class is decorated with an appropriate decorator.

  1. 当我将类型设置为字符串而不是 CarName 时,我的结构有效。
  2. 当我在猫鼬模式中使用原始类型时,它也不起作用
@Schema()
@ObjectType()
export class Car {
  @Prop(
    raw({
      type: Map,
      of: CarName,
    }),
  )
  @Field(() => [CarName])
  names: CarName[];
}
  1. 此外,当我尝试不使用 SetCarParams 作为突变的输入类型时,它也不起作用
@Mutation(() => Car)
  setCar(
    @Args('names', { type: () => [{ key: String, value: String }] })
    names: [{ key: string; value: string }],
  ) {

所以,我弄清楚了问题 - InputType 和 ObjectType 的命名冲突。 当我为它们设置一个准确的命名时,它就像一个魅力。

import { Field, InputType, ObjectType } from '@nestjs/graphql';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@InputType('CarNameInput')
@ObjectType('CarNameType')
@Schema({ versionKey: false, timestamps: true })
export class CarName {
  @Prop()
  @Field(() => String)
  key: string;

  @Prop()
  @Field(() => String)
  value: string;
}

@InputType('CarInput')
@ObjectType('CarType')
export class Car {
  @Field(() => [CarName])
  carNames: Array<CarName>;
}

export type CarNameDocument = CarName & Document;
export const CarNameDto = SchemaFactory.createForClass(CarName);
import { Field, ObjectType, Mutation } from '@nestjs/graphql';
import { Schema } from '@nestjs/mongoose';

@ObjectType()
@Schema()
export class Identifier {
  @Field(() => String)
  id: string;
}

@Mutation(() => Identifier)
async addCar(@Args({ name: 'car', type: () => Car }) car: Car) {
  //TODO something
}

我如何调用 graphql 中的突变:

mutation {
  addCar(
    car: {
      carNames: [
        { key: "asdf1", value: "hello" }
        { key: "asdf2", value: "world" }
      ]
    }
  ) {
    id
  }
}