Skip to content
← Public packages

@kody/onetimefax

Head-start stub for sending faxes from Kody with the Onetime Fax developer API. Fork it and add your API key.

FollowFork

Files

fax-status.ts

74 lines · 2.4 KB · TypeScript
import { object, parseSafe, string } from 'remix/data-schema'
import {
	assertFaxId,
	inputError,
	onetimefaxRequest,
	type OnetimeFax,
} from './client.ts'

const faxStatusInput = object({ faxId: string() }, { unknownKeys: 'error' })

export type FaxStatusResult = {
	faxId: string
	status: string | null
	recipientNumber: string | null
	pageCount: number | null
	quote: OnetimeFax['quote'] | null
	filesReady: boolean
	creditsConsumedCents: number | null
	fax: OnetimeFax
}

/** Shared by prepare-fax and send-fax. */
export function summarizeFax(fax: OnetimeFax): FaxStatusResult {
	const files = Array.isArray(fax.files) ? fax.files : []
	return {
		faxId: fax.id,
		status: typeof fax.status === 'string' ? fax.status : null,
		recipientNumber:
			typeof fax.recipientNumber === 'string' ? fax.recipientNumber : null,
		pageCount: typeof fax.pageCount === 'number' ? fax.pageCount : null,
		quote: fax.quote ?? null,
		filesReady: files.length > 0 && files.every((file) => file.status === 'ready'),
		creditsConsumedCents:
			typeof fax.creditsConsumedCents === 'number'
				? fax.creditsConsumedCents
				: null,
		fax,
	}
}

/** Shared by prepare-fax and send-fax. */
export async function readFax(faxId: string) {
	const { data } = await onetimefaxRequest<{ fax: OnetimeFax }>(
		'GET',
		`/api/v1/faxes/${encodeURIComponent(faxId)}`,
	)
	return data.fax
}

/**
 * Check one Onetime Fax job: draft file processing, the price quote, and
 * after sending, delivery status. Use after `./prepare-fax` to see whether
 * the quote is ready, and after `./send-fax` to follow delivery.
 * Read-only; spends nothing. This is also the package default export.
 *
 * Wraps `GET /api/v1/faxes/{faxId}` (https://www.onetimefax.com/developers/).
 * Onetime Fax does not document a list-faxes endpoint, so keep the ids you get back.
 *
 * @param input - `{ faxId }` from `./prepare-fax`. Unknown keys are rejected.
 * @returns `{ faxId, status, recipientNumber, pageCount, quote, filesReady, creditsConsumedCents, fax }` where `fax` is the raw API object
 *
 * @example
 * import faxStatus from 'kody:@kody/onetimefax/fax-status'
 *
 * const status = await faxStatus({ faxId: 'cmr4...' })
 */
export default async function faxStatus(raw: unknown): Promise<FaxStatusResult> {
	const parsed = parseSafe(faxStatusInput, raw)
	if (!parsed.success) {
		throw inputError('fax-status', 'faxId', parsed.issues)
	}
	const faxId = assertFaxId(parsed.value.faxId)
	return summarizeFax(await readFax(faxId))
}