node-run-middleware icon indicating copy to clipboard operation
node-run-middleware copied to clipboard

async/await usage

Open thebleucheese opened this issue 6 years ago • 2 comments

Just in case anyone's using this and trying to run in modern Node, the callbacks aren't standard so promisify requires some work to get it behaving.

Not perfect but it's a start if you're trying to reuse connect style middleware with direct calls in something like a cron.

    require('run-middleware')(server);

    server.runMiddleware[util.promisify.custom] = (path, options) => {
        return new Promise((resolve, reject) => {
            server.runMiddleware(path, options, function (code,data,headers) {
                let payload = {code: code, data: data, headers: headers};
                resolve(payload);
            });
        });
    };

    const runMiddlewarePromise = util.promisify(server.runMiddleware);

    const runMiddlewareAsync = async (path, options) => {
        try {
            const middlewareRes = await runMiddlewarePromise(path, options);
            return middlewareRes;
        } catch(e) {
            console.error("NOT IMPLEMENTED: ", e);
            return false;
        }
    };

    // ======= Execute with the following ==============
    let resTest = await runMiddlewareAsync('/my/url',{
                    secure: true,
                    connection: {},
                    method:'GET'                    
                });

    console.log("res Test: ", resTest);

thebleucheese avatar Aug 21 '18 04:08 thebleucheese

Thanks. Can you create a pull request?

Aminadav avatar Feb 23 '19 22:02 Aminadav

Ultimately it makes more sense to just use node-fetch if your use case is for emulation, ends up being simpler

kaansoral avatar Jan 23 '21 16:01 kaansoral