![](/img/trans.png)
[英]Best way for splitting GraphQL schema into different modules in express-graphql?
[英]merge different schema in graphql
架構.js
const { buildSchema } = require('graphql');
module.exports = buildSchema(`
type Booking {
_id: ID!
event: Event!
user: User!
}
type Event {
_id: ID!
title: String!
description: String!
price: Float!
creator: User
}
type User {
_id: ID!
email: String!
password: String
createdEvents: [Event!]
}
type RootQuery {
events: [Event!]!
users: [User!]!
bookings: [Booking!]!
}
schema {
query: RootQuery
}
`);
索引.js
app.use(
'/graphql',
graphqlHTTP({
schema: graphQlSchema,
rootValue: graphQlResolvers,
graphiql: true
})
);
我只是想學習 graphql,這是我的第一次,所以我有點困惑上面的查詢工作正常,但我想要 3 個不同的文件用於預訂、用戶、事件並將它們合並到一個文件名 index.js 和之后在主 index.js 中導入高於 1 的那個。 這是我第一次學習graphql。 任何幫助將不勝感激
您可以使用graphql-tools
包的類型定義 (SDL) 合並來合並您的類型定義文件。
該工具合並了 GraphQL 類型定義和模式。 它旨在無沖突地合並所有可能的類型、接口、枚舉和聯合。
例如
types/booking.js
:
module.exports = `
type Booking {
_id: ID!
event: Event!
user: User!
}
`;
types/user.js
:
module.exports = `
type User {
_id: ID!
email: String!
password: String
createdEvents: [Event!]
}
`;
types/event.js
:
module.exports = `
type Event {
_id: ID!
title: String!
description: String!
price: Float!
creator: User
}
`;
types/index.js
:
const { mergeTypeDefs } = require('@graphql-tools/merge');
const bookingType = require('./booking');
const userType = require('./user');
const eventType = require('./event');
const rootTypes = `
type RootQuery {
events: [Event!]!
users: [User!]!
bookings: [Booking!]!
}
schema {
query: RootQuery
}
`;
const types = [bookingType, userType, eventType, rootTypes];
module.exports = mergeTypeDefs(types);
server.js
:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema, print } = require('graphql');
const typeDefs = require('./types');
const app = express();
const port = 4000;
const schema = buildSchema(print(typeDefs));
console.log(print(typeDefs));
app.use(
'/graphql',
graphqlHTTP({
schema,
graphiql: true,
}),
);
app.listen(port, () => console.log('Server started at port:', port));
服務器日志:
type Booking {
_id: ID!
event: Event!
user: User!
}
type User {
_id: ID!
email: String!
password: String
createdEvents: [Event!]
}
type Event {
_id: ID!
title: String!
description: String!
price: Float!
creator: User
}
type RootQuery {
events: [Event!]!
users: [User!]!
bookings: [Booking!]!
}
schema {
query: RootQuery
}
Server started at port: 4000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.