Skip to content

Commit f240f43

Browse files
committed
fix(hukk): not parse the plain text string
it only parse the json data, this fix will making it able to parse any string
1 parent ddb0905 commit f240f43

File tree

2 files changed

+37
-10
lines changed

2 files changed

+37
-10
lines changed

src/hukk.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,9 @@ export class Hukk {
4949
body += data;
5050
});
5151
req.on('end', () => {
52+
const bodyData = {body: this._jsonOrText(body)}
5253
res.writeHead(200, {'Content-Type': 'application/json'});
53-
this._runHook(req, JSON.parse(body), (err: any, data: any) => {
54+
this._runHook(req, bodyData, (err: any, data: any) => {
5455
if (err) {
5556
this._responseError(res, err.message);
5657
}
@@ -81,6 +82,15 @@ export class Hukk {
8182
}
8283
}
8384

85+
private _jsonOrText(str: string) {
86+
try {
87+
const json = JSON.parse(str)
88+
return json
89+
} catch (err) {
90+
return str
91+
}
92+
}
93+
8494
private _responseData(res: ServerResponse, data: any) {
8595
const result = JSON.stringify(data);
8696
res.end(result);

tests/hukk.test.ts

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ const sendRequest = (
3434
req.end();
3535
};
3636

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

5253
it('hook response what it received', done => {
5354
const handle = (body: any) => {
54-
return body
55-
}
56-
hukk.register({endpoint: '/another-webhook', handle})
57-
sendRequest('/another-webhook', postData, (err, data) => {
58-
expect(data).toEqual(postData)
59-
done()
60-
})
61-
})
55+
return body;
56+
};
57+
hukk.register({endpoint: '/another-webhook', handle});
58+
sendRequest('/another-webhook', postData, (err, responseData) => {
59+
const compareTo = JSON.parse(JSON.stringify({body: data}))
60+
const compareFrom = JSON.parse(responseData)
61+
expect(compareFrom).toEqual(compareTo);
62+
done();
63+
});
64+
});
65+
66+
it('hook response with plain text', done => {
67+
const text = 'plain text string'
68+
const handle = (body: any) => {
69+
return body;
70+
};
71+
hukk.register({endpoint: '/another-webhook', handle});
72+
sendRequest('/another-webhook', text, (err, responseData) => {
73+
const compareTo = JSON.parse(JSON.stringify({body: text}))
74+
const compareFrom = JSON.parse(responseData)
75+
expect(compareFrom).toEqual(compareTo);
76+
done();
77+
});
78+
});
6279

6380
afterAll(done => {
6481
hukk.close(done);

0 commit comments

Comments
 (0)