Search code examples
javascriptangularjsrestdatecontentful

contentful & javascript: get only entries with fields.date in the future


I'm using contentful as backend for my mobile app.

match fixtures are stored within contentful. I want to query the next match, but i get the following error:

422 (Unprocessable Entity)

My function to retrieve the next match:

function nextOpponent(){
        var content_Type = mainConfig.config.contentType.match // Matches
        var order = "fields.datum";
        var gt = new Date().toLocaleString();
        console.log(gt);
        var query = "content_type=" + content_Type +
            "&order=" + order +
            "&fields.datum%5Bgte%5D=" + encodeURI(gt);

        contentful.entries(query).then(
            //success
            function(response){
                $scope.nextMatch = response.data.items[0];
                console.log($scope.nextMatch);
            },
            //error
            function(response){

            }
        )
    }

Solution

  • The problem you are facing is mostly because of the date string being malformed. Date strings have to follow the ISO-8601 format. You can create such a formatted string by using the build-in JS function Date#toISOString or via your date formatting library of choice. Besides that you can just pass the arguments as an object.

    The following code uses the build-in date method:

    var gt = new Date().toISOString();
    
    contentful.entries({
      content_type: content_Type,
      order: order,
      'fields.datum[gte]': gt
    }).then(function () {
      // go ahead here...
    });
    

    Additional note: Contentful will cache the result of queries based on the requested URLs. So if you don't need a high precision, I would suggest using timestamps which only reflects the current date or the respective hour of the day. E.g. 2015-07-28 or 2015-07-28T15:00