ELYSIA
unknown
typescript
a month ago
2.0 kB
1
Indexable
Never
import ElysiaApp, { error } from "elysia"; function isValidTimestampz(dateString: string) { if (typeof dateString !== "string") { return false; } // Regular expression to match a proper timestampz (ISO 8601 with timezone offset) const timestampzRegex = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?)(Z|([+-]\d{2}:\d{2}))$/; // Check if the dateString matches the regex if (!timestampzRegex.test(dateString)) { return false; } // Further validation to check if the date is valid const date = new Date(dateString); return !Number.isNaN(date.getTime()); } function parseJSONUnsafe(data: string): any | null { try { const parsed = JSON.parse(data); if (typeof parsed !== "object") { return null; } return parsed; } catch (e) { return null; } } const transformDates = (obj: any) => { for (const key in obj) { if (typeof obj[key] === "object") { transformDates(obj[key]); continue; } if (typeof obj[key] === "string") { const data = parseJSONUnsafe(obj[key]); if ( data && typeof data === "object" && data.constructor.name === "Object" ) { obj[key] = data; console.log({ obj }); transformDates(obj[key]); continue; } } if (isValidTimestampz(obj[key])) { obj[key] = new Date(obj[key]); } } }; const transformBoolean = (obj: any) => { for (const key in obj) { if (typeof obj[key] === "object") { transformBoolean(obj[key]); continue; } if (obj[key] === "true") { obj[key] = true; } else if (obj[key] === "false") { obj[key] = false; } } }; export const useSerializeRequestMiddleware = (app: ElysiaApp) => { return app.onTransform(async (args) => { const { body, query } = args; if (body) transformDates(body); if (query) transformDates(query); if (body) transformBoolean(body); if (query) transformBoolean(query); }); };
Leave a Comment