我目前正在使用一个单独的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工作。
发布于 2020-06-09 21:33:52
如果在.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插件或webpack装载机
import typeDefs from './type-defs.graphql'发布于 2020-06-10 12:40:09
回到当时,我自己写了一个很小的.graphql加载器。它非常小,非常简单,唯一需要做的就是在尝试导入任何.graphql文件之前导入它。从那以后,我就一直在使用它,尽管我确信有一些第三方装载器可用。下面是代码:
// 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... `;发布于 2020-12-10 05:56:13
这对我起了作用:
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);https://stackoverflow.com/questions/62290875
复制相似问题