如何使用 `apollo-server` 加载 .graphql 文件?
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}.`)
})
有什么方法可以简单地加载看起来像这样的 .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
工作。
使用 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]!
}
如果您在 .graphql
文件中定义类型定义,您可以通过以下几种方式之一阅读它:
1.) 自己阅读文件:
const { readFileSync } = require('fs')
// we must convert the file Buffer to a UTF-8 string
const typeDefs = readFileSync(require.resolve('./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 plugin or a webpack loader
import typeDefs from './type-defs.graphql'
那天我自己写了一个很小的 .graphql
加载器。它非常小,非常简单,您唯一要做的就是在尝试导入任何 .graphql
文件之前导入它。从那以后我就一直在使用它,尽管我确信有一些第 3 方加载程序可用。这是代码:
// 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... `;
这对我有用:
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);
我目前正在使用单独的 .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}.`)
})
有什么方法可以简单地加载看起来像这样的 .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
工作。
使用 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]!
}
如果您在 .graphql
文件中定义类型定义,您可以通过以下几种方式之一阅读它:
1.) 自己阅读文件:
const { readFileSync } = require('fs')
// we must convert the file Buffer to a UTF-8 string
const typeDefs = readFileSync(require.resolve('./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 plugin or a webpack loader
import typeDefs from './type-defs.graphql'
那天我自己写了一个很小的 .graphql
加载器。它非常小,非常简单,您唯一要做的就是在尝试导入任何 .graphql
文件之前导入它。从那以后我就一直在使用它,尽管我确信有一些第 3 方加载程序可用。这是代码:
// 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... `;
这对我有用:
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);