简体   繁体   English

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

[英]Ouput Datetime fields as string in GraphQL query using Sequelize

How can I get the MySQL datetime fields to be outputted as strings in a GraphQL query, when fetching the data with Sequelize?使用 Sequelize 获取数据时,如何将 MySQL 日期时间字段作为 GraphQL 查询中的字符串输出?

Here's the (simplified) structure of my 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;

Here is my (simplified) Sequelize model:这是我的(简化的)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
    });
};

And here is my GraphQL schema definition:这是我的 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(),
    },
}

When I run the things query, I always get null for the creationDate and startDate fields.当我运行things查询时,我总是为creationDatestartDate字段获取null What I would like to get is the date and time as a string in the ISO 8601 format.我想得到的是日期和时间作为 ISO 8601 格式的字符串。

The reason you are receiving null is because the property name on the object returned by Sequelize doesn't match the name of your field ( creation_date vs creationDate ).您收到 null 的原因是 Sequelize 返回的对象上的属性名称与您的字段名称不匹配( creation_datecreationDate )。 See this post for a detailed explanation.有关详细说明,请参阅此帖子

Regardless, you'll still need to provide a custom resolver in order to format the date.无论如何,您仍然需要提供自定义解析器来格式化日期。 Without it, you'll end up with the epoch date instead.没有它,你最终会得到纪元日期。 You'll want to do something like:你会想要做这样的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM