我正在使用nestjs + graphql + typeORM + mongoDB创建一个graphql服务器。
我只是无法执行检索带有ObjectID(mongoDB id)的请求的查询。 并以下面的示例我有此错误
UnhandledPromiseRejectionWarning: Error: You need to provide explicit type for DemandResolver#demand parameter #0 !
objectId.scalar.ts
import {Kind} from 'graphql';
import {CustomScalar, Scalar} from '@nestjs/graphql';
import {ObjectID} from 'typeorm';
@Scalar('ObjectID', type => ObjectID)
export class ObjectIDScalar implements CustomScalar<string, ObjectID> {
description = 'Mongo object id scalar type';
parseValue(value: string) {
return new ObjectID(value); // value from the client input variables
}
serialize(value: ObjectID) {
return value.toHexString(); // value sent to the client
}
parseLiteral(ast) {
if (ast.kind === Kind.STRING) {
return new ObjectID(ast.value); // value from the client query
}
return null;
}
}
demand.ts
import {Field, InputType, ObjectType} from 'type-graphql';
import {Column, Entity, ObjectID, ObjectIdColumn} from 'typeorm';
@Entity()
@ObjectType()
@InputType('DemandInput')
export class Demand {
@Field(type => ObjectID, { nullable: true })
@ObjectIdColumn()
id?: ObjectID;
@Field({ nullable: true })
@Column({ nullable: true })
name?: string;
}
demand.module.ts
import {Module} from '@nestjs/common';
import {DemandResolver} from './demand.resolver';
import {DemandService} from './demand.service';
import {TypeOrmModule} from '@nestjs/typeorm';
import {Demand} from './demand';
import {ObjectIDScalar} from '../scalars/objectId.scalar';
@Module({
imports: [TypeOrmModule.forFeature([Demand])],
providers: [DemandResolver, DemandService, ObjectIDScalar],
})
export class DemandModule {}
demand.resolver.ts
import {Args, Mutation, Query, Resolver} from '@nestjs/graphql';
import {Demand} from '/demand';
import {DemandService} from './demand.service';
import {ObjectID} from 'typeorm';
@Resolver(Demand)
export class DemandResolver {
constructor(private readonly demandService: DemandService) { }
@Query(() => Demand)
async demand(@Args('id') id: ObjectID) {
return await this.demandService.findById(id);
}
}
demand.service.ts
import {Injectable} from '@nestjs/common';
import {InjectRepository} from '@nestjs/typeorm';
import {Demand} from '/demand';
import {MongoRepository, ObjectID} from 'typeorm';
@Injectable()
export class DemandService {
constructor(
@InjectRepository(Demand) private readonly demandRepository: MongoRepository<Demand>,
) {}
async findById(id: ObjectID) {
return this.demandRepository.findOne(id);
}
}
希望您能帮助我理解。我尝试在解析器和服务中用字符串替换ObjectID,它可以工作,但是又出现另一个错误
@Query(() => Demand)
async demand(@Args('id') id: string) {
return await this.demandService.findById(id);
}
UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL output type for id