知海

JavaScript:GraphQL Helix(服务端)

graphql-github-io-zh-Hans生态项目与库

JavaScript:GraphQL Helix(服务端)

GraphQL Helix 是一组实用函数,用于构建你自己的 GraphQL HTTP 服务器。该项目托管在 GitHub 上,可通过 npm 安装(包名为 graphql-helix)。你可以阅读 DEV 上的教程 使用 GraphQL Helix 构建 GraphQL 服务器 来获得详细的入门指导。

快速开始

运行一个 hello world 服务器,首先安装依赖:

bash 复制代码
npm install graphql graphql-helix express

然后在 server.js 中写入以下代码,并执行 node server.js

js 复制代码
const express = require('express');
const {
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLString
} = require('graphql');
const {
  getGraphQLParameters,
  processRequest,
  renderGraphiQL,
  shouldRenderGraphiQL
} = require('graphql-helix');

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      hello: {
        type: GraphQLString,
        resolve: () => 'Hello world!',
      },
    },
  }),
});

const app = express();

app.use(express.json());

app.use('/graphql', async (req, res) => {
  const request = {
    body: req.body,
    headers: req.headers,
    method: req.method,
    query: req.query,
  };

  if (shouldRenderGraphiQL(request)) {
    res.send(renderGraphiQL());
  } else {
    const { operationName, query, variables } = getGraphQLParameters(request);

    const result = await processRequest({
      operationName,
      query,
      variables,
      request,
      schema,
    });

    if (result.type === 'RESPONSE') {
      result.headers.forEach(({ name, value }) => res.setHeader(name, value));
      res.status(result.status);
      res.json(result.payload);
    } else {
      // graphql-helix 也支持订阅和增量交付(即 @defer 和 @stream 指令)
      // 开箱即用。参见仓库中实现这些功能的更完整示例。
    }
  }
});

app.listen(4000, () =>
  console.log('Now browse to http://localhost:4000/graphql')
);

这个示例使用了 Express,但 GraphQL Helix 是框架无关且运行时无关的——它可以在 Node.js、Deno 和浏览器中运行。GraphQL Helix 为你提供了一套工具函数来构建你自己的 HTTP 服务器,但最终的具体实现细节由你决定。

帮助我们改进文档

发现翻译问题或内容错误?请告诉我们。