我想通过 Graphql 上的单个查询返回不同的字段数据类型(对于字节字段字符串或数组)。 然而,
'Abstract type "GetRecordsWrapper" must resolve to an Object type at runtime for field "Query.records". Either the "GetRecordsWrapper" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.'
我收到错误。为了解决这个问题,我在 Resolver 类中添加了
__resolveType
函数,但同样的错误仍然存在。
记录解析器:
import { Resolver, Query, Mutation, Args, Subscription } from '@nestjs/graphql';
import { RecordsService } from './records.service';
import { PubSub } from 'graphql-subscriptions';
import { CreateRecordInput, UpdateRecordInput} from '../graphql';
const pubSub = new PubSub();
@Resolver('Record')
export class RecordsResolver {
constructor(private readonly recordsService: RecordsService) {}
__resolveType(obj: any) {
if (typeof obj.byte === 'string') {
return 'HexByteStringResponse';
}
if (Array.isArray(obj.byte)) {
return 'ByteArrayResponse';
}
return null;
}
@Query('records')
async records(@Args('format') args: "byte" | "array"): Promise<any> {
return this.recordsService.findAll(args);
}
记录服务:
import { Injectable } from '@nestjs/common';
import { Record } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { CreateRecordInput, UpdateRecordInput, GetRecordsWrapper, HexByteStringResponse, ByteArrayResponse } from 'src/graphql';
@Injectable()
export class RecordsService {
constructor(private prisma: PrismaService) {}
async findAll(format: "byte" | "array"): Promise<GetRecordsWrapper[]> {
const records = await this.prisma.record.findMany({
include: {
provider: true,
},
});
return records.map(record => {
if (format === "byte") {
return {
...record,
byte: `0x${record.byte.toString('hex')}`,
} as HexByteStringResponse;
} else {
return {
...record,
byte: Array.from(record.byte),
} as ByteArrayResponse;
}
});
}
Graphql 架构包括并集:
scalar DateTime
scalar Bytes
scalar Provider
type Record {
id: ID!
byte: Bytes!
sendedAt: DateTime!
createdAt: DateTime!
provider: Provider!
}
type HexByteStringResponse {
id: ID!
byte: String!
sendedAt: DateTime!
createdAt: DateTime!
provider: Provider!
}
type ByteArrayResponse {
id: ID!
byte: [Int!]!
sendedAt: DateTime!
createdAt: DateTime!
provider: Provider!
}
union GetRecordsWrapper = HexByteStringResponse | ByteArrayResponse
type Query {
records(format: String!): [GetRecordsWrapper]!
record(id: String!): GetRecordsWrapper
recordsWrapper(type: String!): GetRecordsWrapper
}
我认为你应该为联合编写解析器,而不是为了记录本身。 根据文档这里
@Resolver('GetRecordsWrapper')
export class GetRecordsWrapperResolver {
__resolveType(obj: any) {
if (typeof obj.byte === 'string') {
return 'HexByteStringResponse';
}
if (Array.isArray(obj.byte)) {
return 'ByteArrayResponse';
}
return null;
}
}