GraphQL query时返回指定格式的DateTime

版权声明:本文为Martin原创文章,未经Martin允许不得转载。 https://blog.csdn.net/qq_36279445/article/details/88736852

would it be possible to do dates in ISOString format? (011-10-05T14:48:00.000Z)

前端老哥要ISO的,那我就给他ISO的

post.graphql



type Post {
  # ...
  createdAt: String @date
  updatedAt: String @date
}
// ====================================================
//
// This file is part of the Martin.
//
// Create by Martin
// Copyright (c) 2019 Martin
//
// ====================================================

import { SchemaDirectiveVisitor } from 'apollo-server-express';
import { GraphQLField, defaultFieldResolver, GraphQLString } from 'graphql';
import moment = require('moment');

export class DateFormatDirective extends SchemaDirectiveVisitor {
  public visitFieldDefinition(field: GraphQLField<any, any>) {
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async (...args) => {
      const date = await resolve.apply(this, args);
      return moment(date).toISOString();
    };
    // The formatted Date becomes a String, so the field type must change:
    field.type = GraphQLString;
  }
}

schemaDirectives 里面引用一下

看下文档:https://github.com/apollographql/graphql-tools/blob/master/docs/source/schema-directives.md

猜你喜欢

转载自blog.csdn.net/qq_36279445/article/details/88736852
今日推荐