Skip to content

Commit

Permalink
fix(runtime-handler): don't check for exact Content-Type matches (#392)
Browse files Browse the repository at this point in the history
* fix(runtime-handler): don't check for exact Content-Type matches

Content-Type headers may have the media type followed by a semicolon,
followed by some parameters, for example "charset=UTF-8". This fix
ensures that only the start of the Content-Type header matches
application/json when stringifying the body to JSON.

Fixes #391

* chore: add changeset

---------

Co-authored-by: Victor Ayogu <[email protected]>
  • Loading branch information
philnash and victoray authored Mar 26, 2024
1 parent 7bebf6f commit 34de081
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/friendly-turtles-pretend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@twilio/runtime-handler': patch
---

Don't check for exact Content-Type matches
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,21 @@ test('serializes a response with content type set to application/json', () => {
'Set-Cookie': [],
});
});

test('serializes a response with content type set to application/json with a charset', () => {
const response = new Response();
response.setBody({ url: 'https://dkundel.com' });
response.setStatusCode(200);
response.appendHeader('Content-Type', 'application/json; charset=UTF-8');

const serialized = response.serialize();

expect(serialized.body).toEqual(
JSON.stringify({ url: 'https://dkundel.com' })
);
expect(serialized.statusCode).toEqual(200);
expect(serialized.headers).toEqual({
'Content-Type': 'application/json; charset=UTF-8',
'Set-Cookie': [],
});
});
15 changes: 10 additions & 5 deletions packages/runtime-handler/src/dev-runtime/internal/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export class Response implements TwilioResponse {
this.headers[COOKIE_HEADER] = newHeaderValue;
}
} else {
this.headers[COOKIE_HEADER] = Array.isArray(value) ? value: [value];
this.headers[COOKIE_HEADER] = Array.isArray(value) ? value : [value];
}
} else {
const existingValue = this.headers[key];
Expand Down Expand Up @@ -133,12 +133,17 @@ export class Response implements TwilioResponse {
}

serialize() {
const contentType = this.headers['Content-Type'];
let body = this.body;
if (
typeof contentType === 'string' &&
contentType.startsWith('application/json')
) {
body = JSON.stringify(body);
}
return {
statusCode: this.statusCode,
body:
this.headers['Content-Type'] === 'application/json'
? JSON.stringify(this.body)
: this.body,
body: body,
headers: this.headers,
};
}
Expand Down

0 comments on commit 34de081

Please sign in to comment.