使用 Sequelize 在 GraphQL 查询中将日期时间字段输出为字符串

Ouput Datetime fields as string in GraphQL query using Sequelize

在使用 Sequelize 获取数据时,如何让 MySQL 日期时间字段在 GraphQL 查询中作为字符串输出?

这是我的 table 的(简化)结构:

CREATE TABLE `things` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `start_date` datetime DEFAULT NULL,
  `creation_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

这是我的(简化的)Sequelize 模型:

module.exports = function(sequelize, DataTypes) {
    return sequelize.define('things', {
        id: {
            type: DataTypes.INTEGER(10).UNSIGNED,
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        start_date: {
            type: DataTypes.DATE,
            allowNull: true
        },
        creation_date: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: sequelize.literal('CURRENT_TIMESTAMP')
        },
    }, {
        tableName: 'things',
        timestamps: false
    });
};

这是我的 GraphQL 架构定义:

import { gql } from 'apollo-server-express'
import * as db from '../database'

export const typeDefs = gql`
    extend type Query {
        things: [Thing]
    }

    type Thing {
        id: ID!
        creationDate: String
        startDate: String
    }
`

export const resolvers = {
    Query: {
        things: async () => db.things.findAll(),
    },
}

当我 运行 things 查询时,对于 creationDatestartDate 字段,我总是得到 null。 我想要得到的是 ISO 8601 格式的字符串形式的日期和时间。

您收到 null 的原因是因为 Sequelize 返回的对象上的 属性 名称与您的字段名称不匹配(creation_datecreationDate)。有关详细说明,请参阅

无论如何,您仍然需要提供自定义解析器才能格式化日期。没有它,您最终会得到纪元日期。您需要执行以下操作:

const resolvers = {
  Thing: {
    creationDate: (thing) => {
      // thing is an instance of your Sequelize model
      // thing.creation_date is an instance of Date
      return thing.creation_date.toISOString()
    },
  },
}