0

我使用 graphql-tag 和 apollo-server-express 来连接为 api 构建 graphQL 端点。目前我创建这样的架构定义:

属性.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;

创建最终架构。有人可以指出我正确的方向吗?非常感谢任何帮助。提前非常感谢!

4

1 回答 1

1

好的,经过数小时的反复试验和搜索,我发现这个解决方案对我有用:

属性.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 标记内声明属性,并且在整个项目中多次声明查询。

于 2020-11-14T00:42:18.187 回答