How to query date range in gatsby graphql?

2019-07-20 04:09发布

问题:

So i have this query in graphql. But greater than(gt) and less than(lt) is not a defined field.

query Test {
  allStrapiEvent(filter:{date:{gt:"02/13/2019"}}){
    edges{
      node{
        name
        date(formatString:"MM/DD/YYYY")
      }
    }
  } 
}

回答1:

It looks like date is of String type, and therefore doesn't get the comparison operators (gt, lt, gte, lte); which is a shame, because this is really useful.

I think as a workaround, you can add an additional field like timestamp and store the date in number (if not already provided by your CMS). Then you can use comparison operators on them.

// moment.js comes with gatsby
const moment = require('moment');

exports.onCreateNode = ({ node, actions }) => {
  const { createNodeField } = actions

  // I'm guessing your type is StrapiEvent, but it could be st else
  if (node.internal.type === `StrapiEvent`) {
    const date = node.date;

    createNodeField({
      name: 'timestamp',
      node,
      // convert date to unix timestamp & convert to number
      value: +moment(date).format('X'),
    })
  }
}

Then say you want to get events starting from yesterday. You can get the unix timestamp like moment().subtract(1, 'day').format('X') // 1549044285

query Test {
  allStrapiEvent(filter: {
    fields: {
      timestamp: {
        gt: 1549044285
      }
    }
  }) {
    edges{
      node{
        name
        date(formatString:"MM/DD/YYYY")
      }
    }
  } 
}

Not ideal, but will work.