Skip to content

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

Package listing

@kody/stash

src/lib/run.ts

69 lines · 1.4 KB · TypeScript
import {
	addNote,
	archiveNote,
	getNote,
	listNotesByTag,
	listRecent,
	overview,
	searchNotes,
	updateNote,
} from './notes.ts'
import { assertNever, inputRecord, normalizeText } from './util.ts'

const STASH_ACTIONS = [
	'add',
	'update',
	'get',
	'recent',
	'by-tag',
	'archive',
	'search',
	'overview',
] as const

type StashAction = (typeof STASH_ACTIONS)[number]

function parseAction(raw: string): StashAction | null {
	const action = raw.toLowerCase()
	for (const candidate of STASH_ACTIONS) {
		if (candidate === action) return candidate
	}
	return null
}

export async function run(input?: unknown) {
	const body = inputRecord(input ?? {})
	const rawAction = normalizeText(body.action)
	const action = rawAction
		? parseAction(rawAction)
		: body.text
			? 'add'
			: body.query
				? 'search'
				: 'overview'
	if (!action) {
		throw new Error(
			`Unknown action "${rawAction}". Valid actions: ${STASH_ACTIONS.join(', ')}.`,
		)
	}
	switch (action) {
		case 'add':
			return await addNote(body)
		case 'update':
			return await updateNote(body)
		case 'get':
			return await getNote(body)
		case 'recent':
			return await listRecent(body)
		case 'by-tag':
			return await listNotesByTag(body)
		case 'archive':
			return await archiveNote(body)
		case 'search':
			return await searchNotes(body)
		case 'overview':
			return overview()
		default:
			return assertNever(action, `Unhandled stash action: ${String(action)}`)
	}
}