mercredi 6 octobre 2021

JS Avoid same if statement in multiple locations

I have a function that processes a large list of JSON Documents and inserts them into MongoDB.

I want to log what this function is doing at several locations and then chuck off the payload to S3. However, this is conditional from the callee.

function doStuffWithJSON(options={}) {
    const apiRes = getJSONFromAPI();

    if (options.logAndChuck) { console.log('we got results successfully') }

    //50 lines of code that are unconditionally being executed

    if (options.logAndChuck) { console.log('we did stuff with the result') }

    //Another 50 lines of code that are unconditionally being executed

    if (options.logAndChuck) { sendJsonToS3(apiRes) }
}

The repetitive pattern here is that I have the same if statement at multiple different locations of the function. Not sure if there is any way to avoid this just given the nature of it.

Was wondering if there was any pattern to clean stuff up like this.

Thanks!

Aucun commentaire:

Enregistrer un commentaire