Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/cloudflare

Cloudflare helpers: API v4, static site publishing to Pages, analytics, WAF rules, logs, and docs.

FollowFork

Files

settings-store.ts

40 lines · 1.2 KB · TypeScript
import { packageStorage } from 'kody:runtime'
import { sanitizeStoredAccountIds, type StoredAccountIds } from './account-id.ts'

/** Package-storage key holding `{ default?, kody?, pages? }` Cloudflare account ids. */
export const ACCOUNT_IDS_STORAGE_KEY = 'cloudflareAccountIds'

let cached: StoredAccountIds | null = null

/**
 * Read the account ids stored per alias. Returns `{}` when nothing is stored
 * or storage is unavailable in this runtime (resolution then falls back to
 * discovery).
 */
export async function readStoredAccountIds(): Promise<StoredAccountIds> {
	if (cached) return cached
	try {
		const raw = await packageStorage().get(ACCOUNT_IDS_STORAGE_KEY)
		const parsed = typeof raw === 'string' ? safeJson(raw) : raw
		cached = sanitizeStoredAccountIds(parsed)
	} catch {
		return {}
	}
	return cached
}

/** Replace the stored account ids (already validated). */
export async function writeStoredAccountIds(next: StoredAccountIds): Promise<StoredAccountIds> {
	const clean = sanitizeStoredAccountIds(next)
	await packageStorage().set(ACCOUNT_IDS_STORAGE_KEY, JSON.stringify(clean))
	cached = clean
	return clean
}

function safeJson(value: string): unknown {
	try {
		return JSON.parse(value)
	} catch {
		return null
	}
}