Skip to content

src/request.ts

43 lines · 1.5 KB · TypeScript
Raw
import { mintInstallationAccessTokenInternal, signOriginAppJwt } from './token.ts'
import { originFetch } from './http.ts'
import { type OriginRequestParams, type OriginRequestResult } from './types.ts'

/**
 * Raw authenticated request to any `/v1/origin` path.
 *
 * Use this when a typed helper (`./repos`, `./pulls`, `./installations`) does
 * not cover the endpoint. Defaults to installation auth.
 *
 * @param params.path - Origin API path (for example `/rate_limit` or `/repos/{owner}`).
 * @param params.method - HTTP method; defaults to GET unless `body` is set.
 * @param params.auth - `installation` (default) or `app` for an app JWT.
 * @param params.installationId - Optional installation id for installation auth.
 * @returns `{ ok, status, body, rateLimit }` from the Origin response.
 * @example
 * import originRequest from 'kody:@kentcdodds/origin/request'
 * const result = await originRequest({ path: '/rate_limit', auth: 'app' })
 * // => { ok: true, status: 200, body: { resources: { ... } }, rateLimit: { remaining: '4999', ... } }
 */
export async function originRequest(
	params: OriginRequestParams,
): Promise<OriginRequestResult> {
	const auth = params.auth ?? 'installation'
	const bearerToken =
		auth === 'app'
			? await signOriginAppJwt()
			: (
					await mintInstallationAccessTokenInternal({
						installationId: params.installationId,
						scopes: params.scopes,
					})
				).token
	return originFetch({
		path: params.path,
		method: params.method,
		query: params.query,
		body: params.body,
		bearerToken,
	})
}

export default originRequest