Files
supabase/apps/studio/lib/api/apiHelpers.test.ts
Alaister YoungandAlaister Young 0252fd8cad [FE-5114] (part 7) – refactor(studio): remove Next API adapter (#54034)
## Problem

With all Studio API routes migrated to native TanStack Start handlers
(or removed when unused) in parts 1–6, the Next Pages Router API adapter
and legacy `NextApiRequest`/`NextApiResponse` wrappers are no longer
used. Part 7 of 7 for
[FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the)
tears them down.

## Solution

**Removed:**

- `compat/next/api.ts` and `compat/next/api.test.ts` (`toWebHandler`)
- Legacy `apiWrapper`, `apiAuthenticate`, and `fetchUserClaims`
(`NextApiRequest`/`NextApiResponse`) functions and their legacy tests in
`lib/api/apiWrapper.ts`, `lib/api/apiAuthenticate.ts`,
`lib/api/apiWrappers.test.ts`, and `lib/api/apiAuthenticate.test.ts`
- The now-unused `fromNodeHeaders` helper (and its `node:http` import)
and its tests in `lib/api/apiHelpers.ts` / `lib/api/apiHelpers.test.ts`

**Changed:**

- Updated comment in `lib/server/configcat.ts` from `apiAuthenticate` to
`authenticateRequest`

## Review instructions

1. Confirm `git grep -E
"NextApiRequest|NextApiResponse|compat/next/api|toWebHandler|fromNodeHeaders|from
'next'" apps/studio/` returns no matches.
2. Run `pnpm --filter studio run typecheck`, `pnpm knip --workspace
apps/studio`, and `pnpm --filter studio exec vitest run lib/api/
tests/routes/api/ scripts/__tests__/server-source-maps.test.ts`.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 23:01:47 +08:00

302 lines
9.0 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
commaSeparatedStringIntoArray,
constructHeaders,
getBearerToken,
getSearchParamsRecord,
InvalidJsonError,
parseJsonBody,
toSnakeCase,
zBooleanString,
} from './apiHelpers'
vi.mock('@/lib/constants', () => ({
IS_PLATFORM: false,
}))
describe('apiHelpers', () => {
describe('constructHeaders', () => {
beforeEach(() => {
process.env.SUPABASE_SERVICE_KEY = 'test-service-key'
})
it('should return default headers when no headers are provided', () => {
const result = constructHeaders(null as any)
expect(result).toEqual({
'Content-Type': 'application/json',
Accept: 'application/json',
})
})
it('should clean and include only allowed headers', () => {
const inputHeaders = {
Accept: 'application/json',
Authorization: 'Bearer token',
'Content-Type': 'application/json',
'x-connection-encrypted': 'true',
cookie: 'test-cookie',
'User-Agent': 'test-agent',
Referer: 'test-referer',
}
const result = constructHeaders(inputHeaders)
expect(result).toEqual({
Accept: 'application/json',
Authorization: 'Bearer token',
'Content-Type': 'application/json',
'x-connection-encrypted': 'true',
cookie: 'test-cookie',
apiKey: 'test-service-key',
})
})
it('should remove undefined values from headers', () => {
const inputHeaders = {
Accept: undefined,
Authorization: 'Bearer token',
'Content-Type': 'application/json',
cookie: undefined,
}
const result = constructHeaders(inputHeaders)
expect(result).toEqual({
Authorization: 'Bearer token',
'Content-Type': 'application/json',
apiKey: 'test-service-key',
})
})
})
describe('toSnakeCase', () => {
it('should return null for null input', () => {
expect(toSnakeCase(null)).toBeNull()
})
it('should convert object keys to snake case', () => {
const input = {
firstName: 'John',
lastName: 'Doe',
contactInfo: {
emailAddress: 'john@example.com',
phoneNumber: '1234567890',
},
}
const expected = {
first_name: 'John',
last_name: 'Doe',
contact_info: {
email_address: 'john@example.com',
phone_number: '1234567890',
},
}
expect(toSnakeCase(input)).toEqual(expected)
})
it('should handle arrays of objects', () => {
const input = [
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Jane', lastName: 'Smith' },
]
const expected = [
{ first_name: 'John', last_name: 'Doe' },
{ first_name: 'Jane', last_name: 'Smith' },
]
expect(toSnakeCase(input)).toEqual(expected)
})
it('should handle arrays of primitive values', () => {
const input = [1, 'test', true]
expect(toSnakeCase(input)).toEqual([1, 'test', true])
})
it('should handle nested arrays', () => {
const input = {
users: [
{ firstName: 'John', contactInfo: { emailAddress: 'john@example.com' } },
{ firstName: 'Jane', contactInfo: { emailAddress: 'jane@example.com' } },
],
}
const expected = {
users: [
{ first_name: 'John', contact_info: { email_address: 'john@example.com' } },
{ first_name: 'Jane', contact_info: { email_address: 'jane@example.com' } },
],
}
expect(toSnakeCase(input)).toEqual(expected)
})
it('should handle primitive values', () => {
expect(toSnakeCase('test')).toBe('test')
expect(toSnakeCase(123)).toBe(123)
expect(toSnakeCase(true)).toBe(true)
})
})
describe('zBooleanString', () => {
it('should transform "true" string to boolean true', () => {
const schema = zBooleanString()
const result = schema.parse('true')
expect(result).toBe(true)
})
it('should transform "false" string to boolean false', () => {
const schema = zBooleanString()
const result = schema.parse('false')
expect(result).toBe(false)
})
it('should throw error for invalid boolean string', () => {
const schema = zBooleanString()
expect(() => schema.parse('invalid')).toThrow('must be a boolean string')
})
it('should throw custom error message when provided', () => {
const customError = 'Custom boolean error'
const schema = zBooleanString(customError)
expect(() => schema.parse('invalid')).toThrow(customError)
})
it('should throw error for empty string', () => {
const schema = zBooleanString()
expect(() => schema.parse('')).toThrow('must be a boolean string')
})
it('should throw error for non-string input', () => {
const schema = zBooleanString()
expect(() => schema.parse(true)).toThrow()
expect(() => schema.parse(false)).toThrow()
expect(() => schema.parse(123)).toThrow()
})
})
describe('getSearchParamsRecord', () => {
it('maps single params to strings and repeated params to arrays', () => {
const searchParams = new URLSearchParams('name=foo&ids=a&ids=b&empty=')
expect(getSearchParamsRecord(searchParams)).toEqual({
name: 'foo',
ids: ['a', 'b'],
empty: '',
})
})
})
describe('commaSeparatedStringIntoArray', () => {
it('should split comma-separated string into array', () => {
const result = commaSeparatedStringIntoArray('a,b,c')
expect(result).toEqual(['a', 'b', 'c'])
})
it('should trim whitespace from values', () => {
const result = commaSeparatedStringIntoArray('a, b , c')
expect(result).toEqual(['a', 'b', 'c'])
})
it('should filter out empty values', () => {
const result = commaSeparatedStringIntoArray('a,,b,')
expect(result).toEqual(['a', 'b'])
})
it('should handle single value', () => {
const result = commaSeparatedStringIntoArray('single')
expect(result).toEqual(['single'])
})
it('should handle empty string', () => {
const result = commaSeparatedStringIntoArray('')
expect(result).toEqual([])
})
it('should handle string with only commas', () => {
const result = commaSeparatedStringIntoArray(',,,')
expect(result).toEqual([])
})
})
describe('getBearerToken', () => {
it.each([
['Bearer abc.def', 'abc.def'],
['bearer abc.def', 'abc.def'],
['BEARER \t abc.def ', 'abc.def'],
])('returns the token from %j', (header, expected) => {
expect(getBearerToken(header)).toBe(expected)
})
it.each([
['missing', undefined],
['array-valued', ['Bearer a', 'Bearer b']],
['wrong scheme', 'Basic abc'],
['no separator', 'Bearerabc'],
['empty token', 'Bearer'],
['whitespace-only token', 'Bearer '],
])('returns null for a %s header', (_, header) => {
expect(getBearerToken(header)).toBeNull()
})
it('handles a long whitespace run in linear time', () => {
const header = `Bearer${' '.repeat(100_000)}\n`
const start = performance.now()
const token = getBearerToken(header)
const elapsed = performance.now() - start
expect(token).toBeNull()
expect(elapsed).toBeLessThan(100)
})
})
describe('parseJsonBody', () => {
it.each<[string | undefined, unknown]>([
['{"query":"select 1"}', { query: 'select 1' }],
['[1,"two",null]', [1, 'two', null]],
['"hello"', 'hello'],
['42', 42],
['null', null],
['', {}],
[undefined, {}],
])('parses valid JSON body %s', async (body, expected) => {
const request = new Request('http://localhost/api/test', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body,
})
expect(await parseJsonBody(request)).toEqual(expected)
})
it('parses JSON sent with a text/plain content type', async () => {
const request = new Request('http://localhost/api/test', {
method: 'POST',
headers: { 'content-type': 'text/plain;charset=UTF-8' },
body: JSON.stringify({ filenames: ['a/b.png'] }),
})
expect(await parseJsonBody(request)).toEqual({ filenames: ['a/b.png'] })
})
it.each(['{', '[1,', 'undefined', ' ', '{"trailing":1,}'])(
'throws InvalidJsonError for malformed JSON: %s',
async (body) => {
const request = new Request('http://localhost/api/test', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body,
})
await expect(parseJsonBody(request)).rejects.toBeInstanceOf(InvalidJsonError)
}
)
it('rethrows body-read failures instead of masking them as InvalidJsonError', async () => {
const request = new Request('http://localhost/api/test', { method: 'POST', body: '{}' })
const readError = new Error('Stream aborted')
vi.spyOn(request, 'text').mockRejectedValue(readError)
await expect(parseJsonBody(request)).rejects.toBe(readError)
})
})
})