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
+3 -1
View File
@@ -4,9 +4,11 @@
"codemirror", "codemirror",
"conve", "conve",
"Keymap", "Keymap",
"lezer",
"nextjs", "nextjs",
"rehype", "rehype",
"signup", "signup",
"svix" "svix",
"tailwindcss"
] ]
} }
+2
View File
@@ -15,6 +15,7 @@ import type {
FunctionReference, FunctionReference,
} from "convex/server"; } from "convex/server";
import type * as http from "../http"; import type * as http from "../http";
import type * as posts from "../posts";
import type * as users from "../users"; import type * as users from "../users";
/** /**
@@ -27,6 +28,7 @@ import type * as users from "../users";
*/ */
declare const fullApi: ApiFromModules<{ declare const fullApi: ApiFromModules<{
http: typeof http; http: typeof http;
posts: typeof posts;
users: typeof users; users: typeof users;
}>; }>;
export declare const api: FilterApi< 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 { defineSchema, defineTable } from 'convex/server';
import { v } from 'convex/values'; import { v } from 'convex/values';
export default defineSchema(
export default defineSchema({ {
users: defineTable({ users: defineTable({
clerkUser: v.any(), clerkUser: v.any(),
}).index('by_clerk_id', ['clerkUser.id']), }).index('by_clerk_id', ['clerkUser.id']),
posts: defineTable({ posts: defineTable({
userId: v.id('users'), parentPostId: v.optional(v.id('posts')),
content: v.array(v.string()), userId: v.id('users'),
likes: v.array(v.id('users')), content: v.array(v.string()),
replies: v.array( }).index('by_user_id', ['userId']),
v.object({ },
userId: v.id('users'), { schemaValidation: false }
content: v.array(v.string()), );
})
),
}),
});
+13
View File
@@ -44,6 +44,19 @@ export const deleteUser = internalMutation({
return; 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); await ctx.db.delete(userRecord._id);
}, },
}); });
+1 -1
View File
@@ -2,7 +2,7 @@ import Editor from '@/components/Editor';
export default function AddPost() { export default function AddPost() {
return ( return (
<main> <main className='flex flex-col w-full h-full'>
<Editor /> <Editor />
</main> </main>
); );
+64 -45
View File
@@ -1,34 +1,38 @@
'use client'; 'use client';
import { useCodeMirror } from '@/hooks'; import { useCodeMirror } from '@/hooks';
import { darkTheme } from '@/lib/codemirror'; import { basicDark } from '@/lib/codemirror';
import { useUser } from '@clerk/nextjs';
import { indentWithTab } from '@codemirror/commands'; import { indentWithTab } from '@codemirror/commands';
import { markdown, markdownLanguage } from '@codemirror/lang-markdown'; import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
import { languages } from '@codemirror/language-data'; import { languages } from '@codemirror/language-data';
import { Compartment, EditorState } from '@codemirror/state'; import { Compartment, EditorState, Text } from '@codemirror/state';
import { EditorView, keymap } from '@codemirror/view'; import { EditorView, keymap } from '@codemirror/view';
import { basicSetup } from 'codemirror'; import { basicSetup } from 'codemirror';
import { useMutation } from 'convex/react';
import { useTheme } from 'next-themes'; import { useTheme } from 'next-themes';
import { useEffect, useState } from 'react'; import { useRouter } from 'next/navigation';
import ReactMarkdown from 'react-markdown'; import { FormEvent, useEffect, useState } from 'react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import { api } from '../../convex/_generated/api';
import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism'; import PostContent from './PostContent';
import remarkGfm from 'remark-gfm';
export default function Editor() { export default function Editor() {
const user = useUser();
const { theme } = useTheme(); const { theme } = useTheme();
const editorTheme = new Compartment(); const editorTheme = new Compartment();
const [currentDoc, setCurrentDoc] = useState(''); const [currentDoc, setCurrentDoc] = useState(['']);
const createPost = useMutation(api.posts.createPost);
const router = useRouter();
const doc = ['']; const doc = [''];
const extensions = [ const extensions = [
basicSetup, basicSetup,
markdown({ base: markdownLanguage, codeLanguages: languages }), markdown({ base: markdownLanguage, codeLanguages: languages }),
EditorState.tabSize.of(2), EditorState.tabSize.of(2),
editorTheme.of([]), editorTheme.of(basicDark),
keymap.of([indentWithTab]), keymap.of([indentWithTab]),
EditorView.updateListener.of(vu => { EditorView.updateListener.of(vu => {
setCurrentDoc(vu.state.doc.toString()); setCurrentDoc(vu.state.doc.toJSON());
}), }),
]; ];
@@ -42,18 +46,48 @@ export default function Editor() {
if (theme === 'dark') { if (theme === 'dark') {
editorView.dispatch({ editorView.dispatch({
effects: editorTheme.reconfigure([darkTheme]), effects: editorTheme.reconfigure([]),
}); });
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [theme, editorView]); }, [theme, editorView]);
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
try {
if (user.isSignedIn !== true) {
router.push('/login');
return;
}
const result = await createPost({
clerkUserId: user.user.id,
content: currentDoc,
});
switch (result) {
case 'USER_NOT_FOUND':
case 'USER_NOT_AUTHORIZED':
case 'CANNOT_POST_ON_BEHALF_OF_ANOTHER_USER':
throw Error('Unable to create post');
default:
router.push('/');
return;
}
} catch (error) {
console.log(error);
}
}
return ( return (
<form className='flex flex-col shadow-md rounded-md dark:bg-secondary-gray border border-gray-600'> <form
onSubmit={handleSubmit}
className='flex flex-col flex-1 shadow-md rounded-md dark:bg-secondary-gray border border-gray-600'
>
<div className='flex items-center justify-between rounded-t-md p-4 pb-0 border-b border-gray-600 dark:bg-primary-gray'> <div className='flex items-center justify-between rounded-t-md p-4 pb-0 border-b border-gray-600 dark:bg-primary-gray'>
<div className='flex items-center'> <div className='flex items-center'>
<button <button
className='flex items-center justify-center px-3 py-2 rounded-t-md -mb-[1px] disabled:dark:bg-secondary-gray disabled:border disabled:border-gray-600 disabled:border-b-0' className='flex items-center justify-center px-3 py-2 rounded-t-md -mb-[1px] disabled:bg-white disabled:border disabled:border-b-0 disabled:border-gray-600 disabled:dark:bg-secondary-gray'
disabled={mode === 'write'} disabled={mode === 'write'}
onClick={() => setMode('write')} onClick={() => setMode('write')}
type='button' type='button'
@@ -61,7 +95,7 @@ export default function Editor() {
Write Write
</button> </button>
<button <button
className='flex items-center justify-center px-3 py-2 rounded-t-md disabled:dark:bg-secondary-gray disabled:border disabled:border-gray-600 disabled:border-b-0' className='flex items-center justify-center px-3 py-2 rounded-t-md -mb-[1px] disabled:bg-white disabled:border disabled:border-b-0 disabled:border-gray-600 disabled:dark:bg-secondary-gray'
disabled={mode === 'preview'} disabled={mode === 'preview'}
onClick={() => setMode('preview')} onClick={() => setMode('preview')}
type='button' type='button'
@@ -71,42 +105,27 @@ export default function Editor() {
</div> </div>
<div></div> <div></div>
</div> </div>
<div className='p-4'> <div className='flex flex-col p-4 h-0 flex-grow'>
<div <div
className={`${mode === 'write' ? '' : 'hidden'}`} className={`${mode === 'write' ? '' : 'hidden'} flex-1 overflow-auto`}
ref={editorRef} ref={editorRef}
></div> ></div>
<ReactMarkdown <div
className={`${mode === 'preview' ? '' : 'hidden'}`} className={`${
remarkPlugins={[remarkGfm]} mode === 'preview' ? '' : 'hidden'
components={{ } flex-1 overflow-auto`}
code({ node, inline, className, children, ...props }) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<SyntaxHighlighter
{...props}
style={oneDark}
language={match[1]}
PreTag='div'
>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
) : (
<code
{...props}
className={className}
>
{children}
</code>
);
},
}}
> >
{currentDoc} <PostContent content={Text.of(currentDoc).toString()} />
</ReactMarkdown> </div>
</div> </div>
<div className='flex items-center justify-end'> <div className='flex items-center justify-end p-4 pt-0'>
<button type='submit'>Post</button> <button
type='submit'
disabled={!currentDoc.join() || !currentDoc.join().trim()}
className='py-1 px-4 bg-primary-accent text-white rounded-md disabled:opacity-50'
>
Post
</button>
</div> </div>
</form> </form>
); );
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -1,6 +1,7 @@
import { SignedIn, SignedOut, UserButton } from '@clerk/nextjs'; import { SignedIn, SignedOut, UserButton } from '@clerk/nextjs';
import Link from 'next/link'; import Link from 'next/link';
import { BiSolidMessageSquareAdd } from 'react-icons/bi'; import { BiSolidMessageSquareAdd } from 'react-icons/bi';
import ProfileLink from './ProfileLink';
import ThemeButton from './ThemeButton'; import ThemeButton from './ThemeButton';
export default function Navbar() { export default function Navbar() {
@@ -30,7 +31,7 @@ export default function Navbar() {
<Link href='#'>Following</Link> <Link href='#'>Following</Link>
</li> </li>
<li> <li>
<Link href='#'>Profile</Link> <ProfileLink />
</li> </li>
<li> <li>
<Link <Link
+40
View File
@@ -0,0 +1,40 @@
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
import remarkGfm from 'remark-gfm';
import './MarkdownContent.css';
export default function PostContent({ content }: { content: string }) {
return (
<div className='markdown-content'>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
code({ node, inline, className, children, ...props }) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<SyntaxHighlighter
{...props}
style={oneDark}
language={match[1]}
PreTag='div'
>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
) : (
<code
{...props}
className={className}
>
{children}
</code>
);
},
}}
>
{content}
</ReactMarkdown>
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
'use client';
import { useUser } from '@clerk/nextjs';
import Link from 'next/link';
export default function ProfileLink() {
const user = useUser();
if (user.isSignedIn !== true) {
return <span>Profile</span>;
}
return <Link href={`/profile/${user.user.id}`}>Profile</Link>;
}
+169 -42
View File
@@ -1,80 +1,207 @@
import { HighlightStyle } from '@codemirror/language'; import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';
import { Extension } from '@codemirror/state';
import { EditorView } from '@codemirror/view'; import { EditorView } from '@codemirror/view';
import { tags as t } from '@lezer/highlight'; import { tags as t } from '@lezer/highlight';
export const darkTheme = EditorView.theme( const base00 = '#24272d';
const base01 = '#DDDDDD';
const base02 = '#B9D2FF';
const base03 = '#b0b0b0';
const base05 = '#e0e0e0';
const base06 = '#808080';
const base07 = '#000000';
const base08 = '#A54543';
const base09 = '#fc6d24';
const base0A = '#fda331';
const base0B = '#8abeb7';
const base0C = '#b5bd68';
const base0D = '#6fb3d2';
const base0E = '#cc99cc';
const base0F = '#6987AF';
const invalid = base09;
const darkBackground = base00;
const highlightBackground = base02 + '30';
const background = base00;
const tooltipBackground = base01;
const selection = '#202325';
const cursor = base01;
const basicDarkTheme = EditorView.theme(
{ {
'&': { '&': {
backgroundColor: '#24272d', height: '100%',
color: '#d0d9e4', color: base01,
backgroundColor: background,
borderRadius: '0.375rem',
padding: '0.5rem 0',
},
'.cm-gutter': {
height: '100%', height: '100%',
}, },
'.cm-content': { '.cm-content': {
caretColor: '#f8f8f0', caretColor: cursor,
height: '100%',
}, },
'.cm-content, .cm-gutter': { height: '100%' }, '.cm-scroller': {
'.cm-scroller': { overflow: 'auto' }, overflow: 'auto',
'.cm-cursor, .cm-dropCursor': {
borderLeftColor: '#f8f8f0',
}, },
'&.cm-focused': { '.cm-cursor, .cm-dropCursor': { borderLeftColor: cursor },
outline: 'none', '&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection':
{ backgroundColor: selection },
'.cm-panels': { backgroundColor: darkBackground, color: base03 },
'.cm-panels.cm-panels-top': { borderBottom: '2px solid black' },
'.cm-panels.cm-panels-bottom': { borderTop: '2px solid black' },
'.cm-searchMatch': {
backgroundColor: base02,
outline: `1px solid ${base03}`,
color: base07,
}, },
'&.cm-focused .cm-selectionBackground .cm-selectionBackground, .cm-content ::selection': '.cm-searchMatch.cm-searchMatch-selected': {
{ backgroundColor: base05,
backgroundColor: '#2f333a', color: base07,
}, },
'.cm-activeLine': { '.cm-activeLine': { backgroundColor: highlightBackground },
backgroundColor: 'transparent', '.cm-selectionMatch': { backgroundColor: highlightBackground },
'&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket': {
outline: `1px solid ${base03}`,
},
'&.cm-focused .cm-matchingBracket': {
backgroundColor: base02,
color: base07,
}, },
'.cm-gutters': { '.cm-gutters': {
border: 'none', borderRight: `none`,
backgroundColor: '#24272d', color: base06,
color: 'd0d9e4', backgroundColor: darkBackground,
}, },
'.cm-activeLineGutter': { '.cm-activeLineGutter': {
backgroundColor: highlightBackground,
},
'.cm-foldPlaceholder': {
backgroundColor: 'transparent', backgroundColor: 'transparent',
border: 'none',
color: base02,
},
'.cm-tooltip': {
border: 'none',
backgroundColor: tooltipBackground,
},
'.cm-tooltip .cm-tooltip-arrow:before': {
borderTopColor: 'transparent',
borderBottomColor: 'transparent',
},
'.cm-tooltip .cm-tooltip-arrow:after': {
borderTopColor: tooltipBackground,
borderBottomColor: tooltipBackground,
},
'.cm-tooltip-autocomplete': {
'& > ul > li[aria-selected]': {
backgroundColor: highlightBackground,
color: base03,
},
}, },
}, },
{ dark: true } { dark: true }
); );
export const highlightStyle = HighlightStyle.define([ const basicDarkHighlightStyle = HighlightStyle.define([
{ tag: t.keyword, color: base0A },
{ {
tag: t.comment, tag: [t.name, t.deleted, t.character, t.propertyName, t.macroName],
color: '#6272a4', color: base0C,
},
{ tag: [t.variableName], color: base0D },
{ tag: [t.function(t.variableName)], color: base0A },
{ tag: [t.labelName], color: base09 },
{
tag: [t.color, t.constant(t.name), t.standard(t.name)],
color: base0A,
},
{ tag: [t.definition(t.name), t.separator], color: base0E },
{ tag: [t.brace], color: base0E },
{
tag: [t.annotation],
color: invalid,
}, },
{ {
tag: [t.string, t.special(t.brace)], tag: [t.number, t.changed, t.annotation, t.modifier, t.self, t.namespace],
color: '#f1fa8c', color: base0A,
}, },
{ {
tag: [t.number, t.self, t.bool, t.null], tag: [t.typeName, t.className],
color: '#bd93f9', color: base0D,
}, },
{ {
tag: [t.keyword, t.operator], tag: [t.operator, t.operatorKeyword],
color: '#ff79c6', color: base0E,
}, },
{ {
tag: [t.definitionKeyword, t.typeName], tag: [t.tagName],
color: '#8be9fd', color: base0A,
}, },
{ {
tag: t.definition(t.typeName), tag: [t.squareBracket],
color: '#f8f8f2', color: base0E,
}, },
{ {
tag: [ tag: [t.angleBracket],
t.className, color: base0E,
t.definition(t.propertyName),
t.function(t.variableName),
t.attributeName,
],
color: '#50fa7b',
}, },
{ {
tag: [t.heading], tag: [t.attributeName],
color: '#50fa7b', color: base0D,
}, },
{
tag: [t.regexp],
color: base0A,
},
{
tag: [t.quote],
color: base01,
},
{ tag: [t.string], color: base0C },
{
tag: t.link,
color: base0F,
textDecoration: 'underline',
textUnderlinePosition: 'under',
},
{
tag: [t.url, t.escape, t.special(t.string)],
color: base0B,
},
{ tag: [t.meta], color: base08 },
{ tag: [t.comment], color: base06, fontStyle: 'italic' },
{ tag: t.monospace, color: base01 },
{ tag: t.strong, fontWeight: 'bold', color: base0A },
{ tag: t.emphasis, fontStyle: 'italic', color: base0D },
{ tag: t.strikethrough, textDecoration: 'line-through' },
{ tag: t.heading, fontWeight: 'bold', color: base01 },
{ tag: t.special(t.heading1), fontWeight: 'bold', color: base01 },
{ tag: t.heading1, fontWeight: 'bold', color: base01 },
{
tag: [t.heading2, t.heading3, t.heading4],
fontWeight: 'bold',
color: base01,
},
{
tag: [t.heading5, t.heading6],
color: base01,
},
{ tag: [t.atom, t.bool, t.special(t.variableName)], color: base0B },
{
tag: [t.processingInstruction, t.inserted],
color: base0B,
},
{
tag: [t.contentSeparator],
color: base0D,
},
{ tag: t.invalid, color: base02, borderBottom: `1px dotted ${invalid}` },
]); ]);
export const basicDark: Extension = [
basicDarkTheme,
syntaxHighlighting(basicDarkHighlightStyle),
];