Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/core/functions-js/src/FunctionsClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,12 @@ export class FunctionsClient {
throw new FunctionsHttpError(response)
}

let responseType = (response.headers.get('Content-Type') ?? 'text/plain').split(';')[0].trim()
// HTTP media types are case-insensitive (RFC 9110), so normalize before
// matching β€” otherwise an "Application/JSON" response falls through to text.
let responseType = (response.headers.get('Content-Type') ?? 'text/plain')
.split(';')[0]
.trim()
.toLowerCase()
let data: any
if (responseType === 'application/json') {
data = await response.json()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import 'jest'

import { FunctionsClient } from '../../src/index'

/**
* Unit tests (no relay) for response body parsing based on the response
* Content-Type header. HTTP media types are case-insensitive (RFC 9110), so the
* client must match them regardless of casing.
*/
describe('response Content-Type parsing', () => {
const makeClient = (contentType: string, body: string) => {
const customFetch = jest.fn(
async () =>
new Response(body, {
status: 200,
headers: { 'Content-Type': contentType },
})
) as any
return new FunctionsClient('http://localhost', { customFetch })
}

test('parses JSON when Content-Type is lowercase', async () => {
const client = makeClient('application/json', JSON.stringify({ foo: 'bar' }))
const { data, error } = await client.invoke('fn', {})
expect(error).toBeNull()
expect(data).toEqual({ foo: 'bar' })
})

test('parses JSON when Content-Type has mixed casing', async () => {
const client = makeClient('Application/JSON; charset=utf-8', JSON.stringify({ foo: 'bar' }))
const { data, error } = await client.invoke('fn', {})
expect(error).toBeNull()
expect(data).toEqual({ foo: 'bar' })
})

test('parses JSON when Content-Type is uppercase', async () => {
const client = makeClient('APPLICATION/JSON', JSON.stringify({ foo: 'bar' }))
const { data, error } = await client.invoke('fn', {})
expect(error).toBeNull()
expect(data).toEqual({ foo: 'bar' })
})
})
Loading