/* global defineEventHandler, createError, readBody */ import { database } from "../utils/database"; import Snowflake from "../utils/snowflake"; import { client } from "~/utils/types/database"; const clientKeys = [ "name", "address", "phone", "email", ]; export function checkIsClient( value: any, required = true, ): value is Partial> { const errors = new Map(); if (typeof value !== "object") { throw createError({ statusCode: 400, message: "Invalid body", }); } if (!(typeof value.name === "string" || value.name === null || (!required && value.name === undefined))) errors.set("name", "is not string or null"); if (!(typeof value.address === "string" || value.address === null || (!required && value.address === undefined))) errors.set("address", "is not string or null"); if (!(typeof value.phone === "string" || value.phone === null || (!required && value.phone === undefined))) errors.set("phone", "is not string or null"); if (!(typeof value.email === "string" || value.email === null || (!required && value.email === undefined))) errors.set("email", "is not string or null"); for (const i in value) if (!clientKeys.includes(i)) errors.set(i, `excessive property`); if (errors.size !== 0) { let message = "Invalid Parameters: "; for (const i in errors) message += i + ", "; message = message.slice(0, -2); throw createError({ statusCode: 400, message, data: { errors: Object.fromEntries(errors), }, }); } return true; } export default defineEventHandler(async (e) => { const body = await readBody(e); const id = new Snowflake().toString(); if (!checkIsClient(body)) return; // checkIsClient already throws an detailed error await database.query( "INSERT INTO `clients` VALUES (?, ?, ?, ?, ?)", [id, body.name, body.address, body.phone, body.email], ); // FIXME: data may be turncated in the database // either throw an error when data is too large or // reply with turncated data return { id, ...body }; });