From 22e050ebfa892053bace28c00d048d4d6c052a04 Mon Sep 17 00:00:00 2001 From: Blake Matthes Date: Mon, 10 Mar 2025 16:16:46 -0500 Subject: [PATCH] test(apihits): framework for apiHits to be implemented but no db insert yet --- database/schema/apiHits.ts | 26 ++++++++++++++++++++++++++ server/globalUtils/apiHits.ts | 15 +++++++++++---- 2 files changed, 37 insertions(+), 4 deletions(-) create mode 100644 database/schema/apiHits.ts diff --git a/database/schema/apiHits.ts b/database/schema/apiHits.ts new file mode 100644 index 0000000..408fa42 --- /dev/null +++ b/database/schema/apiHits.ts @@ -0,0 +1,26 @@ +import {pgTable, text, timestamp} from "drizzle-orm/pg-core"; +import {createSelectSchema} from "drizzle-zod"; + +export const apiHits = pgTable( + "apiHits", + { + ip: text("ip"), + endpoint: text("endpoint"), + action: text("action"), + lastBody: text("lastBody"), + stats: text("stats"), + add_date: timestamp().defaultNow(), + upd_date: timestamp().defaultNow(), + } + // (table) => [ + // // uniqueIndex('emailUniqueIndex').on(sql`lower(${table.email})`), + // uniqueIndex("role_name").on(table.name), + // ] +); + +// Schema for inserting a user - can be used to validate API requests +// export const insertRolesSchema = createInsertSchema(roles, { +// name: z.string().min(3, {message: "Role name must be more than 3 letters"}), +// }); +// Schema for selecting a Expenses - can be used to validate API responses +export const selectRolesSchema = createSelectSchema(apiHits); diff --git a/server/globalUtils/apiHits.ts b/server/globalUtils/apiHits.ts index 2cb71a7..5afb535 100644 --- a/server/globalUtils/apiHits.ts +++ b/server/globalUtils/apiHits.ts @@ -6,6 +6,7 @@ const requestSchema = z.object({ ip: z.string().optional(), endpoint: z.string(), action: z.string().optional(), + lastBody: z.string().optional(), stats: z.string().optional(), }); @@ -13,19 +14,25 @@ type ApiHitData = z.infer; export const apiHit = async ( c: Context, - data: unknown + data: ApiHitData ): Promise<{success: boolean; data?: ApiHitData; errors?: any[]}> => { // console.log(data); try { // Extract IP from request headers or connection info const forwarded = c.req.header("host"); - //console.log(forwarded); + console.log(forwarded); // Validate the data - const validatedData = requestSchema.parse(data); + const checkData = { + ip: forwarded!, + endpoint: data?.endpoint, + lastBody: data?.lastBody, + action: data?.action, + stats: data?.stats, + }; + const validatedData = requestSchema.parse(checkData); // Proceed with the validated data - // console.log("Validated Data:", validatedData); return {success: true, data: validatedData}; } catch (error) { // Explicitly check if the error is an instance of ZodError