如何使GraphQL突变后自动插入当前UTC?

时间:2018-09-18 11:22:38

标签: mongodb graphql

我的变异代码如下:

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字段。

1 个答案:

答案 0 :(得分:1)

在您的突变中,删除创建的必需项

type Mutation {
  addPost(
    title: String!,
    content: String!,
    // created: DateTime!, changed in next line
    created: DateTime, // no ! means not required
    author_id: String!,
    author_first_name: String!
     author_last_name: String!): Post,
}

然后在您的任务中将其合并到创建的arg中,如果不是

  addPost: async (parent, args) => {
    // if args does not have created, make it here if it is required by task
    const task = fawn.Task();
    task.save(
      dbPost,