为Apollo客户端添加自定义标量类型解析器。
在定义自定义标量类型时,通常需要在服务器端和客户端都定义。下面是一个自定义标量类型的示例:
在服务器端(GraphQL schema定义):
scalar Date
type Query {
events: [Event]
}
type Event {
id: ID!
name: String!
date: Date!
}
在客户端(通过Apollo客户端定义):
const client = new ApolloClient({
link: httpLink, // 浏览器HttpLink或HttpLink才能从服务器查询
cache: new InMemoryCache(),
// 添加标量类型的解析器
resolvers: {
Date: new GraphQLScalarType({
name: 'Date',
parseValue(value) {
return new Date(value); // 将从服务器接收的值转换为Date对象
},
serialize(value) {
return value.toISOString(); // 将Date对象序列化为字符串
},
parseLiteral(ast) {
if (ast.kind === Kind.STRING) {
return new Date(ast.value); // 将GraphQL AST解析为Date对象
}
return null;
},
}),
},
});
在此示例中,我们使用GraphQLScalarType定义了一个名为Date的标量类型,并在Apollo客户端中添加了该类型的解析器。在解析器中,我们将从服务器接收的值转换为Date对象,并将Date对象序列化为字符串,以便GraphQL可以正确处理它。使用parseLiteral方法,我们可以将GraphQL AST解析为Date对象。
然后,在客户端中,我们就可以正常查询到自定义标量类型了:
const GET_EVENTS = gql`
{
events {
id
name
date
}
}
`;
function Events() {
const { loading, error, data } = useQuery(GET_EVENTS);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return data.events.map(event => (
{event.name}
{event.date.toLocaleString()}
));
}