The IML that will solve all your date formatting issues once and for all!

If you have developed an app in the past, you probably know that you need to set date fields as such, allowing users to enter any valid date format. The responsibility is on us, the app developers to make sure those date fields are formatted according to the API documentation of the app your are developing.

The old way of solving this would be to omit the date fields from the body like so:

{
    "url": "/invApi/createDoc",
    "method": "POST",
    "body": {
        "{{...}}": "{{omit(parameters,'dateField'))}}",
        "dateField": "{{formatDate(parameters.dateField,'YYYY-MM-DD')}}"
    },
    "response": {
        "output": "{{body}}"
    }
}

This is fine if you have just one or two fields. The problem starts when you have a complex structure that is sometimes dynamic such as object arrays containing date fields.

The new way to solve this is a recursive IML function that only requires you to add the parameter names in an array and set your output format. In this example ive added 5 fields, so no matter how many times they show up or where in the body, they will be formatted:

function traverseAndFormatDates(parameters) {
    const dateParameters = ["ValueDate", "ExtraDate1", "ExtraDate2", "DueDate", "DatF3", "DUEDATE"];
    Object.entries(parameters).forEach((entry) => {
            const [key, value] = entry;
            if(dateParameters.includes(key)){
                parameters[key] = iml.formatDate(parameters[key], 'YYYY-MM-DD');
            }else if(value && typeof value === 'object') {
                parameters[key] = iml.traverseAndFormatDates(value);
            }        
        })
    return parameters;
}

So instead of using omit and handling each field individually, the communication module looks like this:

{
    "url": "/invApi/createDoc",
    "method": "POST",
    "body": {
        "{{...}}": "{{traverseAndFormatDates(parameters)}}"
    },
    "response": {
        "output": "{{body}}"
    }
}

I hope you guys can make use of this as I have, if anyone has any questions dont hesitate to contact me.

I would like to thank @AlexChekalov for helping me to make this code work, your rock!

3 Likes