feat: add webhook endpoint to support syncing clerk user data into users table

This commit is contained in:
Stevan Freeborn
2023-09-09 22:29:28 -05:00
parent 4b6fec0841
commit 7d755ec5c5
9 changed files with 226 additions and 109 deletions
-90
View File
@@ -1,90 +0,0 @@
# Welcome to your Convex functions directory!
Write your Convex functions here. See
https://docs.convex.dev/using/writing-convex-functions for more.
A query function that takes two arguments looks like:
```ts
// functions.js
import { query } from "./_generated/server";
import { v } from "convex/values";
export const myQueryFunction = query({
// Validators for arguments.
args: {
first: v.number(),
second: v.string(),
},
// Function implementation.
hander: async (ctx, args) => {
// Read the database as many times as you need here.
// See https://docs.convex.dev/database/reading-data.
const documents = await ctx.db.query("tablename").collect();
// Arguments passed from the client are properties of the args object.
console.log(args.first, args.second);
// Write arbitrary JavaScript here: filter, aggregate, build derived data,
// remove non-public properties, or create new objects.
return documents;
},
});
```
Using this query function in a React component looks like:
```ts
const data = useQuery(api.functions.myQueryFunction, {
first: 10,
second: "hello",
});
```
A mutation function looks like:
```ts
// functions.js
import { mutation } from "./_generated/server";
import { v } from "convex/values";
export const myMutationFunction = mutation({
// Validators for arguments.
args: {
first: v.string(),
second: v.string(),
},
// Function implementation.
hander: async (ctx, args) => {
// Insert or modify documents in the database here.
// Mutations can also read from the database like queries.
// See https://docs.convex.dev/database/writing-data.
const message = { body: args.first, author: args.second };
const id = await ctx.db.insert("messages", message);
// Optionally, return a value from your mutation.
return await ctx.db.get(id);
},
});
```
Using this mutation function in a React component looks like:
```ts
const mutation = useMutation(api.functions.myMutationFunction);
function handleButtonPress() {
// fire and forget, the most common way to use mutations
mutation({ first: "Hello!", second: "me" });
// OR
// use the result once the mutation has completed
mutation({ first: "Hello!", second: "me" }).then((result) =>
console.log(result)
);
}
```
Use the Convex CLI to push your functions to a deployment. See everything
the Convex CLI can do by running `npx convex -h` in your project root
directory. To learn more, launch the docs with `npx convex docs`.
+6 -1
View File
@@ -14,6 +14,8 @@ import type {
FilterApi,
FunctionReference,
} from "convex/server";
import type * as http from "../http";
import type * as users from "../users";
/**
* A utility for referencing Convex functions in your app's API.
@@ -23,7 +25,10 @@ import type {
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
declare const fullApi: ApiFromModules<{}>;
declare const fullApi: ApiFromModules<{
http: typeof http;
users: typeof users;
}>;
export declare const api: FilterApi<
typeof fullApi,
FunctionReference<any, "public">
+14 -17
View File
@@ -9,29 +9,25 @@
* @module
*/
import { AnyDataModel } from "convex/server";
import type { DataModelFromSchemaDefinition } from "convex/server";
import type { DocumentByName, TableNamesInDataModel } from "convex/server";
import type { GenericId } from "convex/values";
/**
* No `schema.ts` file found!
*
* This generated code has permissive types like `Doc = any` because
* Convex doesn't know your schema. If you'd like more type safety, see
* https://docs.convex.dev/using/schemas for instructions on how to add a
* schema file.
*
* After you change a schema, rerun codegen with `npx convex dev`.
*/
import schema from "../schema";
/**
* The names of all of your Convex tables.
*/
export type TableNames = string;
export type TableNames = TableNamesInDataModel<DataModel>;
/**
* The type of a document stored in Convex.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Doc = any;
export type Doc<TableName extends TableNames> = DocumentByName<
DataModel,
TableName
>;
/**
* An identifier for a document in Convex.
@@ -43,9 +39,10 @@ export type Doc = any;
*
* IDs are just strings at runtime, but this type can be used to distinguish them from other
* strings when type checking.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Id<TableName extends TableNames = TableNames> =
GenericId<TableName>;
export type Id<TableName extends TableNames> = GenericId<TableName>;
/**
* A type describing your Convex data model.
@@ -56,4 +53,4 @@ export type Id<TableName extends TableNames = TableNames> =
* This type is used to parameterize methods like `queryGeneric` and
* `mutationGeneric` to make them type-safe.
*/
export type DataModel = AnyDataModel;
export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
+86
View File
@@ -0,0 +1,86 @@
import type { WebhookEvent } from '@clerk/backend';
import { httpRouter } from 'convex/server';
import { Webhook } from 'svix';
import { internal } from './_generated/api';
import { httpAction } from './_generated/server';
async function validateRequest(
req: Request
): Promise<WebhookEvent | undefined> {
const payloadString = await req.text();
const svixHeaders = {
'svix-id': req.headers.get('svix-id')!,
'svix-timestamp': req.headers.get('svix-timestamp')!,
'svix-signature': req.headers.get('svix-signature')!,
};
const webhookSecret = process.env.CLERK_WEBHOOK_SECRET;
if (webhookSecret === undefined) {
throw Error('CLERK_WEBHOOK_SECRET is undefined');
}
const wh = new Webhook(webhookSecret);
let evt: Event | null = null;
try {
evt = wh.verify(payloadString, svixHeaders) as Event;
} catch (error) {
console.log(error);
return;
}
return evt as unknown as WebhookEvent;
}
const handleClerkWebhook = httpAction(async (ctx, request) => {
const event = await validateRequest(request);
if (!event) {
return new Response('Error occurred', {
status: 400,
});
}
switch (event.type) {
case 'user.created':
case 'user.updated': {
const existingUser = await ctx.runQuery(internal.users.getUser, {
subject: event.data.id,
});
if (existingUser && event.type === 'user.created') {
console.warn('Overwriting user', event.data.id, 'with', event.data);
}
console.log('creating/updating user', event.data.id);
await ctx.runMutation(internal.users.updateOrCreateUser, {
clerkUser: event.data,
});
break;
}
case 'user.deleted': {
const id = event.data.id!;
await ctx.runMutation(internal.users.deleteUser, { id });
break;
}
default: {
console.log('ignored Clerk webhook event', event.type);
}
}
return new Response(null, {
status: 200,
});
});
const http = httpRouter();
http.route({
path: '/clerk-users-webhook',
method: 'POST',
handler: handleClerkWebhook,
});
export default http;
+8
View File
@@ -0,0 +1,8 @@
import { defineSchema, defineTable } from 'convex/server';
import { v } from 'convex/values';
export default defineSchema({
users: defineTable({
clerkUser: v.any(),
}).index('by_clerk_id', ['clerkUser.id']),
});
+49
View File
@@ -0,0 +1,49 @@
import { UserJSON } from '@clerk/nextjs/dist/types/server';
import { v } from 'convex/values';
import { Doc } from './_generated/dataModel';
import { QueryCtx, internalMutation, internalQuery } from './_generated/server';
export const getUser = internalQuery({
args: { subject: v.string() },
async handler(ctx, args) {
return await userQuery(ctx, args.subject);
},
});
export async function userQuery(
ctx: QueryCtx,
clerkUserId: string
): Promise<(Omit<Doc<'users'>, 'clerkUser'> & { clerkUser: UserJSON }) | null> {
return await ctx.db
.query('users')
.withIndex('by_clerk_id', q => q.eq('clerkUser.id', clerkUserId))
.unique();
}
export const updateOrCreateUser = internalMutation({
args: { clerkUser: v.any() },
async handler(ctx, { clerkUser }: { clerkUser: UserJSON }) {
const userRecord = await userQuery(ctx, clerkUser.id);
if (userRecord === null) {
await ctx.db.insert('users', { clerkUser });
return;
}
await ctx.db.patch(userRecord._id, { clerkUser });
},
});
export const deleteUser = internalMutation({
args: { id: v.string() },
async handler(ctx, { id }) {
const userRecord = await userQuery(ctx, id);
if (userRecord === null) {
console.warn("can't delete user, does not exist", id);
return;
}
await ctx.db.delete(userRecord._id);
},
});