简体   繁体   中英

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?

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:

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:

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. What I would like to get is the date and time as a string in the ISO 8601 format.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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