【问题标题】:How to make GraphQL automatically insert current UTC upon mutation?如何使 GraphQL 在突变时自动插入当前的 UTC?
【发布时间】: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 字段。

【问题讨论】:

    标签: mongodb graphql


    【解决方案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,
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 2021-09-22
      • 2019-04-14
      • 2020-01-17
      • 2012-03-15
      相关资源
      最近更新 更多