gpt4 book ai didi

javascript - Apollo Graphql 架构拼接冲突

转载 作者:搜寻专家 更新时间:2023-11-01 00:28:42 24 4
gpt4 key购买 nike

我有一个关于 GraphQL Schema 拼接的问题。我有两个 Graphql 模式:

type Name {
firstname: String!
lastname: String!
}

type Address {
street: String!
number: Int!
}

type User {
name: Name!
address: Address!
}

type Query {
user(userId: String!): User
}

type User {
age: String!
}

type Query {
user(userId: String!): User
}

我现在尝试使用 graphql-tools 的 mergeSchemas 功能合并模式:

const schema = mergeSchemas({
schemas: [schema1, schema2]
});

但不是我想要实现的(扩展的用户类型):

type Name {
firstname: String!
lastname: String!
}

type Address {
street: String!
number: Int!
}

type User {
name: Name!
address: Address!
age: String!
}

type Query {
user(userId: String!): User
}

结果是这样的: 输入名称{ 名字:字符串! 姓氏:字符串!

type Address {
street: String!
number: Int!
}

type User {
name: Name!
address: Address!
}

type Query {
user(userId: String!): User
}

只有一个 UserType 显示在最终架构中。我尝试在 mergeSchemas 中使用 onTypeConflict API 来扩展类型,但我没有取得任何结果。

有没有办法通过扩展冲突类型来合并模式?

最佳答案

这是合并对象类型的可能解决方案。也许在 onTypeConflict 中按类型名称过滤而不是合并每个类型是有意义的。

import cloneDeep from 'lodash.clonedeep'
import { GraphQLObjectType } from 'graphql/type/definition'
import { mergeSchemas } from 'graphql-tools'

function mergeObjectTypes (leftType, rightType) {
if (!rightType) {
return leftType
}
if (leftType.constructor.name !== rightType.constructor.name) {
throw new TypeError(`Cannot merge with different base type. this: ${leftType.constructor.name}, other: ${rightType.constructor.name}.`)
}
const mergedType = cloneDeep(leftType)
mergedType.getFields() // Populate _fields
for (const [key, value] of Object.entries(rightType.getFields())) {
mergedType._fields[key] = value
}
if (leftType instanceof GraphQLObjectType) {
mergedType._interfaces = Array.from(new Set(leftType.getInterfaces().concat(rightType.getInterfaces())))
}
return mergedType
}

const schema = mergeSchemas({
schemas: [schema1, schema2],
onTypeConflict: (leftType, rightType) => {
if (leftType instanceof GraphQLObjectType) {
return mergeObjectTypes(leftType, rightType)
}
return leftType
}
})

致谢:mergeObjectTypes函数由 Jared Wolinsky 编写。

关于javascript - Apollo Graphql 架构拼接冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47227049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com