Monitoring an expiry date

In case it’s useful to anyone else, here’s a script I use to monitor an expiry date or some other due date. The script assumes a single row dataset, with a column containing a date.

/*
Example config:
{
    columnName: "expiry",
    errorDays: 60,
    warningDays: 30
}
*/
async function getState(params, api) {

    if(!params.config.columnName || typeof params.config.columnName !== 'string') { throw new Error("Missing config property: columnName (string)") }
    if(!params.config.errorDays || typeof params.config.errorDays !== 'number') { throw new Error("Missing config property: errorDays (number)") }

    const column = await api.getColumnData(params.data, params.config.columnName);

    if (!column) { throw new Error(`Column ${params.config.columnName} not found`)}
    if (column.length === 0) { throw new Error(`Data contains no rows`)}

    let date = column[0].value;

    if(!(date instanceof Date)) {
        if(typeof date === 'string' ) {
            date = new Date(date);
            if (date === NaN) {
                throw new Error(`Value in column ${params.config.columnName} is not a valid date string`)    
            } 
        }
        else {
            throw new Error(`Value in column ${params.config.columnName} is not of type Date or string`)
        }
    }

    const daysFromNow = (date.valueOf() - Date.now()) / (1000 * 60 * 60 * 24);

    if (daysFromNow < params.config.errorDays) return {state: 'error'};
    if (daysFromNow < params.config.warningDays) return {state: 'warning'};

    return { state: 'success' }
}
1 Like