Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions db/tables/applications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const applicationsRelations = relations(
references: [assistantApplicationsTable.id],
}),
teamApplication: many(teamApplicationsTable),
//interview: many(interviewsTable),
}),
);

Expand Down
3 changes: 2 additions & 1 deletion db/tables/interview-schemas.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { interviewsTable } from "@/db/tables/interviews";
import { mainSchema } from "@/db/tables/schema";
import type { AnySchema } from "ajv";
import { relations } from "drizzle-orm";
import { json, serial } from "drizzle-orm/pg-core";

export const interviewSchemasTable = mainSchema.table("interviewSchemas", {
id: serial("id").primaryKey(),
jsonSchema: json("jsonSchema").notNull(), // used to validate corresponding interviews interviewAnswers
jsonSchema: json("jsonSchema").$type<AnySchema>().notNull(), // used to validate corresponding interviews interviewAnswers
});

export const interviewScemasRelations = relations(
Expand Down
3 changes: 2 additions & 1 deletion db/tables/interviews.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { assistantApplicationsTable } from "@/db/tables/applications";
import { interviewSchemasTable } from "@/db/tables/interview-schemas";
import { mainSchema } from "@/db/tables/schema";
import { teamUsersTable } from "@/db/tables/users";
import type { Json } from "@/lib/json-schema";
import { relations } from "drizzle-orm";
import { primaryKey } from "drizzle-orm/pg-core";
import { boolean, integer, json, serial, timestamp } from "drizzle-orm/pg-core";
Expand All @@ -14,7 +15,7 @@ export const interviewsTable = mainSchema.table("interviews", {
interviewSchemaId: integer("interviewSchemaId")
.notNull()
.references(() => interviewSchemasTable.id),
interviewAnswers: json("interviewAnswers"),
interviewAnswers: json("interviewAnswers").$type<Json>(),
isCancelled: boolean("isCancelled").notNull(),
plannedTime: timestamp("plannedTime").notNull(),
finishedTime: timestamp("timeFinished"),
Expand Down
56 changes: 56 additions & 0 deletions lib/json-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import Ajv, { type ErrorObject, type AnySchema } from "ajv";
import z from "zod";

type JsonSchemaResult =
| {
success: true;
}
| {
success: false;
error: ErrorObject[];
};

const ajv = new Ajv();

export function validateJsonSchema(
schema: AnySchema,
data: unknown,
): JsonSchemaResult {
const validator = ajv.compile(schema);
const isValid = validator(data);
if (isValid) {
return { success: true };
}
return {
success: false,
error:
validator.errors === undefined || validator.errors === null
? []
: validator.errors,
};
}

export function turnJsonIntoZodSchema(schema: AnySchema) {
return z
.object({})
.passthrough()
.superRefine((data, ctx) => {
const validationResult = validateJsonSchema(schema, data);
if (!validationResult.success) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "The interview schema is not valid",
params: validationResult.error,
});
}

return validationResult.success;
});
}

// from: https://www.reddit.com/r/typescript/comments/13mssvc/types_for_json_and_writing_json
type JsonPrimative = string | number | boolean | null;
type JsonArray = Json[];
type JsonObject = { [key: string]: Json };
type JsonComposite = JsonArray | JsonObject;
export type Json = JsonPrimative | JsonComposite;
11 changes: 8 additions & 3 deletions lib/time-parsers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { z } from "zod";

export const timeStringParser = z.union([z.string().date(), z.string().time()]);
export const timeStringParser = z.union([
z.string().date(),
z.string().time(),
z.string().datetime(),
]);

// Date here refers to the JS object date, so it allows more specific times than dates
export const dateParser = z.date();
export const toDateParser = z
.union([timeStringParser, z.date()])
Expand All @@ -24,7 +29,7 @@ export const toDatePeriodParser = z
})
.pipe(datePeriodParser);

export const pastDateParser = z.date().max(new Date());
export const futureDateParser = z.date().min(new Date());
export const pastDateParser = dateParser.max(new Date());
export const futureDateParser = dateParser.min(new Date());

export type DatePeriod = z.infer<typeof datePeriodParser>;
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
},
"license": "ISC",
"dependencies": {
"ajv": "^8.17.1",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"drizzle-orm": "^0.33.0",
Expand Down Expand Up @@ -52,5 +53,5 @@
"typescript": "^5.8.2",
"yaml": "^2.7.1"
},
"packageManager": "pnpm@10.15.0+sha512.486ebc259d3e999a4e8691ce03b5cac4a71cbeca39372a9b762cb500cfdf0873e2cb16abe3d951b1ee2cf012503f027b98b6584e4df22524e0c7450d9ec7aa7b"
"packageManager": "pnpm@10.18.3+sha512.bbd16e6d7286fd7e01f6b3c0b3c932cda2965c06a908328f74663f10a9aea51f1129eea615134bf992831b009eabe167ecb7008b597f40ff9bc75946aadfb08d"
}
34 changes: 34 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

74 changes: 74 additions & 0 deletions src/db-access/interviews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { database } from "@/db/setup/query-postgres";
import { interviewSchemasTable } from "@/db/tables/interview-schemas";
import { interviewsTable } from "@/db/tables/interviews";
import type {
NewInterview,
NewInterviewSchema,
} from "@/src/request-handling/interviews";
import type {
InterviewSchema,
InterviewSchemaKey,
} from "@/src/response-handling/interviews";
import { inArray } from "drizzle-orm";
import { type OrmResult, ormError } from "../error/orm-error";
import type { QueryParameters } from "../request-handling/common";
import { newDatabaseTransaction } from "./common";

export async function selectInterviewSchemaWithId(
id: InterviewSchemaKey[],
): Promise<OrmResult<InterviewSchema[]>> {
return await newDatabaseTransaction(database, async (tx) => {
const result = await tx
.select()
.from(interviewSchemasTable)
.where(inArray(interviewSchemasTable.id, id));
if (result.length !== id.length) {
throw ormError("Couln't find all entries");
}

return result;
});
}

export async function selectInterviewSchemas(listQueries: QueryParameters) {
return await newDatabaseTransaction(database, async (tx) => {
const result = await tx
.select()
.from(interviewSchemasTable)
.limit(listQueries.limit)
.offset(listQueries.offset);

return result;
});
}

export async function insertInterviewSchema(
interviewSchemaRequests: NewInterviewSchema[],
): Promise<OrmResult<InterviewSchema[]>> {
return await newDatabaseTransaction(database, async (tx) => {
const result = await tx
.insert(interviewSchemasTable)
.values(interviewSchemaRequests)
.returning();

if (result.length !== interviewSchemaRequests.length) {
throw ormError("Failed to insert all entries");
}

return result;
});
}

export async function insertInterview(interviewRequests: NewInterview[]) {
return await newDatabaseTransaction(database, async (tx) => {
const result = await tx
.insert(interviewsTable)
.values(interviewRequests)
.returning();

if (result.length !== interviewRequests.length) {
throw ormError("Failed to insert all entries");
}
return result;
});
}
41 changes: 41 additions & 0 deletions src/request-handling/interviews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { interviewsTable } from "@/db/tables/interviews";
import { turnJsonIntoZodSchema } from "@/lib/json-schema";
import {
futureDateParser,
timeStringParser,
toDateParser,
} from "@/lib/time-parsers";
import { serialIdParser } from "@/src/request-handling/common";
import type { AnySchema } from "ajv";
import metaSchema from "ajv/dist/refs/json-schema-draft-07.json";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod";

export const newInterviewSchemaSchema = z.object({
jsonSchema: turnJsonIntoZodSchema(metaSchema).transform<AnySchema>((v) => v), // If the object passed this json parser we know it is a validJsonSchema
});

export const newInterviewSchema = z.object({
applicationId: serialIdParser,
interviewSchemaId: serialIdParser,
interviewAnswers: z.object({}).passthrough(), // This will be further checked after schema is gotten from database
isCancelled: z.boolean(),
plannedTime: timeStringParser,
});

export const newInterviewToInsertSchema = newInterviewSchema
.extend({
plannedTime: newInterviewSchema.shape.plannedTime
.pipe(toDateParser)
.pipe(futureDateParser),
})
.pipe(createInsertSchema(interviewsTable));

export const newInterviewSchemaToInsertSchema = newInterviewSchemaSchema.extend(
{},
); // because of the way drizzle-zod works this pipe does wrong type inference and shouldn't be used

export type NewInterview = z.infer<typeof newInterviewToInsertSchema>;
export type NewInterviewSchema = z.infer<
typeof newInterviewSchemaToInsertSchema
>;
10 changes: 10 additions & 0 deletions src/response-handling/interviews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { interviewSchemasTable } from "@/db/tables/interview-schemas";
import { createSelectSchema } from "drizzle-zod";
import type { z } from "zod";

const interviewSchemaSchema = createSelectSchema(interviewSchemasTable)
.strict()
.readonly();

export type InterviewSchema = z.infer<typeof interviewSchemaSchema>;
export type InterviewSchemaKey = InterviewSchema["id"];
Loading