Search code examples
node.jsodatasap-business-bydesign

How to add a date time filter for odata using o.js


I'm using this npm package : o.js to manipulate oData service

I'm trying to fetch an entity, but I want to add a filter : get only where the LastChangeDateTime is greater than the past five minutes

what I am doing wrong?

The query :

 static async fetchRecentProjectTasks(odataHandler) {
        var pastFiveMinutes = moment().subtract(5, 'minutes').format();
        return await odataHandler.get('ProjectTaskCollection').query({
            $filter: `LastChangeDateTime ge datetime'${pastFiveMinutes}'`,
            $top: parseInt(20000),
            $select: "ObjectID,LastChangeDateTime",
            $orderby: "ObjectID",
            $format: 'json'
        });
    }

This is the output of the request :

https://xxx.xxx.com/sap/byd/odata/cust/v1/odata_project/ProjectTaskCollection?%24filter=LastChangeDateTime+ge+datetime%272021-01-10T18%3A04%3A35-05%3A00%27&%24top=20000&%24select=ObjectID&%24orderby=ObjectID&%24format=json

Error :

{"error":{"code":"","message":{"lang":"en","value":"Invalid parametertype used at function 'ge'"}}}

Solution

  • I've solved it by trying a different approach of string concatenation, and I've used the datetimeoffset while formatting the date to toISOString()

      static async fetchRecentProjectTasks(odataHandler) {
            var pastFiveMinutes = moment().subtract(5, 'minutes').toISOString();
            return await odataHandler.get('ProjectTaskCollection').query({
                $top: parseInt(20000),
                $filter: "LastChangeDateTime ge datetimeoffset'" + pastFiveMinutes + "'",
                $select: "ObjectID,ID,Name,EarliestPlannedStartDateTime,EarliestPlannedEndDateTime,LastChangeDateTime,ProjectTaskService",
                $orderby: "ObjectID",
                "$expand": "ProjectTaskService,ProjectTaskService/ServiceProductDescription,ProjectTaskService/ProjectTaskServicePeriodPlan",
                $format: 'json'
            }).catch(err => {
                console.log(err.url);
            });
        }
    

    I don't understand what was wrong in the first query but whatever, as long as it works