55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
import { defineEventHandler, readBody } from "h3";
|
|
|
|
import { baaWrapper } from "./clients.get";
|
|
import { type client } from "~/utils/types/database";
|
|
|
|
import { createError } from "#imports";
|
|
|
|
const clientKeys: Array<string> = [
|
|
"name",
|
|
"address",
|
|
"phone",
|
|
"email",
|
|
];
|
|
|
|
export function checkIsClient(
|
|
value: any,
|
|
required = false,
|
|
): value is Partial<Omit<client, "id">> {
|
|
const errors = new Map<string, string>();
|
|
|
|
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 as Partial<Omit<client, "id">>)
|
|
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((e) => {
|
|
return baaWrapper.RESTpost(e, clientKeys as Array<keyof Omit<client, "id">>, (o): o is Omit<client, "id"> => checkIsClient(o, true));
|
|
});
|