HTTP2 push for Express

525 Views Asked by At

I'm trying to set up HTTP2 for an Express app I've built. As I understand, Express does not support the NPM http2 module, so I'm using SPDY. Here's how I'm thinking to go about it-I'd appreciate advice from people who've implemented something similar.

1) Server setup-I want to wrap my existing app with SPDY, to keep existing routes. Options are just an object with a key and a cert for SSL.

const app = express();
...all existing Express stuff, followed by:

spdy
    .createServer(options, app)
    .listen(CONFIG.port, (error) => {
    if (error) {
        console.error(error);
        return process.exit(1)
    } else {
        console.log('Listening on port: ' + port + '.')
    }
});

2) At this point, I want to enhance some of my existing routes with a conditional PUSH response. I want to check to see if there are any updates for the client making a request to the route (the client is called an endpoint, and the updates are an array of JSON objects called endpoint changes,) and if so, push to the client.

My idea is that I will write a function which takes res as one of its parameters, save the endpoint changes as a file (I haven't found a way to push non-file data,) and then add them to a push stream, then delete the file. Is this the right approach? I also notice that there is a second parameter that the stream takes, which is a req/res object-am I formatting it properly here?

const checkUpdates = async (obj, res) => {
    if(res.push){
        const endpointChanges = await updateEndpoint(obj).endpointChanges;
        if (endpointChanges) {
            const changePath = `../../cache/endpoint-updates${new Date().toISOString()}.json`;
            const savedChanges = await jsonfile(changePath, endpointChanges);
            if (savedChanges) {
                let stream = res.push(changePath, {req: {'accept': '**/*'}, res: {'content-type': 'application/json'}});

                stream.on('error', function (err) {
                    console.log(err);
                });

                stream.end();
                res.end();
                fs.unlinkSync(changePath);
            }
        }
    }
};

3) Then, within my routes, I want to call the checkUpdates method with the relevant parameters, like this:

router.get('/somePath', async (req, res) => {
    await checkUpdates({someInfo}, res);
    ReS(res, {
            message: 'keepalive succeeded'
        }, 200);
    }
);

Is this the right way to implement HTTP2?

0

There are 0 best solutions below