如何使用“apollo-server”加载 .graphql 文件?

2024-02-23

我目前正在使用单独的加载 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要么工作。


如果您在 a 中定义类型定义.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.) 使用巴贝尔插件 https://github.com/detrohutt/babel-plugin-import-graphql or a 网页包加载器 https://github.com/apollographql/graphql-tag#webpack-loading-and-preprocessing

import typeDefs from './type-defs.graphql'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用“apollo-server”加载 .graphql 文件? 的相关文章

随机推荐