和其他许多人一样,我正在尝试使用 GraphQL 和 JavaScript 创建自己的
Date
标量。我读过很多例子,并特别遵循了 来自 apollo 的指南。
我做了什么scalar Date
添加到我的架构中
GraphQLScalarType
的实例。我称该实例为
dateScalar
Date
的新属性,其值为
dateScalar
Date
准备好根据我所读到的内容进行使用。但是,每次执行查询时得到的值与我存储在数据库中的值完全相同。如果那是一个字符串,我会看到一个字符串,如果那是一个数字,我会看到一个数字。它在任何时候都不会被解析或序列化。这就是我的文件的样子。
schema.js
const { buildSchema } = require('graphql');
const schema = buildSchema(`
scalar Date
# more schema
`);
module.exports = schema;
root.js
const { dateScalar } = require('./customScalars');
const root = {
// queries
// mutations
// scalars
Date: dateScalar
};
module.exports = root;
自定义标量.js
const { GraphQLScalarType } = require('graphql');
const dateScalar = new GraphQLScalarType({
name: 'Date',
description: 'This is a scalar version of the js Date',
serialize(value) {
console.log('call serialize');
return value.getTime();
},
parseValue(value) {
console.log('call parseValue');
return new Date(value).getFullYear();
},
parseLiteral(ast) {
console.log('call parseLiteral');
return;
}
});
module.exports = {
dateScalar
};
服务器.js
const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./graphql/schema.js');
const graphqlRoot = require('./graphql/root.js');
var app = express();
app.use('/endpoint', graphqlHTTP({
schema: schema,
graphiql: true,
rootValue: graphqlRoot,
}));
app.listen(3333, () => console.log('Now browse to localhost:3333/endpoint'));
到目前为止我的调试
serialize
等,但没有一个被调用。
Date
属性,并且行为完全相同
dateScalar
的实例是否符合我的预期。我通过在将其导入不同文件后调用
console.log(dateScalar.serialize(new Date().getTime()))
来完成此操作。执行此操作时,我收到日志告诉我调用了序列化,结果正是我所期望的。
我的猜测是 GraphQL 正在使用
.toString()
进行序列化和解析,因为它找不到我的序列化/解析实现。
关于如何让 GraphQL 使用我的自定义标量有什么想法吗?
graphql-tools
制作可执行模式并使用
apollo-server-express
而不是
express-graphql
express-graphql
。所以我的解决方案需要用
apollo-server-express
替换它。幸运的是,它不需要太多改变。这对我有用,需要进行一些修改以匹配您的代码。
首先安装软件包:
npm install apollo-server-express graphql-tools
const {makeExecutableSchema} = require('graphql-tools')
const {graphqlExpress} = require('apollo-server-express');
const graphqlRoot = require('./graphql/root.js');
//...
const schemaDef = `
scalar Date
# more schema
`;
//build the schema
const schema = makeExecutableSchema({
typeDefs: [schemaDef],
resolvers: graphqlRoot
});
// your new endpoint:
app.use('/endpoint', bodyParser.json(), graphqlExpress({ schema }));
了解更多关于此外,使用 Apollo,可以轻松拥有多个架构文件和解析器文件,而不必担心手动组合它们。以下是文档中的解释: