Aminadav / node-run-middleware

NodeJS Express module to simulate URL requests, for internal executing REST API's
https://github.com/aminag/node-run-middleware
ISC License
65 stars 22 forks source link

async/await usage #23

Open thebleucheese opened 6 years ago

thebleucheese commented 6 years ago

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);
Aminadav commented 5 years ago

Thanks. Can you create a pull request?

kaansoral commented 3 years ago

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