Sunday, March 13, 2016

How to send result of an yield on a promise as a stream in express 4?

Leave a Comment

Is there a way i could send the result of yielding a promise as a steam?

The json payload in some cases will be huge, it would make sense sending it as a stream.

function aPromise() {     // result of a postgres query. Using `pg`     return Promise.resolve({         'data': [1, 2 ,3]     }   }); }  //express 4 router let wrap = require('co-express');  router.get('/', wrap(function* (req, res, next) {     let payload;      try {         payload = yield aPromise();     } catch (e) {         return next(e);     }      res.json(payload); }));  

1 Answers

Answers 1

If you're fetching and loading into memory the whole object of your response, it's going to be hard to then reasonably turn it into streaming again. Anyway, streaming JSON implementation is needed here.

You'd have to share more details about how you're fetching the data. The choice of reasonable solution depends on this entirely.

Here's two examples of how you can make it work, where I made some assumptions:

  1. You are capable of creating a stream of tuples like this: [key, data] for each key you want to put in the resulting json being sent out. This assumes your data is a lot of keys.

    res.set('content-type', 'application/json'); keystream.pipe(JSONStream.stringifyObject()).pipe(res)

  2. You are capable of creating a stream of objects that you want to return as items in an array for the final json response.

    res.set('content-type', 'application/json'); itemsstream.pipe(JSONStream.stringify()).pipe(res)

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment