你不会为Color
。这是一个简单的、可运行的示例:
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);
Run a cars
query ({cars {color}}
) in GraphiQL http://localhost:3000/graphiql您将在我们的数据中看到每辆车返回的颜色。现在,更改其中的一个值data(不是枚举定义)为您未定义的颜色,例如PINK
。再次运行查询,您将看到类似以下的错误消息:
"Expected a value of type \"Color\" but received: PINK"
这也适用于解析器,因此如果我通过为 Car 添加解析器来覆盖数据,如下所示:
Car: {
color: () => 'RED'
}
该查询将显示所有颜色为红色的汽车。如果将解析器返回的值更改为BLACK
,查询将再次出错。
枚举只是强制特定字段解析为的任何值都在您定义的值集中的一种方法。