DylanDevD
Convex Communityβ€’16mo agoβ€’
25 replies
DylanDev

Clerk With Convex in Backend Functions

I want to store a score variable in the public metadata but I can't figure out how to modify that from the backend and I get an error?

Error:
Uncaught Error
    at UserAPI.request (../node_modules/@clerk/backend/src/api/request.ts:186:15)
    at async handler (../convex/game.ts:102:61)


Code:
import { v } from "convex/values";

import { mutation, query } from "./_generated/server";
import { createClerkClient } from '@clerk/backend';

const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY });

...

export const checkGuess = mutation({
    args: { id: v.id("levels"), guessLatitude: v.float64(), guessLongitude: v.float64() },
    handler: async(ctx, args) => {
        const level = await ctx.db.get(args.id);

        if(!level) {
            throw new Error("No levels exist");
        }

        const correctLat = level.latitude;
        const correctLng = level.longitude;

        const distanceAway = parseInt(haversineDistanceInFeet(correctLat, correctLng, args.guessLatitude, args.guessLongitude).toFixed(0));
        // give some leniency to the distance
        let lenientDistance = distanceAway - 20;
        if (lenientDistance < 0) {
            lenientDistance = 0;
        }
        // If within 250 feet, score increases by distance if outside of 250 feet score = 0
        let score = 250 - lenientDistance; 
        if (score < 0) { // no negative score
            score = 0;
        }

        // Fetch the user from Clerk
        const user = await ctx.auth.getUserIdentity();
        if(user !== null) {
            console.log(user); // THIS IS PRINTING OUT CORRECTLY
            await clerkClient.users.updateUser(user.subject, {
                publicMetadata: {
                    score: score,
                },
            });
        }

        return {
            correctLat,
            correctLng,
            distanceAway,
            score,
        }
    }
});
Was this page helpful?