Files
SanatiLeads/convex/searchJobs.ts

93 lines
2.4 KiB
TypeScript

import { mutation, query } from "./_generated/server";
import { v } from "convex/values";
import { getAuthUserId } from "@convex-dev/auth/server";
export const create = mutation({
args: {
projectId: v.id("projects"),
config: v.optional(v.any()),
},
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthorized");
const project = await ctx.db.get(args.projectId);
if (!project || project.userId !== userId) {
throw new Error("Project not found or unauthorized");
}
const now = Date.now();
return await ctx.db.insert("searchJobs", {
projectId: args.projectId,
status: "pending",
config: args.config,
progress: 0,
createdAt: now,
updatedAt: now,
});
},
});
export const update = mutation({
args: {
jobId: v.id("searchJobs"),
status: v.union(
v.literal("pending"),
v.literal("running"),
v.literal("completed"),
v.literal("failed")
),
progress: v.optional(v.number()),
error: v.optional(v.string()),
},
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthorized");
const job = await ctx.db.get(args.jobId);
if (!job) throw new Error("Job not found");
const project = await ctx.db.get(job.projectId);
if (!project || project.userId !== userId) {
throw new Error("Project not found or unauthorized");
}
await ctx.db.patch(args.jobId, {
status: args.status,
progress: args.progress,
error: args.error,
updatedAt: Date.now(),
});
},
});
export const listByProject = query({
args: {
projectId: v.id("projects"),
status: v.optional(v.string()),
},
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) return [];
const project = await ctx.db.get(args.projectId);
if (!project || project.userId !== userId) return [];
if (args.status) {
return await ctx.db
.query("searchJobs")
.withIndex("by_project_status", (q) =>
q.eq("projectId", args.projectId).eq("status", args.status!)
)
.order("desc")
.collect();
}
return await ctx.db
.query("searchJobs")
.withIndex("by_project_createdAt", (q) => q.eq("projectId", args.projectId))
.order("desc")
.collect();
},
});