简体   繁体   English

如何使用`apollo-server`加载a.graphql文件?

[英]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.

相关问题 graphql apollo-server 中的文件上传错误 - File upload error in graphql apollo-server 使用 graphql 和 apollo-server 在解析器中获取会话 - Getting session in resolvers using graphql and apollo-server Apollo-server 在生产中隐藏 graphql ui - Apollo-server hide graphql ui in production 为什么要在服务器上缓存 graphql 字段。 (阿波罗服务器) - Why to cache graphql fields on server. ( apollo-server ) 关于如何在与 apollo-server 一起使用时处理“graphql-redis-subscriptions”身份验证的任何想法 - Any idea on how to handle 'graphql-redis-subscriptions' authentication when used together with apollo-server 使用 graphql-upload 和 apollo-server 缺少多部分字段“操作” - Missing multipart field ‘operations’ with graphql-upload and apollo-server 如何将 cookie 从 apollo-server 传递到 apollo-clenet - How to pass cookie from apollo-server to apollo-clenet 当我尝试使用 createReadStream 使用 apollo-server 上传文件时出现此错误, - I get this error when I try to upload a file with apollo-server using createReadStream , 如何在 nodeJs 中不使用 React 从 Apollo-Server 获取数据? - How to fetch data from Apollo-Server without using React in nodeJs? 用 Apollo-server 和 Prisma 2 开玩笑 - Jest with Apollo-server and Prisma 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM