Files
portabase/src/features/agents/agents.action.ts
T

77 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-05-16 15:54:17 +02:00
"use server";
2025-09-23 20:35:48 +02:00
import {ActionError, userAction} from "@/lib/safe-actions/actions";
2026-01-28 15:54:03 +01:00
import {AgentSchema} from "@/features/agents/agents.schema";
import {z} from "zod";
2026-03-28 16:22:04 +01:00
import {eq, and, ne, count} from "drizzle-orm";
import {db} from "@/db";
2025-07-16 12:36:11 +02:00
import * as drizzleDb from "@/db";
import {slugify} from "@/utils/slugify";
2026-03-28 16:35:02 +01:00
import {getHealthLast12hLogs} from "@/db/services/healthcheck";
2024-11-11 12:39:59 +01:00
const verifySlugUniqueness = async (slug: string, agentId?: string) => {
const conditions = agentId ? and(eq(drizzleDb.schemas.agent.slug, slug), ne(drizzleDb.schemas.agent.id, agentId)) : eq(drizzleDb.schemas.agent.slug, slug);
const [countResult] = await db.select({count: count()}).from(drizzleDb.schemas.agent).where(conditions);
2025-05-16 15:54:17 +02:00
if (countResult.count > 0) {
2024-11-11 12:39:59 +01:00
throw new ActionError("Slug already exists");
}
2025-05-16 15:54:17 +02:00
};
2024-11-11 12:39:59 +01:00
2026-04-10 18:37:35 +02:00
export const createAgentAction = userAction.schema(
z.object({
organizationId: z.string().optional(),
data: AgentSchema,
})
).action(async ({parsedInput}) => {
const slug = slugify(parsedInput.data.name);
await verifySlugUniqueness(slug);
2026-04-10 18:37:35 +02:00
const [createdAgent] = await db.insert(drizzleDb.schemas.agent).values({...parsedInput.data, slug: slug, organizationId: parsedInput.organizationId}).returning();
if (createdAgent && parsedInput.organizationId){
await db.insert(drizzleDb.schemas.organizationAgent).values({
organizationId: parsedInput.organizationId,
agentId: createdAgent.id,
});
}
2025-05-16 15:54:17 +02:00
return {
data: createdAgent,
};
});
2024-11-11 12:39:59 +01:00
export const updateAgentAction = userAction
.schema(
z.object({
2025-05-16 15:54:17 +02:00
id: z.string(),
data: AgentSchema,
})
2024-11-11 12:39:59 +01:00
)
.action(async ({parsedInput}) => {
const slug = slugify(parsedInput.data.name);
await verifySlugUniqueness(slug, parsedInput.id);
2024-11-11 12:39:59 +01:00
const [updatedAgent] = await db.update(drizzleDb.schemas.agent).set({
...parsedInput.data,
slug: slug
}).where(eq(drizzleDb.schemas.agent.id, parsedInput.id)).returning();
2024-11-11 12:39:59 +01:00
return {
data: updatedAgent,
2025-05-16 15:54:17 +02:00
};
});
2026-02-10 11:44:45 +01:00
export const getAgentAction = userAction.schema(z.string()).action(async ({parsedInput}) => {
const agent = await db.query.agent.findFirst({
where: eq(drizzleDb.schemas.agent.id, parsedInput),
with: {
databases: true
}
});
2026-03-28 16:35:02 +01:00
2026-02-10 11:44:45 +01:00
return {
data: agent,
2026-03-28 16:35:02 +01:00
health: agent ? await getHealthLast12hLogs({ id: agent.id }) : []
2026-02-10 11:44:45 +01:00
};
});
2026-03-28 16:35:02 +01:00