Skip to content

Commit

Permalink
fix(hukk): not parse the plain text string
Browse files Browse the repository at this point in the history
it only parse the json data, this fix will making it able to parse any string
  • Loading branch information
nampdn committed Nov 19, 2018
1 parent ddb0905 commit f240f43
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 10 deletions.
12 changes: 11 additions & 1 deletion src/hukk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ export class Hukk {
body += data;
});
req.on('end', () => {
const bodyData = {body: this._jsonOrText(body)}
res.writeHead(200, {'Content-Type': 'application/json'});
this._runHook(req, JSON.parse(body), (err: any, data: any) => {
this._runHook(req, bodyData, (err: any, data: any) => {
if (err) {
this._responseError(res, err.message);
}
Expand Down Expand Up @@ -81,6 +82,15 @@ export class Hukk {
}
}

private _jsonOrText(str: string) {
try {
const json = JSON.parse(str)
return json
} catch (err) {
return str
}
}

private _responseData(res: ServerResponse, data: any) {
const result = JSON.stringify(data);
res.end(result);
Expand Down
35 changes: 26 additions & 9 deletions tests/hukk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ const sendRequest = (
req.end();
};

const postData = JSON.stringify({action: 'test', foo: 'bar'});
const data = {action: 'test', foo: 'bar'};
const postData = JSON.stringify(data);
describe('hukk', () => {
beforeAll(done => {
hukk.listen(testPort, done);
Expand All @@ -51,14 +52,30 @@ describe('hukk', () => {

it('hook response what it received', done => {
const handle = (body: any) => {
return body
}
hukk.register({endpoint: '/another-webhook', handle})
sendRequest('/another-webhook', postData, (err, data) => {
expect(data).toEqual(postData)
done()
})
})
return body;
};
hukk.register({endpoint: '/another-webhook', handle});
sendRequest('/another-webhook', postData, (err, responseData) => {
const compareTo = JSON.parse(JSON.stringify({body: data}))
const compareFrom = JSON.parse(responseData)
expect(compareFrom).toEqual(compareTo);
done();
});
});

it('hook response with plain text', done => {
const text = 'plain text string'
const handle = (body: any) => {
return body;
};
hukk.register({endpoint: '/another-webhook', handle});
sendRequest('/another-webhook', text, (err, responseData) => {
const compareTo = JSON.parse(JSON.stringify({body: text}))
const compareFrom = JSON.parse(responseData)
expect(compareFrom).toEqual(compareTo);
done();
});
});

afterAll(done => {
hukk.close(done);
Expand Down

0 comments on commit f240f43

Please sign in to comment.