How can Gatsby/GraphQL sort an integer field numerically rather than alphabetically?

Viewed 329

I'm building a Gatsby site (v2.24.47) where I pull data from a CSV file with information about pages in a book. This is loaded using gatsby-transformer-csv, and I use custom schema to ensure that the column page_num is transformed into a Int-type field. But it seems as if Gatsby is ordering the field alphabetically rather than numerically. For example, if I query all pages after, say, page 12, it includes page 8 and 9, and indeed just sorting the pages also returns them in alphabetic order. I need the pages to be sorted numerically. Is there a way to do so?

Any help would be much appreciated. I've included a minimal example below.


gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/data/`,
      }
    },
    `gatsby-transformer-csv`
  ],
}

gatsby-node.js

exports.createSchemaCustomization = ({ actions, schema }) => {
    const { createTypes } = actions
    createTypes(`
        type PagesCsv implements Node @dontInfer {
            page_num: Int
        }
    `)
}

data/pages.csv

page_num
8
9
10
11
12
13
14

GraphQL query (in GraphiQL)

query MyQuery {
  allPagesCsv(filter: {page_num: {gt: 12}}) {
    nodes {
      page_num
    }
  }
}

returns

{
  "data": {
    "allPagesCsv": {
      "nodes": [
        {
          "page_num": 8
        },
        {
          "page_num": 9
        },
        {
          "page_num": 13
        },
        {
          "page_num": 14
        }
      ]
    }
  },
  "extensions": {}
}

Similarly, querying allPagesCsv(sort: {fields: page_num}) returns the pages in alphabetic order 10, 11, 12, 13, 14, 8, 9.

0 Answers
Related