[英]How to load a .graphql file using `apollo-server`?
I am currently loading the GraphQL schema using a separate .graphql
file, but it is encapsulated within strings:我目前正在使用单独的
.graphql
文件加载 GraphQL 架构,但它封装在字符串中:
schema.graphql
const schema = `
type CourseType {
_id: String!
name: String!
}
type Query {
courseType(_id: String): CourseType
courseTypes: [CourseType]!
}
`
module.exports = schema
Then using it for the apollo-server
:然后将其用于
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}.`)
})
Is there any way to simply load a.graphql that looks as such?有没有办法简单地加载看起来像这样的a.graphql?
schema.graphql
type CourseType {
_id: String!
name: String!
}
type Query {
courseType(_id: String): CourseType
courseTypes: [CourseType]!
}
Then it would be parsed in the index.js
?那么它会在
index.js
中解析吗? I noticed that graphql-yoga
supports this, but was wondering if apollo-server
does.我注意到
graphql-yoga
支持这一点,但想知道apollo-server
是否支持。 I cannot find it anywhere in the docs.我在文档中的任何地方都找不到它。 I can't get
fs.readFile
to work either.我也无法让
fs.readFile
工作。
If you define your type definitions inside a .graphql
file, you can read it in one of several ways:如果您在
.graphql
文件中定义类型定义,您可以通过以下几种方式之一读取它:
1.) Read the file yourself: 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.) Utilize a library like graphql-tools
to do it for you: 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.) Use a babel plugin or a webpack loader 3.) 使用babel 插件或webpack 加载器
import typeDefs from './type-defs.graphql'
Back in the day I wrote a teeny-tiny .graphql
loader myself.过去,我自己编写了一个很小的
.graphql
加载程序。 It is very small, very simple, and the only thing you have to do is import it before you try to import any .graphql
files.它非常小,非常简单,您只需在尝试导入任何
.graphql
文件之前将其导入。 I have used it ever since even though I am sure that there are some 3rd party loaders available.从那以后我就一直在使用它,尽管我确信有一些 3rd 方加载器可用。 Here's the code:
这是代码:
// 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;
And then in your app:然后在您的应用程序中:
// index.js
import "./graphql-loader"; // (or require("./graphql-loader") if you prefer)
That's it, you can then import typeDefs from "./type-defs.graphql"
wherever you want.就是这样,然后您可以
import typeDefs from "./type-defs.graphql"
。
The loader works by wrapping the text in your .graphql
file inside a template string and compiling it as a simple JS module:加载器通过将
.graphql
文件中的文本包装在模板字符串中并将其编译为简单的 JS 模块来工作:
module.exports = ` ...your gql schema... `;
Figured it out using fs
(thanks to Tal Z):使用
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]!
}
This worked for me:这对我有用:
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);
This can be achieved by:这可以通过以下方式实现:
// 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.