Skip to content
← Public packages

@kody/openapi

Bind an OpenAPI spec and call selected operations with saved integration or secret names.

src/call.ts

58 lines · 1.6 KB · TypeScript
import {
	executeOpenApiOperationRequest,
	type OpenApiOperationRequestArgs,
	type OpenApiOperationRequestResult,
} from './request.ts'
import { assertBindingName } from './selection.ts'
import { requireBinding } from './storage.ts'

export type CallInput = OpenApiOperationRequestArgs & {
	/** Binding name from bind(). */
	name: string
	/** Operation slug from bind()/get(). */
	operation: string
}

/**
 * Call one bound OpenAPI operation. Replacement for
 * kody.openapi["name"].operation({ params, query, headers, body }).
 * Use after bind() on this forked package.
 *
 * @param input - Binding name, operation slug, and request fields
 * @returns Status, parsed body, and truncation flag
 *
 * @example
 * import call from 'kody:@<username>/openapi/call'
 * const listed = await call({
 *   name: 'acme',
 *   operation: 'list_widgets',
 *   query: { limit: 10 },
 * })
 */
export default async function call(
	input: CallInput,
): Promise<OpenApiOperationRequestResult> {
	const name = assertBindingName(input.name)
	const slug = input.operation.trim()
	if (!slug) {
		throw new Error('operation is required')
	}
	const binding = await requireBinding(name)
	const operation = binding.operations.find((entry) => entry.slug === slug)
	if (!operation) {
		const available = binding.operations.map((entry) => entry.slug).join(', ')
		throw new Error(
			`Operation "${slug}" is not on binding "${name}". Bound slugs: ${available || '(none)'}.`,
		)
	}
	return executeOpenApiOperationRequest({
		binding,
		operation,
		args: {
			params: input.params,
			query: input.query,
			headers: input.headers,
			body: input.body,
		},
	})
}