Skip to content

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

Package listing

@kody/twitch

src/validation.ts

56 lines · 1.9 KB · TypeScript
export type InputRecord = Record<string, unknown>

export function inputRecord(value: unknown): InputRecord {
	if (value === null || typeof value !== 'object' || Array.isArray(value)) {
		throw new Error('Input must be an object.')
	}
	return value as InputRecord
}

export function requiredString(input: InputRecord, key: string): string {
	const value = input[key]
	if (typeof value !== 'string' || value.trim().length === 0) {
		throw new Error(key + ' is required.')
	}
	return value.trim()
}

export function optionalString(input: InputRecord, key: string): string | undefined {
	const value = input[key]
	if (value === undefined || value === null || value === '') return undefined
	if (typeof value !== 'string') throw new Error(key + ' must be a string.')
	const trimmed = value.trim()
	return trimmed.length > 0 ? trimmed : undefined
}

export function optionalBoolean(input: InputRecord, key: string): boolean | undefined {
	const value = input[key]
	if (value === undefined || value === null) return undefined
	if (typeof value !== 'boolean') throw new Error(key + ' must be a boolean.')
	return value
}

export function boundedLimit(value: unknown, fallback = 20, max = 100): number {
	if (value === undefined || value === null) return fallback
	if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > max) {
		throw new Error('limit must be an integer from 1 through ' + max + '.')
	}
	return Number(value)
}

export function stringList(value: unknown, key: string): string[] {
	if (value === undefined || value === null || value === '') return []
	if (typeof value === 'string') {
		const trimmed = value.trim()
		return trimmed ? [trimmed] : []
	}
	if (!Array.isArray(value)) {
		throw new Error(key + ' must be a string or an array of strings.')
	}
	return value.map((item, index) => {
		if (typeof item !== 'string' || item.trim().length === 0) {
			throw new Error(key + '[' + index + '] must be a non-empty string.')
		}
		return item.trim()
	})
}