Skip to content

Commit

Permalink
feat(sifrr-server): add body helpers in put, patch requests
Browse files Browse the repository at this point in the history
  • Loading branch information
aadityataparia committed Jan 28, 2020
1 parent 44de3ac commit 7cb2861
Showing 1 changed file with 45 additions and 20 deletions.
65 changes: 45 additions & 20 deletions packages/server/sifrr-server/src/server/baseapp.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,32 @@ const contTypes = ['application/x-www-form-urlencoded', 'multipart/form-data'];
const noOp = () => true;
const { stob } = require('./utils');

const handleBody = (res, req) => {
const contType = req.getHeader('content-type');

res.bodyStream = function() {
const stream = new Readable();
stream._read = noOp;

this.onData((ab, isLast) => {
// uint and then slicing is bit faster than slice and then uint
stream.push(new Uint8Array(ab.slice(ab.byteOffset, ab.byteLength)));
if (isLast) {
stream.push(null);
}
});

return stream;
};

res.body = () => stob(res.bodyStream());

if (contType.indexOf('application/json') > -1)
res.json = async () => JSON.parse(await res.body());
if (contTypes.map(t => contType.indexOf(t) > -1).indexOf(true) > -1)
res.formData = formData.bind(res, contType);
};

class BaseApp {
_staticPaths = new Map();
_watched = new Map();
Expand Down Expand Up @@ -101,29 +127,28 @@ class BaseApp {
if (typeof handler !== 'function')
throw Error(`handler should be a function, given ${typeof handler}.`);
this._post(pattern, (res, req) => {
const contType = req.getHeader('content-type');

res.bodyStream = function() {
const stream = new Readable();
stream._read = noOp;

this.onData((ab, isLast) => {
// uint and then slicing is bit faster than slice and then uint
stream.push(new Uint8Array(ab.slice(ab.byteOffset, ab.byteLength)));
if (isLast) {
stream.push(null);
}
});
handleBody(res, req);
handler(res, req);
});
return this;
}

return stream;
};
put(pattern, handler) {
if (typeof handler !== 'function')
throw Error(`handler should be a function, given ${typeof handler}.`);
this._put(pattern, (res, req) => {
handleBody(res, req);

res.body = () => stob(res.bodyStream());
handler(res, req);
});
return this;
}

if (contType.indexOf('application/json') > -1)
res.json = async () => JSON.parse(await res.body());
if (contTypes.map(t => contType.indexOf(t) > -1).indexOf(true) > -1)
res.formData = formData.bind(res, contType);
patch(pattern, handler) {
if (typeof handler !== 'function')
throw Error(`handler should be a function, given ${typeof handler}.`);
this._patch(pattern, (res, req) => {
handleBody(res, req);

handler(res, req);
});
Expand Down

0 comments on commit 7cb2861

Please sign in to comment.