Helidium / Mitol

Lightweight NodeJS http server
Other
175 stars 5 forks source link

Implement stream response #12

Open Helidium opened 6 years ago

Helidium commented 6 years ago

The response object is a plain object. It should extend ReadableStream

brandonros commented 6 years ago
var readBody = function(req) {
  return new Promise(function(resolve, reject) {
    var body = [];

    req.on('data', function(chunk) {
      body.push(chunk);
    });

    req.on('error', function(err) {
      reject(err);
    });

    req.on('end', function() {
      resolve(Buffer.concat(body).toString());
    });
  });
};

var bindServer = function() {
  var server = http.createServer();

  var responseHeaders = {
    'Content-Type': 'application/json'
  };

  server.on('request', async function(req, res) {
    logger.debug(`${process.pid} received request`);

    try {
      var body = JSON.parse(await readBody(req));

      var result = await handleRequest(body);

      res.writeHead(200, responseHeaders);
      res.end(JSON.stringify(result));
    } catch (err) {
      logger.error(err);

      res.writeHead(500, responseHeaders);
      res.end(JSON.stringify({error: err.stack}));
    }
  });

  server.listen(PORT, function() {
    logger.debug(new Date(), `${process.pid} bound to port ${PORT}...`);
  });

  return server;
};

Does this mean you can't read chunks on POST bodies for example?