rovravR
Convex Community6mo ago
4 replies
rovrav

Question about how Convex makes transactions in a mutation

I'm testing out convex right now and I'm slowly falling in love with it, one of the features that blew my mind is how it converts mutations into transactions using plain typescript. However, there might be repetitive logic and I figured out a way to reuse that logic but I'm not sure if that is going to break the functionality of converting it into a transaction

Let me show you the code below

import { mutation } from "@/convex/_generated/server";
import { v } from "convex/values";
import { GenericMutationCtx } from "convex/server";
import { api } from "@/convex/_generated/api";
import {
  getOrCreateGlobalDomain,
  getOrCreateGlobalUrl,
  getOrCreateUserObjectDomain,
  getOrCreateUserObjectUrl,
} from "@/utils/convex-query-helpers";

export const uploadHistoryItemMutation = mutation({
  args: {
    url: v.string(),
    domainUrl: v.string(),
  },
  handler: async (ctx, args) => {
    // Check if user is authenticated
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) {
      throw new Error("User must be authenticated to create a history item");
    }

    const userId = identity.subject;
    const { url, domainUrl } = args;

    // Get or create all required entities using helper functions
    const globalDomainId = await getOrCreateGlobalDomain(ctx, domainUrl);
    const globalUrlId = await getOrCreateGlobalUrl(ctx, url, globalDomainId);
    const userObjectDomainId = await getOrCreateUserObjectDomain(
      ctx,
      userId,
      globalDomainId
    );
    const userObjectUrlId = await getOrCreateUserObjectUrl(
      ctx,
      userId,
      globalUrlId,
      globalDomainId,
      userObjectDomainId
    );

    // Create the history item
    const historyItemId = await ctx.db.insert("historyItems", {
      url,
      globalDomainId,
      globalUrlId,
      userObjectUrlId,
      userObjectDomainId,
      userId,
    });

    return {
      historyItemId,
      globalDomainId,
      globalUrlId,
    };
  },
});
Was this page helpful?