如何将 GraphQLObjectType 与 graphql-tag 和 gql-tag 创建的模式结合起来?
Posted
技术标签:
【中文标题】如何将 GraphQLObjectType 与 graphql-tag 和 gql-tag 创建的模式结合起来?【英文标题】:How can I combine a GraphQLObjectType with a schema created by graphql-tag with gql-tag? 【发布时间】:2021-02-25 19:25:49 【问题描述】:我使用 graphql-tag 和 apollo-server-express 来连接为 api 构建 graphQL 端点。目前我创建这样的架构定义:
properties.js
let model =
const typeDefs = gql`
extend type Query
property(id: Int!): [Property]
type Property
title: String
street: String
postalcode: String
city: String
country: String
`
const resolvers =
Query:
property: getTheEntriesFromDB,
,
model.typeDefs = typeDefs;
model.resolvers = resolvers;
module.exports = model;
和 server.js
const server = new ApolloServer(
modules: [
require('./modules/properties'),
],
):
但是,我想根据数据库架构自动创建类型“属性”。我发现我可以像这样创建一个 GraphQLObjectType:
const propertyType = new graphql.GraphQLObjectType(
name: 'Property',
fields:
title: type: graphql.GraphQLString ,
street: type: graphql.GraphQLString ,
postalcode: type: graphql.GraphQLString ,
city: type: graphql.GraphQLString ,
country: type: graphql.GraphQLString ,
);
但我不知道如何将其与
let model =
const typeDefs = gql`
extend type Query
property(id: Int!): [Property]
`
const resolvers =
Query:
property: getTheEntriesFromDB,
,
model.typeDefs = typeDefs;
model.resolvers = resolvers;
module.exports = model;
创建最终架构。有人可以指出我正确的方向吗? 非常感谢任何帮助。提前非常感谢!
【问题讨论】:
【参考方案1】:好的,经过数小时的反复试验和搜索,我找到了适合我的解决方案:
properties.js
const buildASTSchema, GraphQLObjectType, GraphQLSchema, GraphQLString, parse, printSchema = require('graphql')
let model =
const propertyType = new GraphQLObjectType(
name: 'Property',
fields:
title: type: GraphQLString ,
street: type: GraphQLString ,
postalcode: type: GraphQLString ,
city: type: GraphQLString ,
country: type: GraphQLString ,
);
let typeDefs = gql`
extend type Query
property(id: Int!): [Property]
type Property
id: Int
`
typeDefs.definitions[0].kind = 'ObjectTypeDefinition' //replace ObjectTypeExtension with ObjectTypeDefinition to make AST 'valid' but keep extend in gql-tag to satisfy code inspection in ide
typeDefs = parse(printSchema(buildASTSchema(typeDefs)).replace('type Query ', 'extend type Query ') + printSchema(new GraphQLSchema( types: [ propertyType ])).replace('type Property ', 'extend type Property '))
const resolvers =
Query:
property: getTheEntriesFromDB,
,
model.typeDefs = typeDefs;
model.resolvers = resolvers;
module.exports = model;
需要“扩展”关键字,因为需要在 gql 标记内声明属性,并且在整个项目中多次声明查询。
【讨论】:
以上是关于如何将 GraphQLObjectType 与 graphql-tag 和 gql-tag 创建的模式结合起来?的主要内容,如果未能解决你的问题,请参考以下文章
来自 GraphQLObjectType 模式的 graphql mergeSchemas