【问题标题】:Ouput Datetime fields as string in GraphQL query using Sequelize使用 Sequelize 在 GraphQL 查询中将日期时间字段输出为字符串
【发布时间】:2020-06-08 16:39:09
【问题描述】:

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

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

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 查询时,我总是得到nullcreationDatestartDate 字段。 我想得到的是日期和时间作为 ISO 8601 格式的字符串。

【问题讨论】:

    标签: javascript node.js graphql sequelize.js apollo-server


    【解决方案1】:

    您收到 null 的原因是 Sequelize 返回的对象的属性名称与您的字段名称不匹配(creation_datecreationDate)。详细解释见this post

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

    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()
        },
      },
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多