本文介绍了如何使用 graphql-tools 使用或解析枚举类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 graphql-tools 文档中找不到任何地方应该如何在提供给 makeExecutableSchema 的模式中使用 enum 类型.有人知道这是怎么做到的吗?

I cannot find anywhere in the graphql-tools documentation how one should go about utilizing enum types in schemas that are fed to makeExecutableSchema. Anyone have a clue how this done?

示例代码:

enum Color {
  RED
  GREEN
  BLUE
}

type Car {
  color: Color!
}

Color 的解析器是什么样的?

What would the resolver for Color look like?

推荐答案

您不会为 Color 编写解析器.这是一个简单的、可运行的示例:

You wouldn't write a resolver for Color. Here's a simple, runnable example:

const bodyParser = require('body-parser');
const { graphqlExpress, graphiqlExpress } = require('graphql-server-express');
const { makeExecutableSchema } = require('graphql-tools');
const app = require('express')();

const carsData = [
  {color: 'RED'},
  {color: 'GREEN'},
  {color: 'BLUE'},
];

const typeDefs = `
  enum Color {
    RED
    GREEN
    BLUE
  }
  type Car {
    color: Color!
  }
  type Query {
    cars: [Car!]!
  }
`;

const resolvers = {
  Query: {
    cars: () => carsData,
  }
};

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));

app.listen(3000);

cars 查询 ({cars {color}})>GraphiQL,您将在我们的数据中看到为每辆车返回的颜色.现在,将 data 中的一个值(不是 Enum 定义)更改为您未定义的颜色,例如 PINK.再次运行查询,您将看到如下错误消息:

Run a cars query ({cars {color}}) in GraphiQL and you will see a color returned for each car in our data. Now, change one of the values in the data (not the Enum definition) to a color you didn't define, like PINK. Run the query again and you will see an error message like:

"Expected a value of type "Color" but received: PINK"

这也适用于解析器,所以如果我通过为 Car 添加解析器来覆盖数据,如下所示:

This works with resolvers too, so if I override the data by adding a resolver for Car like this:

Car: {
  color: () => 'RED'
}

查询将显示所有颜色为红色的汽车.如果将解析器返回的值更改为 BLACK,查询将再次出错.

The query will show all the cars with RED as their color. If you change the value returned by the resolver to BLACK, the query will error out again.

枚举只是强制特定字段解析为的任何值都在您定义的值集内的一种方式.

Enums are just a way of enforcing that whatever value a particular field resolves to is within the set of values you define.

这篇关于如何使用 graphql-tools 使用或解析枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:57