Refactor image upload handling across items and receipts routes to include validation for uploaded images, enhancing error handling and user feedback. Consolidate parsing functions by importing from a shared module, improving code maintainability. Update server hooks to ensure consistent cookie handling and error logging.
This commit is contained in:
@@ -1,19 +1,11 @@
|
||||
import { fail } from "@sveltejs/kit";
|
||||
import type { Actions, PageServerLoad } from "./$types";
|
||||
import type { StackqItem } from "$lib/types/items";
|
||||
import { parseBool, parseNum } from "$lib/parse-form";
|
||||
import { validateImageUpload } from "$lib/validate-image-upload";
|
||||
|
||||
const COLLECTION = "Stackq_Items";
|
||||
|
||||
function parseNum(val: unknown): number | undefined {
|
||||
if (val === "" || val === null || val === undefined) return undefined;
|
||||
const n = Number(val);
|
||||
return Number.isFinite(n) ? n : undefined;
|
||||
}
|
||||
|
||||
function parseBool(val: unknown): boolean {
|
||||
return val === "on" || val === "true" || val === true;
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const list = await locals.pb
|
||||
.collection(COLLECTION)
|
||||
@@ -47,6 +39,10 @@ export const actions: Actions = {
|
||||
const Stock = parseBool(form.get("Stock"));
|
||||
const imageFileCreate = form.get("Image") as File | null;
|
||||
const hasImage = imageFileCreate && imageFileCreate.size > 0;
|
||||
if (hasImage) {
|
||||
const imgError = validateImageUpload(imageFileCreate);
|
||||
if (imgError) return fail(400, { error: imgError, form: "create" });
|
||||
}
|
||||
|
||||
if (!Item) return fail(400, { error: "Item name is required", form: "create" });
|
||||
|
||||
@@ -91,6 +87,10 @@ export const actions: Actions = {
|
||||
const Stock = parseBool(form.get("Stock"));
|
||||
const Image = form.get("Image") as File | null;
|
||||
const imageFile = Image && Image.size > 0 ? Image : undefined;
|
||||
if (imageFile) {
|
||||
const imgError = validateImageUpload(imageFile);
|
||||
if (imgError) return fail(400, { error: imgError, form: "update" });
|
||||
}
|
||||
|
||||
if (!Item) return fail(400, { error: "Item name is required", form: "update" });
|
||||
|
||||
|
||||
Reference in New Issue
Block a user