如何使用`apollo-server`加载.graphql文件? [英] How to load a .graphql file using `apollo-server`?

查看:20
本文介绍了如何使用`apollo-server`加载.graphql文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用单独的 .graphql 文件加载 GraphQL 模式,但它封装在字符串中:

I am currently loading the GraphQL schema using a separate .graphql file, but it is encapsulated within strings:

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

Is there any way to simply load a .graphql that looks as such? schema.graphql

type CourseType {
  _id: String!
  name: String!
}

type Query {
  courseType(_id: String): CourseType
  courseTypes: [CourseType]!
}

然后会在index.js中解析?我注意到 graphql-yoga 支持这一点,但想知道 apollo-server 是否支持.我在文档中的任何地方都找不到它.我也无法让 fs.readFile 工作.

Then it would be parsed in the index.js? I noticed that graphql-yoga supports this, but was wondering if apollo-server does. I cannot find it anywhere in the docs. I can't get fs.readFile to work either.

推荐答案

如果您在 .graphql 文件中定义类型定义,您可以通过以下几种方式之一阅读它:

If you define your type definitions inside a .graphql file, you can read it in one of several ways:

1.) 自己阅读文件:

1.) Read the file yourself:

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 这样的库来为你做这件事:

2.) Utilize a library like graphql-tools to do it for you:

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'

这篇关于如何使用`apollo-server`加载.graphql文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆