add crud for providers and models

This commit is contained in:
miloschwartz
2026-07-31 15:44:17 -04:00
parent 3d34ed70b0
commit f1a2da277e
27 changed files with 2241 additions and 3 deletions
+185
View File
@@ -0,0 +1,185 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { aiModels, aiProviders, db } from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
import { and, eq, ne } from "drizzle-orm";
import type { CreateOrEditAiModelResponse } from "@server/routers/aiProvider/types";
import {
aiBudgetUnitSchema,
refineBudgetFields
} from "@server/routers/aiProvider/validation";
const paramsSchema = z.strictObject({
orgId: z.string().nonempty(),
providerId: z.coerce.number().int().positive(),
modelId: z.coerce.number().int().positive()
});
const bodySchema = z
.strictObject({
modelKey: z.string().nonempty().optional(),
name: z.string().nonempty().optional(),
budgetAmount: z.number().positive().optional().nullable(),
budgetUnit: aiBudgetUnitSchema.optional().nullable(),
enabled: z.boolean().optional()
})
.superRefine((data, ctx) => {
refineBudgetFields(data, ctx);
});
registry.registerPath({
method: "post",
path: "/org/{orgId}/ai-provider/{providerId}/model/{modelId}",
description: "Update an AI model.",
tags: [OpenAPITags.AiModel],
request: {
params: paramsSchema,
body: {
content: {
"application/json": {
schema: bodySchema
}
}
}
},
responses: {
200: {
description: "Successful response"
}
}
});
export async function updateAiModel(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { orgId, providerId, modelId } = parsedParams.data;
const body = parsedBody.data;
const [existing] =
req.aiModel && req.aiModel.modelId === modelId
? [req.aiModel]
: await db
.select({ model: aiModels })
.from(aiModels)
.innerJoin(
aiProviders,
eq(aiModels.providerId, aiProviders.providerId)
)
.where(
and(
eq(aiModels.modelId, modelId),
eq(aiModels.providerId, providerId),
eq(aiProviders.orgId, orgId)
)
)
.limit(1)
.then((rows) => rows.map((r) => r.model));
if (!existing) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`AI model with ID ${modelId} not found`
)
);
}
if (
body.modelKey !== undefined &&
body.modelKey !== existing.modelKey
) {
const [conflict] = await db
.select({ modelId: aiModels.modelId })
.from(aiModels)
.where(
and(
eq(aiModels.providerId, providerId),
eq(aiModels.modelKey, body.modelKey),
ne(aiModels.modelId, modelId)
)
)
.limit(1);
if (conflict) {
return next(
createHttpError(
HttpCode.CONFLICT,
`Model with key ${body.modelKey} already exists for this provider`
)
);
}
}
const updateData: Partial<typeof aiModels.$inferInsert> = {
updatedAt: Date.now()
};
if (body.modelKey !== undefined) {
updateData.modelKey = body.modelKey;
}
if (body.name !== undefined) {
updateData.name = body.name;
}
if (body.budgetAmount !== undefined) {
updateData.budgetAmount = body.budgetAmount;
}
if (body.budgetUnit !== undefined) {
updateData.budgetUnit = body.budgetUnit;
}
if (body.enabled !== undefined) {
updateData.enabled = body.enabled;
}
const [model] = await db
.update(aiModels)
.set(updateData)
.where(
and(
eq(aiModels.modelId, modelId),
eq(aiModels.providerId, providerId)
)
)
.returning();
return response<CreateOrEditAiModelResponse>(res, {
data: { model },
success: true,
error: false,
message: "AI model updated successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}