113 | );
114 | }
115 |
--------------------------------------------------------------------------------
/src/components/PageLayout.tsx:
--------------------------------------------------------------------------------
1 | import { Link, useLocation } from "react-router-dom";
2 | import { UserMenu } from "@/components/UserMenu";
3 | import { Search } from "@/components/Search";
4 | import type { ReactNode } from "react";
5 | import { GitHubLogoIcon, StarFilledIcon } from "@radix-ui/react-icons";
6 | import { cn } from "@/lib/utils";
7 | import { buttonVariants } from "./ui/button";
8 |
9 | function StarUsLink() {
10 | return (
11 |
20 |
21 |
22 |
23 |
24 |
28 | Star us on GitHub
29 |
30 |
31 | );
32 | }
33 |
34 | export function Header() {
35 | const location = useLocation();
36 | return (
37 |
38 |
70 |
71 | );
72 | }
73 |
74 | export function Footer() {
75 | return (
76 |
88 | );
89 | }
90 |
91 | function FooterLink({ href, children }: { href: string; children: ReactNode }) {
92 | return (
93 |
98 | {children}
99 |
100 | );
101 | }
102 |
--------------------------------------------------------------------------------
/convex/_generated/server.js:
--------------------------------------------------------------------------------
1 | /* prettier-ignore-start */
2 |
3 | /* eslint-disable */
4 | /**
5 | * Generated utilities for implementing server-side Convex query and mutation functions.
6 | *
7 | * THIS CODE IS AUTOMATICALLY GENERATED.
8 | *
9 | * To regenerate, run `npx convex dev`.
10 | * @module
11 | */
12 |
13 | import {
14 | actionGeneric,
15 | httpActionGeneric,
16 | queryGeneric,
17 | mutationGeneric,
18 | internalActionGeneric,
19 | internalMutationGeneric,
20 | internalQueryGeneric,
21 | } from "convex/server";
22 |
23 | /**
24 | * Define a query in this Convex app's public API.
25 | *
26 | * This function will be allowed to read your Convex database and will be accessible from the client.
27 | *
28 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
29 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
30 | */
31 | export const query = queryGeneric;
32 |
33 | /**
34 | * Define a query that is only accessible from other Convex functions (but not from the client).
35 | *
36 | * This function will be allowed to read from your Convex database. It will not be accessible from the client.
37 | *
38 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
39 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
40 | */
41 | export const internalQuery = internalQueryGeneric;
42 |
43 | /**
44 | * Define a mutation in this Convex app's public API.
45 | *
46 | * This function will be allowed to modify your Convex database and will be accessible from the client.
47 | *
48 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
49 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
50 | */
51 | export const mutation = mutationGeneric;
52 |
53 | /**
54 | * Define a mutation that is only accessible from other Convex functions (but not from the client).
55 | *
56 | * This function will be allowed to modify your Convex database. It will not be accessible from the client.
57 | *
58 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
59 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
60 | */
61 | export const internalMutation = internalMutationGeneric;
62 |
63 | /**
64 | * Define an action in this Convex app's public API.
65 | *
66 | * An action is a function which can execute any JavaScript code, including non-deterministic
67 | * code and code with side-effects, like calling third-party services.
68 | * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
69 | * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
70 | *
71 | * @param func - The action. It receives an {@link ActionCtx} as its first argument.
72 | * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
73 | */
74 | export const action = actionGeneric;
75 |
76 | /**
77 | * Define an action that is only accessible from other Convex functions (but not from the client).
78 | *
79 | * @param func - The function. It receives an {@link ActionCtx} as its first argument.
80 | * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
81 | */
82 | export const internalAction = internalActionGeneric;
83 |
84 | /**
85 | * Define a Convex HTTP action.
86 | *
87 | * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object
88 | * as its second.
89 | * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`.
90 | */
91 | export const httpAction = httpActionGeneric;
92 |
93 | /* prettier-ignore-end */
94 |
--------------------------------------------------------------------------------
/src/components/Author/Edit.tsx:
--------------------------------------------------------------------------------
1 | import { useMutation } from "convex/react";
2 | import { api } from "../../../convex/_generated/api";
3 | import { zodResolver } from "@hookform/resolvers/zod";
4 | import { Label } from "@/components/ui/label";
5 | import { Switch } from "@/components/ui/switch";
6 | import { Form } from "@/components/ui/form";
7 | import { useState, type FormEventHandler } from "react";
8 | import { useForm, type SubmitHandler } from "react-hook-form";
9 | import { useNavigate } from "react-router-dom";
10 | import { z } from "zod";
11 | import { Toolbar } from "@/components/Toolbar";
12 | import { TextField, MarkdownField } from "@/components/Inputs";
13 | import { Button } from "@/components/ui/button";
14 | import { useToast } from "@/components/ui/use-toast";
15 | import type { Doc } from "../../../convex/_generated/dataModel";
16 | import { usersZod } from "../../../convex/schema";
17 | import { AuthorProfile } from "./Profile";
18 |
19 | export function EditableProfile({ user }: { user: Doc<"users"> }) {
20 | const { toast } = useToast();
21 | const navigate = useNavigate();
22 |
23 | const [previewing, setPreviewing] = useState(false);
24 |
25 | const update = useMutation(api.users.update);
26 |
27 | const zodSchema = z.object(usersZod);
28 | const defaultValues = user;
29 |
30 | const form = useForm>({
31 | defaultValues,
32 | resolver: zodResolver(zodSchema),
33 | });
34 |
35 | const onReset = () => {
36 | form.reset(defaultValues);
37 | navigate(`/authors/${user._id}`);
38 | };
39 |
40 | const onSubmit: SubmitHandler> = async (data) => {
41 | try {
42 | await update({ id: user._id, patch: data });
43 | toast({
44 | title: "User Profile Updated",
45 | });
46 | form.reset(data);
47 | navigate(`/authors/${user._id}`);
48 | } catch (e) {
49 | const error = e as Error;
50 | toast({
51 | variant: "destructive",
52 | title: "Error Updating Profile",
53 | description: error.message,
54 | });
55 | }
56 | };
57 |
58 | // Wrapper for form.handleSubmit to avoid no-misused-promises error;
59 | // see https://github.com/orgs/react-hook-form/discussions/8020
60 | const submitHandler: FormEventHandler = (...args) =>
61 | void form.handleSubmit(onSubmit)(...args);
62 |
63 | const { isValid, isDirty } = form.formState;
64 | const values = form.getValues();
65 |
66 | return (
67 | <>
68 |
69 |
47 | This template is a starting point for building your content-driven
48 | fullstack web application.
49 |
50 |
51 | To prevent abuse, the content in the public demo app hosted at{" "}
52 |
57 | convex-cms.com
58 | {" "}
59 | is reset daily using a Convex{" "}
60 |
65 | cron job
66 | {" "}
67 | defined in convex/crons.ts. You can edit & create new
68 | posts, but your changes will be deleted within 24 hours.
69 |
70 |
Explore the code
71 |
72 |
73 |
74 |
75 | Inspect the database
76 |
77 |
78 |
79 | Open the{" "}
80 |
85 | Convex dashboard
86 | {" "}
87 | in another window.
88 |
89 |
90 |
91 |
92 |
93 |
94 | Change the backend
95 |
96 |
97 |
98 | Edit the functions in the convex/ directory to change
99 | the backend functionality.
100 |
101 |
102 |
103 |
104 |
105 |
106 | Change the frontend
107 |
108 |
109 |
110 | Edit src/components and src/pages to
111 | change your frontend.
112 |
113 |
114 |
115 |
116 |
Helpful resources
117 |
118 |
119 | Read comprehensive documentation for all Convex features.
120 |
121 |
122 | Learn about best practices, use cases, and more from a growing
123 | collection of articles, videos, and walkthroughs.
124 |
125 |
126 | Join our developer community to ask questions, trade tips & tricks,
127 | and show off your projects.
128 |
129 |
130 | Get unblocked quickly by searching across the docs, Stack, and
131 | Discord chats.
132 |
133 |
134 |
135 |
136 | );
137 | }
138 |
139 | function Resource({
140 | title,
141 | children,
142 | href,
143 | }: {
144 | title: string;
145 | children: ReactNode;
146 | href: string;
147 | }) {
148 | return (
149 |
162 | );
163 | }
164 |
--------------------------------------------------------------------------------
/convex/_generated/server.d.ts:
--------------------------------------------------------------------------------
1 | /* prettier-ignore-start */
2 |
3 | /* eslint-disable */
4 | /**
5 | * Generated utilities for implementing server-side Convex query and mutation functions.
6 | *
7 | * THIS CODE IS AUTOMATICALLY GENERATED.
8 | *
9 | * To regenerate, run `npx convex dev`.
10 | * @module
11 | */
12 |
13 | import {
14 | ActionBuilder,
15 | HttpActionBuilder,
16 | MutationBuilder,
17 | QueryBuilder,
18 | GenericActionCtx,
19 | GenericMutationCtx,
20 | GenericQueryCtx,
21 | GenericDatabaseReader,
22 | GenericDatabaseWriter,
23 | } from "convex/server";
24 | import type { DataModel } from "./dataModel.js";
25 |
26 | /**
27 | * Define a query in this Convex app's public API.
28 | *
29 | * This function will be allowed to read your Convex database and will be accessible from the client.
30 | *
31 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
32 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
33 | */
34 | export declare const query: QueryBuilder;
35 |
36 | /**
37 | * Define a query that is only accessible from other Convex functions (but not from the client).
38 | *
39 | * This function will be allowed to read from your Convex database. It will not be accessible from the client.
40 | *
41 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
42 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
43 | */
44 | export declare const internalQuery: QueryBuilder;
45 |
46 | /**
47 | * Define a mutation in this Convex app's public API.
48 | *
49 | * This function will be allowed to modify your Convex database and will be accessible from the client.
50 | *
51 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
52 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
53 | */
54 | export declare const mutation: MutationBuilder;
55 |
56 | /**
57 | * Define a mutation that is only accessible from other Convex functions (but not from the client).
58 | *
59 | * This function will be allowed to modify your Convex database. It will not be accessible from the client.
60 | *
61 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
62 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
63 | */
64 | export declare const internalMutation: MutationBuilder;
65 |
66 | /**
67 | * Define an action in this Convex app's public API.
68 | *
69 | * An action is a function which can execute any JavaScript code, including non-deterministic
70 | * code and code with side-effects, like calling third-party services.
71 | * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
72 | * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
73 | *
74 | * @param func - The action. It receives an {@link ActionCtx} as its first argument.
75 | * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
76 | */
77 | export declare const action: ActionBuilder;
78 |
79 | /**
80 | * Define an action that is only accessible from other Convex functions (but not from the client).
81 | *
82 | * @param func - The function. It receives an {@link ActionCtx} as its first argument.
83 | * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
84 | */
85 | export declare const internalAction: ActionBuilder;
86 |
87 | /**
88 | * Define an HTTP action.
89 | *
90 | * This function will be used to respond to HTTP requests received by a Convex
91 | * deployment if the requests matches the path and method where this action
92 | * is routed. Be sure to route your action in `convex/http.js`.
93 | *
94 | * @param func - The function. It receives an {@link ActionCtx} as its first argument.
95 | * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
96 | */
97 | export declare const httpAction: HttpActionBuilder;
98 |
99 | /**
100 | * A set of services for use within Convex query functions.
101 | *
102 | * The query context is passed as the first argument to any Convex query
103 | * function run on the server.
104 | *
105 | * This differs from the {@link MutationCtx} because all of the services are
106 | * read-only.
107 | */
108 | export type QueryCtx = GenericQueryCtx;
109 |
110 | /**
111 | * A set of services for use within Convex mutation functions.
112 | *
113 | * The mutation context is passed as the first argument to any Convex mutation
114 | * function run on the server.
115 | */
116 | export type MutationCtx = GenericMutationCtx;
117 |
118 | /**
119 | * A set of services for use within Convex action functions.
120 | *
121 | * The action context is passed as the first argument to any Convex action
122 | * function run on the server.
123 | */
124 | export type ActionCtx = GenericActionCtx;
125 |
126 | /**
127 | * An interface to read from the database within Convex query functions.
128 | *
129 | * The two entry points are {@link DatabaseReader.get}, which fetches a single
130 | * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
131 | * building a query.
132 | */
133 | export type DatabaseReader = GenericDatabaseReader;
134 |
135 | /**
136 | * An interface to read from and write to the database within Convex mutation
137 | * functions.
138 | *
139 | * Convex guarantees that all writes within a single mutation are
140 | * executed atomically, so you never have to worry about partial writes leaving
141 | * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
142 | * for the guarantees Convex provides your functions.
143 | */
144 | export type DatabaseWriter = GenericDatabaseWriter;
145 |
146 | /* prettier-ignore-end */
147 |
--------------------------------------------------------------------------------
/src/components/Inputs.tsx:
--------------------------------------------------------------------------------
1 | import { Input } from "./ui/input";
2 | import type {
3 | FieldPath,
4 | FieldValue,
5 | FieldValues,
6 | UseFormReturn,
7 | } from "react-hook-form";
8 | import {
9 | FormField,
10 | FormItem,
11 | FormLabel,
12 | FormControl,
13 | FormMessage,
14 | FormDescription,
15 | } from "./ui/form";
16 | import { Textarea } from "./ui/textarea";
17 | import { useMutation, useQuery } from "convex/react";
18 | import { api } from "../../convex/_generated/api";
19 | import {
20 | UploadButton,
21 | type UploadFileResponse,
22 | } from "@xixixao/uploadstuff/react";
23 | import "@xixixao/uploadstuff/react/styles.css";
24 | import type { Id } from "../../convex/_generated/dataModel";
25 | import { useToast } from "./ui/use-toast";
26 | import { useEffect, useState } from "react";
27 |
28 | interface CommonProps {
29 | name: FieldPath;
30 | form: UseFormReturn;
31 | }
32 |
33 | interface TextFieldProps
34 | extends CommonProps {
35 | hidden?: boolean;
36 | required?: boolean;
37 | itemClass?: string;
38 | controlClass?: string;
39 | }
40 |
41 | export function TextField({
42 | name,
43 | form,
44 | hidden,
45 | required,
46 | itemClass,
47 | controlClass,
48 | }: TextFieldProps) {
49 | const ifRequired = required ? { required: true, "aria-required": true } : {};
50 | return (
51 | (
55 |
58 |
211 | ) : (
212 |
222 |
223 | )}
224 | >
225 | );
226 | }
227 |
--------------------------------------------------------------------------------
/src/components/ui/dropdown-menu.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
3 | import {
4 | CheckIcon,
5 | ChevronRightIcon,
6 | DotFilledIcon,
7 | } from "@radix-ui/react-icons";
8 |
9 | import { cn } from "@/lib/utils";
10 |
11 | const DropdownMenu = DropdownMenuPrimitive.Root;
12 |
13 | const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
14 |
15 | const DropdownMenuGroup = DropdownMenuPrimitive.Group;
16 |
17 | const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
18 |
19 | const DropdownMenuSub = DropdownMenuPrimitive.Sub;
20 |
21 | const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
22 |
23 | const DropdownMenuSubTrigger = React.forwardRef<
24 | React.ElementRef,
25 | React.ComponentPropsWithoutRef & {
26 | inset?: boolean;
27 | }
28 | >(({ className, inset, children, ...props }, ref) => (
29 |
38 | {children}
39 |
40 |
41 | ));
42 | DropdownMenuSubTrigger.displayName =
43 | DropdownMenuPrimitive.SubTrigger.displayName;
44 |
45 | const DropdownMenuSubContent = React.forwardRef<
46 | React.ElementRef,
47 | React.ComponentPropsWithoutRef
48 | >(({ className, ...props }, ref) => (
49 |
57 | ));
58 | DropdownMenuSubContent.displayName =
59 | DropdownMenuPrimitive.SubContent.displayName;
60 |
61 | const DropdownMenuContent = React.forwardRef<
62 | React.ElementRef,
63 | React.ComponentPropsWithoutRef
64 | >(({ className, sideOffset = 4, ...props }, ref) => (
65 |
66 |
76 |
77 | ));
78 | DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
79 |
80 | const DropdownMenuItem = React.forwardRef<
81 | React.ElementRef,
82 | React.ComponentPropsWithoutRef & {
83 | inset?: boolean;
84 | }
85 | >(({ className, inset, ...props }, ref) => (
86 |
95 | ));
96 | DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
97 |
98 | const DropdownMenuCheckboxItem = React.forwardRef<
99 | React.ElementRef,
100 | React.ComponentPropsWithoutRef
101 | >(({ className, children, checked, ...props }, ref) => (
102 |
111 |
112 |
113 |
114 |
115 |
116 | {children}
117 |
118 | ));
119 | DropdownMenuCheckboxItem.displayName =
120 | DropdownMenuPrimitive.CheckboxItem.displayName;
121 |
122 | const DropdownMenuRadioItem = React.forwardRef<
123 | React.ElementRef,
124 | React.ComponentPropsWithoutRef
125 | >(({ className, children, ...props }, ref) => (
126 |
134 |
135 |
136 |
137 |
138 |
139 | {children}
140 |
141 | ));
142 | DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
143 |
144 | const DropdownMenuLabel = React.forwardRef<
145 | React.ElementRef,
146 | React.ComponentPropsWithoutRef & {
147 | inset?: boolean;
148 | }
149 | >(({ className, inset, ...props }, ref) => (
150 |
159 | ));
160 | DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
161 |
162 | const DropdownMenuSeparator = React.forwardRef<
163 | React.ElementRef,
164 | React.ComponentPropsWithoutRef
165 | >(({ className, ...props }, ref) => (
166 |
171 | ));
172 | DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
173 |
174 | const DropdownMenuShortcut = ({
175 | className,
176 | ...props
177 | }: React.HTMLAttributes) => {
178 | return (
179 |
183 | );
184 | };
185 | DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
186 |
187 | export {
188 | DropdownMenu,
189 | DropdownMenuTrigger,
190 | DropdownMenuContent,
191 | DropdownMenuItem,
192 | DropdownMenuCheckboxItem,
193 | DropdownMenuRadioItem,
194 | DropdownMenuLabel,
195 | DropdownMenuSeparator,
196 | DropdownMenuShortcut,
197 | DropdownMenuGroup,
198 | DropdownMenuPortal,
199 | DropdownMenuSub,
200 | DropdownMenuSubContent,
201 | DropdownMenuSubTrigger,
202 | DropdownMenuRadioGroup,
203 | };
204 |
--------------------------------------------------------------------------------
/convex/posts.ts:
--------------------------------------------------------------------------------
1 | import { v } from "convex/values";
2 | import { mutation as rawMutation, query } from "./_generated/server";
3 | import schema from "./schema";
4 | import { Triggers } from "convex-helpers/server/triggers";
5 | import { DataModel, type Doc } from "./_generated/dataModel";
6 | import {
7 | customMutation,
8 | customCtx,
9 | } from "convex-helpers/server/customFunctions";
10 |
11 | // Use Triggers to keep aggregated 'search' field up-to-date
12 | // by automatically updating it whenever a post is created/updated.
13 | // See also: https://stack.convex.dev/triggers#denormalizing-a-field
14 | const triggers = new Triggers();
15 |
16 | triggers.register("posts", async (ctx, change) => {
17 | console.log("Triggered on posts with change: ", change);
18 | if (change.newDoc) {
19 | // A post has been inserted or updated;
20 | // aggregate the relevant searchable text fields
21 | // into a single 'search' string to be indexed
22 | const { title, content, summary, slug } = change.newDoc;
23 | const newSearch = [title, content, summary, slug].join(" ");
24 |
25 | // if the search aggregate has changed, update it
26 | if (change.newDoc.search !== newSearch) {
27 | console.log(
28 | `Triggering search field update for ${slug} (post ${change.id})`,
29 | );
30 | await ctx.db.patch(change.id, { search: newSearch });
31 | }
32 | }
33 | });
34 | // Wrap the default Convex mutation function to be aware of our trigger
35 | const mutation = customMutation(rawMutation, customCtx(triggers.wrapDB));
36 |
37 | export const publish = mutation({
38 | args: {
39 | versionId: v.id("versions"),
40 | },
41 | handler: async (ctx, args) => {
42 | const version = await ctx.db.get(args.versionId);
43 | if (!version) {
44 | throw new Error(`Version ${args.versionId} not found`);
45 | }
46 | const {
47 | _id,
48 | _creationTime,
49 | editorId: _editorId,
50 | postId,
51 | ...content
52 | } = version;
53 | const oldPost = await ctx.db.get(postId);
54 |
55 | if (!oldPost) {
56 | throw new Error(`Post ${version.postId} not found`);
57 | }
58 | const patch = {
59 | ...content,
60 | published: true,
61 | publishTime: oldPost.publishTime || Date.now(),
62 | updateTime: Date.now(),
63 | };
64 | await ctx.db.patch(postId, patch);
65 | return ctx.db.get(postId);
66 | },
67 | });
68 |
69 | export const list = query({
70 | args: {},
71 | handler: async (ctx) => {
72 | // If the user is authenticated, include unpublished drafts
73 | // by omitting the index filter. Otherwise, use the index
74 | // filter to only return published posts
75 | const authed = await ctx.auth.getUserIdentity();
76 |
77 | const posts = await ctx.db
78 | .query("posts")
79 | .withIndex(
80 | "by_published",
81 | authed ? undefined : (q) => q.eq("published", true),
82 | )
83 | .order("desc")
84 | .collect();
85 |
86 | return Promise.all(
87 | posts.map(async (post) => {
88 | // Add the author's details to each post.
89 | const author = (await ctx.db.get(post.authorId))!;
90 | return { ...post, author };
91 | }),
92 | );
93 | },
94 | });
95 |
96 | export const getById = query({
97 | args: {
98 | id: v.id("posts"),
99 | withAuthor: v.optional(v.boolean()),
100 | },
101 | handler: async (ctx, args) => {
102 | const { id, withAuthor } = args;
103 | const post = await ctx.db.get(id);
104 | if (!post) return null;
105 | let author;
106 | if (withAuthor) {
107 | // Add the author's details to each post.
108 | author = (await ctx.db.get(post.authorId))!;
109 | }
110 | return { ...post, author };
111 | },
112 | });
113 |
114 | type PostAugmented = Doc<"posts"> & {
115 | publicVersion?: Doc<"versions">;
116 | draft?: Doc<"versions">;
117 | author?: Doc<"users">;
118 | };
119 | export const getBySlug = query({
120 | args: {
121 | slug: v.string(),
122 | withDraft: v.optional(v.boolean()),
123 | withAuthor: v.optional(v.boolean()),
124 | },
125 | handler: async (ctx, args) => {
126 | const versionsBySlug = ctx.db
127 | .query("versions")
128 | .withIndex("by_slug", (q) => q.eq("slug", args.slug));
129 |
130 | const publicVersion = await versionsBySlug
131 | .filter((q) => q.eq(q.field("published"), true))
132 | .order("desc")
133 | .first();
134 |
135 | let post = await ctx.db
136 | .query("posts")
137 | .withIndex("by_slug", (q) => q.eq("slug", args.slug))
138 | .order("desc")
139 | .first();
140 |
141 | if (!post) {
142 | // The slug for this post may have changed
143 | // try searching for this slug in old versions
144 | if (publicVersion) {
145 | // The slug is outdated, lookup the postId
146 | post = await ctx.db.get(publicVersion.postId);
147 | }
148 | }
149 | if (!post) return null; // The slug is unknown
150 |
151 | const authed = await ctx.auth.getUserIdentity();
152 | if (!authed && !post.published) {
153 | // This is an unpublished draft, unauthenticated
154 | // user does not have permission to view it
155 | return null;
156 | }
157 |
158 | const result: PostAugmented = post;
159 | if (publicVersion) {
160 | result.publicVersion = publicVersion;
161 | }
162 |
163 | if (args.withDraft) {
164 | // Find the most recent unpublished draft, if any,
165 | // created after this post was last updated
166 | const draft = await ctx.db
167 | .query("versions")
168 | .withIndex("by_postId", (q) => q.eq("postId", post._id))
169 | .filter((q) =>
170 | q.and(
171 | q.gt(
172 | q.field("_creationTime"),
173 | post.updateTime || post._creationTime,
174 | ),
175 | q.eq(q.field("published"), false),
176 | ),
177 | )
178 | .order("desc")
179 | .first();
180 | if (draft) {
181 | result.draft = draft;
182 | }
183 | }
184 |
185 | if (args.withAuthor) {
186 | const author = await ctx.db.get(post.authorId);
187 | if (author) {
188 | result.author = author;
189 | }
190 | }
191 |
192 | return result;
193 | },
194 | });
195 |
196 | export const isSlugTaken = query({
197 | args: {
198 | slug: v.string(),
199 | postId: schema.tables.posts.validator.fields.postId,
200 | },
201 | handler: async (ctx, args) => {
202 | const { slug, postId } = args;
203 |
204 | // Find any existing post(s) with this slug and flag
205 | // any whose postId doesn't match the one given
206 | const posts = await ctx.db
207 | .query("posts")
208 | .withIndex("by_slug", (q) => q.eq("slug", slug))
209 | .collect();
210 | const badPostIds = new Set(
211 | posts.filter((p) => p._id !== postId).map((p) => p._id),
212 | );
213 |
214 | // It's possible that the slug is no longer in use on any posts,
215 | // but had previously been used in an old version of another post.
216 | // Collect all version(s) with this slug...
217 | const versions = await ctx.db
218 | .query("versions")
219 | .withIndex("by_slug", (q) => q.eq("slug", slug))
220 | .collect();
221 | // ...and flag any whose postId doesn't match the one given.
222 | const badVersions = versions.filter((v) => v.postId !== postId);
223 | badVersions.map((v) => badPostIds.add(v.postId));
224 |
225 | if (badPostIds.size > 0) {
226 | // This slug is unavailable (already/previously in use)
227 | const msg = `Slug "${slug}" is unavailable, used on post(s) ${Array.from(badPostIds).toString()}`;
228 | console.error(msg);
229 | return msg;
230 | } else {
231 | return false;
232 | }
233 | },
234 | });
235 |
236 | export const search = query({
237 | args: { searchTerm: v.string() },
238 | handler: async (ctx, args) => {
239 | const authed = await ctx.auth.getUserIdentity();
240 |
241 | const results = await ctx.db
242 | .query("posts")
243 | .withSearchIndex("search_all", (q) => {
244 | const search = q.search("search", args.searchTerm);
245 |
246 | // Search public + draft posts if user is authed;
247 | // otherwise, add filter to only search public posts
248 | return authed ? search : search.eq("published", true);
249 | })
250 | .collect();
251 |
252 | return Promise.all(
253 | results.map(async (post) => {
254 | // Add the author's details to each post.
255 | const author = (await ctx.db.get(post.authorId))!;
256 | return { ...post, author };
257 | }),
258 | );
259 | },
260 | });
261 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2024 Convex, Inc.
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/convex/data.ts:
--------------------------------------------------------------------------------
1 | import { internalMutation } from "./_generated/server";
2 | import type { Id, TableNames } from "./_generated/dataModel";
3 | import { byEmail, getOrSetSlug } from "./users";
4 |
5 | const USERS = ["ian@convex.dev", "wayne@convex.dev", "contact@anjana.dev"];
6 | const POSTS = [
7 | {
8 | authorIndex: 1,
9 | content: `A few months into their startup journey, Emily and Jason had successfully launched their platform, thanks to the robust backend support from Convex.dev. Their users loved the smooth, intuitive experience, and the team was ready to take the next big step: adding content management capabilities.
10 |
11 | When Convex announced their new CMS feature, Emily and Jason were thrilled. The CMS was exactly what they needed to empower their users to manage their content seamlessly within the platform. The developers spent the day exploring the new feature, diving into its functionalities, and brainstorming how they could integrate it to enhance their platform’s offerings.
12 |
13 | The creative startup office buzzed with excitement as they mapped out new possibilities. Jason pointed out key features on the laptop screen while Emily jotted down implementation ideas. The large screen in the office displayed the CMS dashboard, hinting at the powerful new tools they were eager to incorporate. This new addition to Convex’s offerings not only fueled their excitement but also opened up a world of possibilities for their startup’s growth.`,
14 | imageUrl:
15 | "https://pleasant-albatross-666.convex.cloud/api/storage/82027b58-1979-435c-a41a-e55205b0a0c5",
16 | published: true,
17 | slug: "convexcms",
18 | summary:
19 | "This new addition to Convex’s offerings not only fueled their excitement but also opened up a world of possibilities for their startup’s growth.",
20 | title: "Exploring Convex’s New CMS",
21 | },
22 | {
23 | authorIndex: 0,
24 | title: "Introducing Convex Auth",
25 | slug: "introducing-convex-auth",
26 | summary:
27 | "Convex Auth is a library for implementing authentication natively in your Convex backend.",
28 | published: true,
29 | content: ` "Convex Auth is a library for implementing authentication using your Convex backend.
30 |
31 | Check it out [in the Convex docs
32 | ](https: //docs.convex.dev/auth/convex-auth) to get started or play with the [example demo](https://labs.convex.dev/auth-example) ([source](https://github.com/get-convex/convex-auth-example)).
33 |
34 | *This article is based on the [launch video
35 | ](https: //convex.dev/auth).*
36 |
37 | # Motivation
38 |
39 | Convex is designed for building multi-user applications. And if your app has users, it needs authentication. But authentication is a really complex component of a full-stack app. For this reason we have been recommending the built-in integrations with mature authentication platforms like [Clerk
40 | ](https: //clerk.dev/) and [Auth0](https://auth0.com/).
41 |
42 | Yet many developers have been asking for a self-hosted solution. The auth platforms I mentioned have a ton of features but they also store the authentication data. This complicates your app, as that data has to be somehow synced or shared with your backend and database.
43 |
44 | 
46 |
47 | This is a surmountable challenge, but maybe you’re just getting started and your app doesn’t need every authentication feature. You’d rather have more control over the data and a simpler architecture to build on top of.
48 |
49 | 
51 |
52 | # Functionality
53 |
54 | Convex Auth enables you to build such a solution. It is inspired by the excellent [Auth.js
55 | ](https: //authjs.dev/) and [Lucia](https://lucia-auth.com/) libraries, and reuses some of their implementation. It is also similar in its capabilities to auth solutions such as Firebase Auth and Supabase Auth (although it doesn’t have all of their features yet).
56 |
57 | In the [demo
58 | ](https: //labs.convex.dev/auth-example) you can see the various sign-in methods you can implement with Convex Auth. It supports sign-in via OAuth, magic links, one-time-passwords and normal email and password combination. You can use any of the 80 OAuth providers supported by Auth.js.
59 |
60 | # Code deep dive
61 |
62 | ## Server configuration
63 |
64 | The main configuration file is \`auth.ts\` in your convex directory, which configures the available authentication methods:
65 |
66 | \`\`\`jsx
67 | import GitHub from '@auth/core/providers/github';
68 | import Google from '@auth/core/providers/google';
69 | import Resend from '@auth/core/providers/resend';
70 | import { Password
71 | } from '@convex-dev/auth/providers/Password';
72 |
73 | export const { auth, signIn, signOut, store
74 | } = convexAuth({
75 | providers: [GitHub, Google, Resend, Password
76 | ],
77 | });
78 | \`\`\`
79 |
80 | Your \`schema.ts\` must also include the tables used by the library, including the \`users\` table. This is because the library uses indexes on these tables for efficient lookups:
81 |
82 | \`\`\`jsx
83 | import { authTables
84 | } from '@convex-dev/auth/server';
85 | import { defineSchema, defineTable
86 | } from 'convex/server';
87 | import { v
88 | } from 'convex/values';
89 |
90 | export default defineSchema({
91 | ...authTables,
92 | // Your other tables...
93 | });
94 | \`\`\`
95 |
96 | There is additional configuration in \`auth.config.ts\` and \`https.ts\`, but you won’t need to touch these. See [Manual Setup
97 | ](https: //labs.convex.dev/auth/setup/manual) for more details if you’re interested.
98 |
99 | ## Frontend configuration
100 |
101 | On the frontend, instead of using \`ConvexProvider\`, the app is wrapped in \`ConvexAuthProvider\`. Then in the \`App\` root component, the \`Authenticated\` and \`Unauthenticated\` components (from \`convex/react\`) are used to render different UI based on the authentication state. When not authenticated, your app can render the sign-in form:
102 |
103 | \`\`\`jsx
104 | import { Content
105 | } from '@/Content';
106 | import { SignInForm
107 | } from '@/auth/SignInForm';
108 | import { Authenticated, Unauthenticated
109 | } from 'convex/react';
110 |
111 | export default function App() {
112 | return (
113 | <>
114 |
115 |
116 |
117 |
118 |
119 |
120 | >
121 | );
122 | }
123 |
124 | \`\`\`
125 |
126 | The key part of the sign-in UI is calling the \`signIn\` function with the name of one of the authentication methods configured in \`auth.ts\`. For example here’s a form that sends the user a magic link:
127 |
128 | \`\`\`jsx
129 |
130 | import { useAuthActions
131 | } from '@convex-dev/auth/react';
132 |
133 | export function SignInWithMagicLink() {
134 | const { signIn
135 | } = useAuthActions();
136 | return (
137 |
150 | );
151 | }
152 | \`\`\`
153 |
154 | ## Handling authentication
155 |
156 | Finally, let’s look at how the authentication state is used to power the signed-in experience. The \`auth.ts\` file exports an \`auth\` helper, which has methods for retrieving the current user and session ID. Using these methods, we can return the information about the current user back to the client:
157 |
158 | \`\`\`jsx
159 | import { query
160 | } from './_generated/server';
161 | import { auth
162 | } from './auth';
163 |
164 | export const viewer = query({
165 | args: {},
166 | handler: async (ctx) => {
167 | const userId = await auth.getUserId(ctx);
168 | return userId !== null ? ctx.db.get(userId) : null;
169 | },
170 | });
171 | \`\`\`
172 |
173 | As well as enforce that certain functions can only be called by signed-in users:
174 |
175 | \`\`\`jsx
176 | import { query, mutation
177 | } from './_generated/server';
178 | import { v
179 | } from 'convex/values';
180 | import { auth
181 | } from './auth';
182 |
183 | export const send = mutation({
184 | args: { body: v.string()
185 | },
186 | handler: async (ctx,
187 | { body
188 | }) => {
189 | const userId = await auth.getUserId(ctx);
190 | if (userId === null) {
191 | throw new Error('Not signed in');
192 | }
193 | // Send a new message.
194 | await ctx.db.insert('messages',
195 | { body, userId
196 | });
197 | },
198 | });
199 | \`\`\`
200 |
201 | ## Conclusion
202 |
203 | And that’s all it takes to get self-hosted auth to work. From here I recommend you read through the [docs
204 | ](https: //labs.convex.dev/auth). They go into detail on how to implement the various authentication methods and on the trade-offs between them. I hope you’ll find the library useful. Please let us know what you think on our [discord](https://arc.net/l/quote/dxljwnkc)."
205 | `,
206 | },
207 | {
208 | authorIndex: 1,
209 | content: `A team of full-stack developers, comprised of Alex, Priya, and Mateo, were always on the lookout for new tools and technologies that could push the boundaries of their projects. When they heard about the Convex “Zero to One” hackathon, they decided to join, eager to explore what this new backend platform could offer.
210 |
211 | The hackathon challenge was simple yet ambitious: build something unique using Convex.dev in just 48 hours. The team brainstormed and decided to create a blog platform that could effortlessly handle dynamic content and user interactions. They were drawn to Convex’s promise of fast, scalable, and serverless backend solutions, which seemed perfect for their idea.
212 |
213 | As they delved into the development, they were impressed by how quickly they could set up their backend using Convex. The platform’s real-time features and seamless integration with their frontend frameworks allowed them to focus on creating a rich, interactive user experience without worrying about managing servers or databases. The project came together faster than they expected, with Convex handling the heavy lifting behind the scenes.
214 |
215 | By the end of the hackathon, their blog platform was not only functional but also robust and scalable. The experience had been so smooth and empowering that they decided to take their idea further. The team transformed their hackathon project into a full-fledged startup, using Convex as the backbone of their platform. They envisioned expanding the blog into a community-driven space where users could create, share, and interact with content effortlessly.
216 |
217 | With Convex.dev, they were confident they could scale their startup quickly and efficiently. What started as a hackathon experiment had now evolved into a startup venture, fueled by the possibilities that Convex unlocked for them. The journey from zero to one was just the beginning, and they were excited to see where Convex would take them next.`,
218 | imageUrl:
219 | "https://pleasant-albatross-666.convex.cloud/api/storage/6a651783-cb93-4878-a7c9-784091e560c4",
220 | published: true,
221 | slug: "hackathon-startup",
222 | summary:
223 | "With Convex.dev, they were confident they could scale their startup quickly and efficiently. ",
224 | title: "From Hackathon to Startup with Convex",
225 | },
226 | {
227 | authorIndex: 2,
228 | content: `Two full-stack developers, Emily and Jason, were deep into building their startup, an innovative platform aimed at simplifying online event management. They had been struggling with the backend infrastructure, trying to find a solution that would allow them to focus more on the frontend and less on managing complex databases and APIs.
229 |
230 | One day, Emily stumbled upon Convex.dev while researching backend solutions. Excited, she immediately shared it with Jason. They were both impressed by how Convex.dev promised to simplify their workflow by providing a fully managed backend platform that integrated seamlessly with their preferred frontend frameworks. The speed and ease of use were exactly what they needed to accelerate their development process. They could now build, test, and deploy features faster, giving them more time to focus on their startup’s unique value proposition.
231 |
232 | In their sleek, modern office, Emily and Jason dove into Convex.dev, quickly realizing how it could transform their project. The whiteboard behind them was soon filled with new ideas and plans, as they excitedly mapped out the next steps for their startup, now confident that they had the right tools to bring their vision to life.`,
233 | imageUrl:
234 | "https://pleasant-albatross-666.convex.cloud/api/storage/19ead46b-c4d6-47df-bd3f-ff007761c6c0",
235 | published: true,
236 | slug: "discovering-convex",
237 | summary:
238 | "Two full-stack developers, Emily and Jason, were deep into building their startup, an innovative platform aimed at simplifying online event management. ",
239 | title: "Discovering Convex.dev",
240 | },
241 | ];
242 |
243 | export const clearPosts = internalMutation({
244 | args: {},
245 | handler: async (ctx) => {
246 | await Promise.all(
247 | ["posts", "versions"].map(async (table) => {
248 | const oldData = await ctx.db.query(table as TableNames).collect();
249 | await Promise.all(
250 | oldData.map(async ({ _id }) => {
251 | await ctx.db.delete(_id);
252 | }),
253 | );
254 | console.log(
255 | `Deleted ${oldData.length} documents from "${table}" table`,
256 | );
257 | }),
258 | );
259 | },
260 | });
261 |
262 | export const reset = internalMutation({
263 | args: {},
264 | handler: async (ctx) => {
265 | await clearPosts(ctx, {});
266 | const userIds: Id<"users">[] = await Promise.all(
267 | USERS.map(async (email) => {
268 | const user = await byEmail(ctx, { email });
269 | if (!user) throw new Error("user not found " + email);
270 | console.log(`Found ${user._id} in "users" table`);
271 | const slug = await getOrSetSlug(ctx, { id: user._id });
272 | console.log(`Author slug: ${slug}`);
273 | return user._id;
274 | }),
275 | );
276 | await Promise.all(
277 | POSTS.map(async (p) => {
278 | const { authorIndex, ...post } = p;
279 | const authorId = userIds[authorIndex];
280 | const { title, content, summary, slug } = post;
281 | const search = [title, content, summary, slug].join(" ");
282 |
283 | const postId = await ctx.db.insert("posts", {
284 | ...post,
285 | authorId,
286 | publishTime: Date.now(),
287 | search,
288 | });
289 | console.log(`Created document ${postId} in "posts" table`);
290 | const versionId = await ctx.db.insert("versions", {
291 | ...post,
292 | postId,
293 | authorId,
294 | editorId: authorId,
295 | });
296 | console.log(`Created document ${versionId} in "versions" table`);
297 | }),
298 | );
299 | },
300 | });
301 |
--------------------------------------------------------------------------------