Apollo GraphQL - 将 .graphql 模式导入为 typeDefs
Apollo GraphQL - Import .graphql schema as typeDefs
使用 graphql-yoga,您可以通过执行以下操作简单地导入您的模式:typeDefs: './src/schema.graphql'
。使用 apollo-server-express 是否有类似的方法?
如果没有,如何从外部 .graphql
文件导入 typeDef?
可以使用函数makeExecutableSchema
传入typeDefs
。像这样:
import { makeExecutableSchema } from 'graphql-tools';
import mySchema from './src/schema.graphql';
const app = express();
const schema = makeExecutableSchema({
typeDefs: [mySchema],
resolvers: {
...
},
});
app.use(
'/graphql',
graphqlExpress({ schema })
);
我找到了一种使用 grahpql-import 的方法,它完全符合我的需要。请参阅下面的示例代码:
import { ApolloServer } from 'apollo-server-express'
import { importSchema } from 'graphql-import'
import Query from './resolvers/Query'
const typeDefs = importSchema('./src/schema.graphql')
const server = new ApolloServer({
typeDefs,
resolvers: {
Query
}
})
const app = express()
server.applyMiddleware({ app })
app.listen({ port: 4000 })
**
更新:graphql-import v0.7+
**
importSchema
现在是异步的,应该作为一个承诺来处理。只需将它包装在一个 async
函数中,然后简单地 await
它。
async function start() {
const typeDefs = await importSchema(".src/schema.graphql")
}
作为最近的回应,按照此处教程的顶部 link 可以将架构移动到一个名为 schema.graphql 的新文件,然后导入“fs”和“路径”并输入在文件中,现在看起来像:
const fs = require('fs');
const path = require('path');
const server = new ApolloServer({
typeDefs: fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf8'
),
resolvers,
})
使用 graphql-yoga,您可以通过执行以下操作简单地导入您的模式:typeDefs: './src/schema.graphql'
。使用 apollo-server-express 是否有类似的方法?
如果没有,如何从外部 .graphql
文件导入 typeDef?
可以使用函数makeExecutableSchema
传入typeDefs
。像这样:
import { makeExecutableSchema } from 'graphql-tools';
import mySchema from './src/schema.graphql';
const app = express();
const schema = makeExecutableSchema({
typeDefs: [mySchema],
resolvers: {
...
},
});
app.use(
'/graphql',
graphqlExpress({ schema })
);
我找到了一种使用 grahpql-import 的方法,它完全符合我的需要。请参阅下面的示例代码:
import { ApolloServer } from 'apollo-server-express'
import { importSchema } from 'graphql-import'
import Query from './resolvers/Query'
const typeDefs = importSchema('./src/schema.graphql')
const server = new ApolloServer({
typeDefs,
resolvers: {
Query
}
})
const app = express()
server.applyMiddleware({ app })
app.listen({ port: 4000 })
**
更新:graphql-import v0.7+
**
importSchema
现在是异步的,应该作为一个承诺来处理。只需将它包装在一个 async
函数中,然后简单地 await
它。
async function start() {
const typeDefs = await importSchema(".src/schema.graphql")
}
作为最近的回应,按照此处教程的顶部 link 可以将架构移动到一个名为 schema.graphql 的新文件,然后导入“fs”和“路径”并输入在文件中,现在看起来像:
const fs = require('fs');
const path = require('path');
const server = new ApolloServer({
typeDefs: fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf8'
),
resolvers,
})