factor out common api code

This commit is contained in:
Wroclaw 2023-05-11 09:11:20 +02:00
parent 1e63e008af
commit 67cad656d5
7 changed files with 239 additions and 201 deletions

View file

@ -1,10 +1,9 @@
/* global defineEventHandler, createError, readBody */
import { database } from "../utils/database";
import Snowflake from "../utils/snowflake";
import { baaWrapper } from "./clients.get";
import { client } from "~/utils/types/database";
const clientKeys = [
const clientKeys: Array<string> = [
"name",
"address",
"phone",
@ -13,7 +12,7 @@ const clientKeys = [
export function checkIsClient(
value: any,
required = true,
required = false,
): value is Partial<Omit<client, "id">> {
const errors = new Map<string, string>();
@ -29,7 +28,7 @@ export function checkIsClient(
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)
for (const i in value as Partial<Omit<client, "id">>)
if (!clientKeys.includes(i)) errors.set(i, `excessive property`);
if (errors.size !== 0) {
@ -49,19 +48,6 @@ export function checkIsClient(
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 };
export default defineEventHandler((e) => {
return baaWrapper.RESTpost(e, clientKeys as Array<keyof Omit<client, "id">>, (o): o is Omit<client, "id"> => checkIsClient(o, true));
});