Skip to content
← Public packages

@kentcdodds/package-app-kit

Design tokens, PWA install/update, About/version, cache helpers, and optional realtime notes sync for Kody package apps.

FollowFork

starter-tanstack/app/controllers/notes-action.ts

41 lines · 1.4 KB · TypeScript
import { addNote, deleteNote } from '../data/notes.ts'
import { createRoutes } from '../routes.ts'

function wantsJson(request: Request) {
	const accept = (request.headers.get('accept') || '').toLowerCase()
	return accept.startsWith('application/json')
}

/**
 * Notes form POST (add / delete). Mirrors Remix starter progressive-enhancement contract.
 */
function redirectTo(request: Request, location: string, status = 303) {
	const absolute = new URL(location, request.url).toString()
	return Response.redirect(absolute, status)
}

export async function notesAction(request: Request, appBasePath: string) {
	const form = await request.formData()
	const intent = String(form.get('intent') ?? '')
	const json = wantsJson(request)
	const routes = createRoutes(appBasePath)

	if (intent === 'delete') {
		const id = String(form.get('id') || '').trim()
		const result = id ? await deleteNote(id) : { ok: false }
		if (json) return Response.json({ ok: Boolean(result?.ok), id })
		return redirectTo(request, routes.notes.index.href())
	}

	const text = String(form.get('text') || '').trim()
	if (!text) {
		if (json) {
			return Response.json({ ok: false, error: 'A note needs some text.' }, { status: 400 })
		}
		return redirectTo(request, routes.notes.index.href())
	}

	const note = await addNote(text)
	if (json) return Response.json({ ok: true, note })
	return redirectTo(request, routes.notes.index.href())
}