Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kody/trello

src/request.ts

55 lines · 1.9 KB · TypeScript
import { isMutatingMethod, trelloRequest } from './client.ts'
import { parseAuthInput } from './auth.ts'
import type { JsonRecord, MutationInput, TrelloAuthInput } from './types.ts'
import { optionalBoolean, optionalString, requireRecord, requireString } from './types.ts'

export type TrelloRawRequestInput = TrelloAuthInput &
	MutationInput & {
		path: string
		method?: string
		query?: JsonRecord
		body?: JsonRecord
	}

/**
 * Call any Trello REST path under `api.trello.com`. GET is read-only.
 * POST / PUT / PATCH / DELETE need `confirm: true` or `dryRun: true`.
 * @example
 * import { request } from 'kody:@kody/trello/request'
 * const page = await request({ path: '/members/me/boards', query: { filter: 'open' } })
 */
export async function request(input: TrelloRawRequestInput) {
	const method = (input.method ?? 'GET').toUpperCase()
	const path = requireString(input.path, 'path')
	if (isMutatingMethod(method) && input.dryRun !== true && input.confirm !== true) {
		throw new Error(
			`${method} ${path} requires confirm: true after explicit user approval, or dryRun: true.`,
		)
	}
	return trelloRequest({
		...input,
		method,
		path,
	})
}

/**
 * Call any Trello REST path.
 * @example
 * import request from 'kody:@kody/trello/request'
 * const me = await request({ path: '/members/me' })
 */
export default async function requestEntrypoint(
	params: Partial<TrelloRawRequestInput> & Record<string, unknown> = {},
) {
	const input = requireRecord(params, 'request')
	return request({
		...parseAuthInput(input),
		path: optionalString(input.path, 'path') ?? '',
		method: optionalString(input.method, 'method'),
		query: input.query && typeof input.query === 'object' ? (input.query as JsonRecord) : undefined,
		body: input.body && typeof input.body === 'object' ? (input.body as JsonRecord) : undefined,
		confirm: optionalBoolean(input.confirm, 'confirm'),
		dryRun: optionalBoolean(input.dryRun, 'dryRun'),
	})
}