Skip to content

Commit 69d7183

Browse files
committed
fix(twilio-run): correctly serialize JSON Responses
Fixes #276
1 parent a5d948e commit 69d7183

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

packages/twilio-run/__tests__/runtime/internal/response.test.ts

+30-2
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,11 @@ test('appends a header correctly with no existing one', () => {
6969
});
7070

7171
test('calls express response correctly', () => {
72-
const mockRes = ({
72+
const mockRes = {
7373
status: jest.fn(),
7474
set: jest.fn(),
7575
send: jest.fn(),
76-
} as unknown) as ExpressResponse;
76+
} as unknown as ExpressResponse;
7777
const response = new Response();
7878
response.setBody(`I'm a teapot!`);
7979
response.setStatusCode(418);
@@ -84,3 +84,31 @@ test('calls express response correctly', () => {
8484
expect(mockRes.status).toHaveBeenCalledWith(418);
8585
expect(mockRes.set).toHaveBeenCalledWith({ 'Content-Type': 'text/plain' });
8686
});
87+
88+
test('serializes a response', () => {
89+
const response = new Response();
90+
response.setBody("I'm a teapot!");
91+
response.setStatusCode(418);
92+
response.appendHeader('Content-Type', 'text/plain');
93+
94+
const serialized = response.serialize();
95+
96+
expect(serialized.body).toEqual("I'm a teapot!");
97+
expect(serialized.statusCode).toEqual(418);
98+
expect(serialized.headers).toEqual({ 'Content-Type': 'text/plain' });
99+
});
100+
101+
test('serializes a response with content type set to application/json', () => {
102+
const response = new Response();
103+
response.setBody({ url: 'https://dkundel.com' });
104+
response.setStatusCode(200);
105+
response.appendHeader('Content-Type', 'application/json');
106+
107+
const serialized = response.serialize();
108+
109+
expect(serialized.body).toEqual(
110+
JSON.stringify({ url: 'https://dkundel.com' })
111+
);
112+
expect(serialized.statusCode).toEqual(200);
113+
expect(serialized.headers).toEqual({ 'Content-Type': 'application/json' });
114+
});

packages/twilio-run/src/runtime/internal/response.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,10 @@ export class Response implements TwilioResponse {
5858
serialize() {
5959
return {
6060
statusCode: this.statusCode,
61-
body: this.body.toString(),
61+
body:
62+
this.headers['Content-Type'] === 'application/json'
63+
? JSON.stringify(this.body)
64+
: this.body,
6265
headers: this.headers,
6366
};
6467
}

0 commit comments

Comments
 (0)