我使用graphql-tag和apollo-server-express进行连接,为应用程序接口构建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'),
],
}):然而,我想要基于数据库模式自动创建类型'Property‘。我发现我可以像这样创建一个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;来创建最终的模式。谁能给我指个方向?任何帮助都是非常感谢的。提前谢谢你!
发布于 2020-11-14 08:42:18
好的,经过几个小时的试错和搜索,我找到了这个对我有效的解决方案:
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标记内声明,而查询在整个项目中声明了不止一次。
https://stackoverflow.com/questions/64826812
复制相似问题