Skip to content
← Public packages

@kentcdodds/sentry

Inspect Sentry organizations, projects, issues, and event summaries.

FollowFork

Files

request-init.ts

54 lines · 1.9 KB · TypeScript
type JsonRecord = Record<string, unknown>

const allowedKeys = new Set(['path', 'query', 'init', 'method', 'headers', 'body'])

/**
 * Build the fetch init for `request`. Top-level `method`, `headers`, and
 * `body` win over `init`. Object bodies are sent as JSON. Unknown keys throw
 * so a typo never silently becomes a GET.
 */
export function buildRequestInit(input: JsonRecord): RequestInit | undefined {
	const unknown = Object.keys(input).filter((key) => !allowedKeys.has(key))
	if (unknown.length) {
		throw new Error(
			'request got unknown keys: ' +
				unknown.join(', ') +
				'. Use path, query, method, headers, body, or init.',
		)
	}
	const init = input.init
	if (init !== undefined && (init === null || typeof init !== 'object' || Array.isArray(init))) {
		throw new Error('request init must be an object.')
	}
	const merged: RequestInit = { ...(init as RequestInit | undefined) }
	if (input.method !== undefined) {
		if (typeof input.method !== 'string' || !input.method.trim()) {
			throw new Error('request method must be a non-empty string.')
		}
		merged.method = input.method.trim().toUpperCase()
	}
	const headers: Record<string, string> = {
		...headersToRecord(merged.headers),
		...headersToRecord(input.headers as HeadersInit | undefined),
	}
	if (input.body !== undefined) {
		if (typeof input.body === 'string') {
			merged.body = input.body
		} else {
			merged.body = JSON.stringify(input.body)
			if (!Object.keys(headers).some((key) => key.toLowerCase() === 'content-type')) {
				headers['content-type'] = 'application/json'
			}
		}
	}
	if (Object.keys(headers).length) merged.headers = headers
	if (merged.body !== undefined && !merged.method) {
		throw new Error('request body needs a method such as POST or PUT.')
	}
	return Object.keys(merged).length ? merged : undefined
}

function headersToRecord(headers: HeadersInit | undefined): Record<string, string> {
	if (!headers) return {}
	return Object.fromEntries(new Headers(headers).entries())
}