[英]How to load a .graphql file using `apollo-server`?
我目前正在使用单独的.graphql
文件加载 GraphQL 架构,但它封装在字符串中:
schema.graphql
const schema = `
type CourseType {
_id: String!
name: String!
}
type Query {
courseType(_id: String): CourseType
courseTypes: [CourseType]!
}
`
module.exports = schema
然后将其用于apollo-server
:
index.js
const { ApolloServer, makeExecutableSchema } = require('apollo-server')
const typeDefs = require('./schema.graphql')
const resolvers = { ... }
const schema = makeExecutableSchema({
typeDefs: typeDefs,
resolvers
})
const server = new ApolloServer({
schema: schema
})
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}.`)
})
有没有办法简单地加载看起来像这样的a.graphql? schema.graphql
type CourseType {
_id: String!
name: String!
}
type Query {
courseType(_id: String): CourseType
courseTypes: [CourseType]!
}
那么它会在index.js
中解析吗? 我注意到graphql-yoga
支持这一点,但想知道apollo-server
是否支持。 我在文档中的任何地方都找不到它。 我也无法让fs.readFile
工作。
如果您在.graphql
文件中定义类型定义,您可以通过以下几种方式之一读取它:
1.)自己阅读文件:
const { readFileSync } = require('fs')
// we must convert the file Buffer to a UTF-8 string
const typeDefs = readFileSync('./type-defs.graphql').toString('utf-8')
2.)利用像graphql-tools
这样的库来为你做这件事:
const { loadDocuments } = require('@graphql-tools/load');
const { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader');
// this can also be a glob pattern to match multiple files!
const typeDefs = await loadDocuments('./type-defs.graphql', {
file,
loaders: [
new GraphQLFileLoader()
]
})
3.) 使用babel 插件或webpack 加载器
import typeDefs from './type-defs.graphql'
过去,我自己编写了一个很小的.graphql
加载程序。 它非常小,非常简单,您只需在尝试导入任何.graphql
文件之前将其导入。 从那以后我就一直在使用它,尽管我确信有一些 3rd 方加载器可用。 这是代码:
// graphql-loader.js
const oldJSHook = require.extensions[".js"];
const loader = (module, filename) => {
const oldJSCompile = module._compile;
module._compile = function (code, file) {
code = `module.exports = \`\r${code}\`;`;
module._compile = oldJSCompile;
module._compile(code, file);
};
oldJSHook(module, filename);
};
require.extensions[".graphql"] = loader;
require.extensions[".gql"] = loader;
然后在您的应用程序中:
// index.js
import "./graphql-loader"; // (or require("./graphql-loader") if you prefer)
就是这样,然后您可以import typeDefs from "./type-defs.graphql"
。
加载器通过将.graphql
文件中的文本包装在模板字符串中并将其编译为简单的 JS 模块来工作:
module.exports = ` ...your gql schema... `;
使用fs
计算出来(感谢 Tal Z):
index.js
const fs = require('fs')
const mongoUtil = require('./mongoUtil')
const { ApolloServer, makeExecutableSchema } = require('apollo-server')
function readContent (file, callback) {
fs.readFile(file, 'utf8', (err, content) => {
if (err) return callback(err)
callback(null, content)
})
}
mongoUtil.connectToServer((error) => {
if (error) {
console.error('Error connecting to MongoDB.', error.stack)
process.exit(1)
}
console.log('Connected to database.')
const Query = require('./resolvers/Query')
const resolvers = {
Query
}
readContent('./schema.graphql', (error, content) => {
if (error) throw error
const schema = makeExecutableSchema({
typeDefs: content,
resolvers
})
const server = new ApolloServer({
schema: schema
})
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}.`)
})
})
})
schema.graphql
type CourseType {
_id: String!
name: String!
}
type Query {
courseType(_id: String): CourseType
courseTypes: [CourseType]!
}
这对我有用:
const { gql } = require('apollo-server');
const fs = require('fs');
const path = require('path');
//function that imports .graphql files
const importGraphQL = (file) =>{
return fs.readFileSync(path.join(__dirname, file),"utf-8");
}
const gqlWrapper = (...files)=>{
return gql`${files}`;
}
const enums = importGraphQL('./enums.graphql');
const schema = importGraphQL('./schema.graphql');
module.exports = gqlWrapper(enums,schema);
这可以通过以下方式实现:
// schema.ts
import 'graphql-import-node';
import {makeExecutableSchema} from 'graphql-tools';
import {ApolloServer} from 'apollo-server-express';
import * as typeDefs from './schema/schema.graphql';
import resolvers from './resolverMap';
const schema = new ApolloServer({
schema: makeExecutableSchema({
typeDefs,
resolvers
})
});
export default schema;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.