feat: delete all users posts when user is deleted

This commit is contained in:
Stevan Freeborn
2023-09-10 20:19:31 -05:00
parent 90f95e50a5
commit 1ad65d8b30
12 changed files with 1452 additions and 107 deletions
+2
View File
@@ -15,6 +15,7 @@ import type {
FunctionReference,
} from "convex/server";
import type * as http from "../http";
import type * as posts from "../posts";
import type * as users from "../users";
/**
@@ -27,6 +28,7 @@ import type * as users from "../users";
*/
declare const fullApi: ApiFromModules<{
http: typeof http;
posts: typeof posts;
users: typeof users;
}>;
export declare const api: FilterApi<
+33
View File
@@ -0,0 +1,33 @@
import { v } from 'convex/values';
import { mutation } from './_generated/server';
import { userQuery } from './users';
export const createPost = mutation({
args: {
clerkUserId: v.string(),
content: v.array(v.string()),
parentPostId: v.optional(v.id('posts')),
},
handler: async (ctx, args) => {
const userIdentity = await ctx.auth.getUserIdentity();
const user = await userQuery(ctx, args.clerkUserId);
if (userIdentity === null) {
return 'USER_NOT_AUTHORIZED';
}
if (user === null) {
return 'USER_NOT_FOUND';
}
if (userIdentity.subject !== args.clerkUserId) {
return 'CANNOT_POST_ON_BEHALF_OF_ANOTHER_USER';
}
return await ctx.db.insert('posts', {
userId: user._id,
content: args.content,
parentPostId: args.parentPostId,
});
},
});
+13 -17
View File
@@ -1,19 +1,15 @@
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']),
posts: defineTable({
userId: v.id('users'),
content: v.array(v.string()),
likes: v.array(v.id('users')),
replies: v.array(
v.object({
userId: v.id('users'),
content: v.array(v.string()),
})
),
}),
});
export default defineSchema(
{
users: defineTable({
clerkUser: v.any(),
}).index('by_clerk_id', ['clerkUser.id']),
posts: defineTable({
parentPostId: v.optional(v.id('posts')),
userId: v.id('users'),
content: v.array(v.string()),
}).index('by_user_id', ['userId']),
},
{ schemaValidation: false }
);
+13
View File
@@ -44,6 +44,19 @@ export const deleteUser = internalMutation({
return;
}
const userPosts = await ctx.db
.query('posts')
.withIndex('by_user_id', q => q.eq('userId', userRecord._id))
.collect();
const userPostDeletePromises = [];
for (const post of userPosts) {
userPostDeletePromises.push(ctx.db.delete(post._id));
}
await Promise.all(userPostDeletePromises);
await ctx.db.delete(userRecord._id);
},
});