aboutsummaryrefslogtreecommitdiff
path: root/src/lib/server/services/validation.ts
blob: a8cebd9b5bdbfb2e283ae140e6c912c048046d69 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

import * as v from 'valibot';

export const IdSchema = v.pipe(v.number(), v.integer(), v.minValue(1));

export const AddGrocerySchema = v.object({
	name: v.pipe(v.string(), v.minLength(1)),
	categoryId: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
});

export const AddReferenceSchema = v.object({
	reference: v.pipe(v.string(), v.minLength(1)),
	price: v.nullable(v.pipe(v.number(), v.minValue(0))),
	unit: v.nullable(v.string()),
	qualityScore: v.nullable(
		v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(100)),
	),
});

export function numericId(
	value: FormDataEntryValue | null | undefined,
): number {
	const str = value?.toString().trim() ?? '';
	const n = Number(str);
	if (!Number.isFinite(n) || n <= 0 || !Number.isInteger(n)) {
		throw new Error('Invalid id');
	}
	return n;
}

export function parseFormString(
	value: FormDataEntryValue | null | undefined,
): string | null {
	const str = value?.toString().trim() ?? '';
	return str || null;
}

export function parseOptionalNumber(
	value: FormDataEntryValue | null | undefined,
): number | null {
	const str = value?.toString().trim() ?? '';
	if (!str) return null;
	const n = Number(str);
	if (!Number.isFinite(n)) return null;
	return n;
}