Search code examples
reactjsgraphqlmarkdowngatsbynetlify

GraphQL transforming time field to number


I have content in markdown files (generated in netlify cms) that looks like this:

enter image description here enter image description here

I'm not sure if the syntax highlighter in vs code is treating the values of startTime and endTime or if this is something with markdown itself or the way it is being created in netlify cms.

But either way graphQL seems to read one as a number and the other as a string:

enter image description here

I tried to create type definitions in gatsby-node.js as follows but when I check the console output I see that it is too late and it is been given the values 1200 and 1080 instead of 18:00 and 20:00

exports.createSchemaCustomization = ({ actions, schema }) => {
    const { createTypes } = actions
    const typeDefs = [
        schema.buildObjectType({
            name: 'MarkdownRemark',
            fields: {
                frontmatter: 'Frontmatter!'
            },
            interfaces: ['Node'],
            extensions: {
                infer: true,
            },
        }),
        schema.buildObjectType({
            name: 'Frontmatter',
            fields: {
                startTime: {
                    type: 'String!',
                    resolve(parent) {
                        console.log(parent.startTime);
                        return `${parent.startTime}`;
                    }
                },
                endTime: {
                    type: 'String!',
                    resolve(parent) {
                        console.log(parent.endTime);
                        return `${parent.endTime}`;
                    }
                }
            }
        }),
    ]
    createTypes(typeDefs)
}

Is there some way I can specify in Netlify's config.yml not to treat this field as a number? Or am I looking in the wrong place?

This is how I declare the fields in config.yml:

- { label: "Start Time", name: startTime, widget: string}
- { label: "End Time", name: endTime, widget: string}

But now when I look in github I see some very strange results:

enter image description here


Solution

  • In your config.yml use the datetime widget and the format options provided by Netlify:

    - { name: startTime, label: "Start Time", widget: datetime, date_format: MM/DD/YYYY, time_format: false, format: L }
    - { name: endTime, label: "EndTime", widget: datetime, date_format: MM/DD/YYYY, time_format: false, format: L },
    

    Change your date_format(MM/DD/YYYY) for any desired format.

    Keep in mind that Netlify datetime widget uses momentjs, check their format options to get one that fits you.