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

问题描述 投票:0回答:3

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

node.js graphql apollo apollo-server
3个回答
1
投票

如果你把你的类型定义在一个 .graphql 文件,你可以通过以下几种方式之一来读取它。

1.) 自己读取文件。

const { readFileSync } = require('fs')

const typeDefs = readFileSync('./type-defs.graphql')

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'

1
投票

当年我写了一个小小的 .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... `;

0
投票

用这个方法解决了 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]!
}
© www.soinside.com 2019 - 2024. All rights reserved.