Repository navigation
feat(api): add community template API #61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| import { Request, Response, RequestHandler } from "express"; | ||
| import { asyncHandler } from "../utils/async-handler.js"; | ||
| import prisma from "../lib/db.js"; | ||
|
|
||
| // POST /api/v1/templates | ||
| export const createTemplate: RequestHandler = asyncHandler( | ||
| async (req: Request, res: Response) => { | ||
| const userId = res.locals.user.id as string; | ||
| const { | ||
| title, | ||
| description, | ||
| category, | ||
| iconSymbol, | ||
| images, | ||
| formId, | ||
| fields, | ||
| status, | ||
| } = req.body; | ||
|
|
||
| let resolvedFields = fields ?? []; | ||
| let finalFormId = null; | ||
|
|
||
| if (!fields && formId) { | ||
| const sourceForm = await prisma.form.findFirst({ | ||
| where: { id: formId, userId }, | ||
| select: { fields: true }, | ||
| }); | ||
|
|
||
| if (!sourceForm) { | ||
| res.status(404).json({ | ||
| success: false, | ||
| message: "Source form not found or does not belong to you", | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| resolvedFields = sourceForm.fields; | ||
| finalFormId = formId; | ||
| } | ||
|
|
||
| const template = await prisma.template.create({ | ||
| data: { | ||
| title, | ||
| description, | ||
| category, | ||
| iconSymbol, | ||
| images: images ?? [], | ||
| fields: resolvedFields, | ||
| formId: finalFormId, | ||
| status: status ?? "PUBLISHED", | ||
| createdById: userId, | ||
| }, | ||
| }); | ||
|
|
||
| res.status(201).json({ success: true, data: template }); | ||
| } | ||
| ); | ||
|
|
||
| // GET /api/v1/template | ||
|
|
||
| export const listTemplates: RequestHandler = asyncHandler( | ||
| async (req: Request, res: Response) => { | ||
| const { category } = req.query; | ||
| const take = Math.min(Number(req.query.limit) || 20, 50); | ||
| const skip = Math.max(Number(req.query.offset) || 0, 0); | ||
|
|
||
| const where: Record<string, unknown> = { status: "PUBLISHED" }; | ||
| if (typeof category === "string" && category.length > 0) { | ||
| where.category = category; | ||
| } | ||
|
|
||
| const templates = await prisma.template.findMany({ | ||
| where, | ||
| take, | ||
| skip, | ||
| orderBy: [ | ||
| { featured: "desc" }, | ||
| { useCount: "desc" }, | ||
| { createdAt: "desc" }, | ||
| ], | ||
| select: { | ||
| id: true, | ||
| title: true, | ||
| description: true, | ||
| category: true, | ||
| iconSymbol: true, | ||
| images: true, | ||
| featured: true, | ||
| useCount: true, | ||
| createdAt: true, | ||
| createdBy: { | ||
| select: { | ||
| id: true, | ||
| name: true, | ||
| image: true, | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| res.json({ success: true, data: templates }); | ||
| } | ||
| ); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import { z } from "zod"; | ||
| import { FormDefinitionSchema } from "@repo/types"; | ||
|
|
||
| export const CreateTemplateSchema = z.object({ | ||
| title: z.string().min(1, "Title is required").max(200), | ||
| description: z.string().max(2000).optional(), | ||
| category: z.string().max(100).optional(), | ||
| iconSymbol: z.string().max(10).optional(), | ||
| images: z | ||
| .array(z.string().url("Each image must be a valid URL")) | ||
| .max(5, "Maximum 5 images allowed") | ||
| .default([]), | ||
|
|
||
| // Either supply a formId to snapshot from, or provide fields directly | ||
| formId: z.string().optional(), | ||
| fields: FormDefinitionSchema.optional(), | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| // Publish immediately or save as draft | ||
| status: z.enum(["DRAFT", "PUBLISHED"]).default("PUBLISHED"), | ||
| }).refine((d) => Boolean(d.formId) !== Boolean(d.fields), { | ||
| message: "Provide exactly one of `formId` or `fields`", | ||
| path: ["fields"], | ||
| }); | ||
|
|
||
| export type CreateTemplateInput = z.infer<typeof CreateTemplateSchema>; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import { Router } from "express"; | ||
| import { requireAuth } from "../../middleware/require-auth"; | ||
| import { validate } from "../../middleware/validate"; | ||
| import { CreateTemplateSchema } from "../../lib/template-schemas"; | ||
| import { | ||
| createTemplate, | ||
| listTemplates, | ||
| } from "../../controllers/template.controller"; | ||
|
|
||
| const templateRouter: Router = Router(); | ||
|
|
||
| templateRouter.get("/", listTemplates); | ||
| templateRouter.post("/", requireAuth, validate(CreateTemplateSchema), createTemplate); | ||
|
|
||
| export default templateRouter; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,27 +1,45 @@ | ||
| // ============================================ | ||
| // TEMPLATES | ||
| // ============================================ | ||
| // ============================================ | ||
| // TEMPLATES | ||
| // ============================================ | ||
|
|
||
| enum TemplateStatus { | ||
| DRAFT | ||
| PUBLISHED | ||
| ARCHIVED | ||
| } | ||
|
|
||
| model Template { | ||
| id String @id @default(cuid()) | ||
| id String @id @default(cuid()) | ||
| title String | ||
| description String? @db.Text | ||
| description String? @db.Text | ||
| category String? | ||
|
|
||
| // Template structure (same format as Form.fields) | ||
| fields Json @default("[]") | ||
|
|
||
| fields Json @default("[]") | ||
| // Preview | ||
| iconSymbol String? @default("📋") | ||
|
|
||
| iconSymbol String? @default("📋") | ||
| images String[] @default([]) | ||
|
|
||
| // Status | ||
| status TemplateStatus @default(DRAFT) | ||
|
|
||
| // Source form (optional back-reference) | ||
| formId String? | ||
|
|
||
| // Owner | ||
| createdById String? | ||
| createdBy User? @relation(fields: [createdById], references: [id], onDelete: SetNull) | ||
|
|
||
| // Metadata | ||
| featured Boolean @default(false) | ||
| useCount Int @default(0) | ||
|
|
||
| createdAt DateTime @default(now()) | ||
| updatedAt DateTime @updatedAt | ||
| featured Boolean @default(false) | ||
| useCount Int @default(0) | ||
| createdAt DateTime @default(now()) | ||
| updatedAt DateTime @updatedAt | ||
|
|
||
| @@index([featured]) | ||
| @@index([category]) | ||
| @@index([createdById]) | ||
| @@index([status]) | ||
| @@map("templates") | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.