【发布时间】:2019-02-22 10:13:01
【问题描述】:
我的变异代码如下所示:
Mutation: {
addPost: async (parent, args) => {
// Add new post to dbPosts
const task = fawn.Task();
task.save(
dbPost,
{
_id: new mongoose.Types.ObjectId(),
title: args.title,
content: args.content,
created: args.created,
author: {
id: args.author_id,
first_name: args.author_first_name,
last_name: args.author_last_name,
}
}
);
}
}
我正在使用的架构定义为:
scalar DateTime
type Query {
posts: [Post],
post(id: ID!): Post,
}
type Mutation {
addPost(
title: String!,
content: String!,
created: DateTime!,
author_id: String!,
author_first_name: String!
author_last_name: String!): Post,
}
type Post {
id: ID!
title: String!,
content: String!,
author: Author!,
created: DateTime,
}
显然,我还使用自定义标量来处理日期/时间值。这个自定义标量 DateTime 解析为:
const { GraphQLScalarType } = require('graphql/type');
const tmUTC = () => {
const tmLoc = new Date();
return tmLoc.getTime() + tmLoc.getTimezoneOffset() * 60000;
};
DateTime = new GraphQLScalarType({
name: 'DateTime',
description: 'Date/Time custom scalar type',
parseValue: () => { // runs on mutation
return tmUTC();
},
serialize: (value) => { // runs on query
return new Date(value.getTime());
},
parseLiteral: () => {
return tmUTC();
},
});
module.exports = DateTime;
现在这工作正常,我可以按预期插入和检索带有时间戳的条目。但是,我仍然需要为 created 字段传递一个虚拟参数,以便 DateTime 解析器启动:
mutation{
addPost(
title: "Ghostbusters",
content: "Lots and lots of ghosts here...",
created: "",
author_id: "5ba0c2491c9d440000ac8fc3",
author_first_name: "Bill",
author_last_name: "Murray"
){
title
content
id
created
}
}
我什至可以将该字段留空,但仍会记录时间。但我不能把它放在我的突变调用中。有什么办法可以做到这一点?这里的目标是让 GraphQL 自动执行 DateTime 解析器,而无需用户在突变调用中显式输入 created 字段。
【问题讨论】: