| 1 | import { createRoute, z } from '@hono/zod-openapi' |
| 2 | import { and, eq |
| 3 | import type { app |
| 4 | import { requireApiKey, throwHttp |
| 5 | import { ProjectEntity } |
| 6 | import { errorResponse } |
| 7 | import { db } |
| 8 | import { projectStatus, projects |
| 9 | |
| 10 | const bodySchema = z |
| 11 | name: z.string |
| 12 | slug: z |
| 13 | .string() |
| 14 | .min(1) |
| 15 | .max(255) |
| 16 | .regex(/^[a-z0-9 |
| 17 | description: z.string |
| 18 | status: z.enum |
| 19 | dueDate: z.coerce |
| 20 | }) |
| 21 | |
| 22 | const route = createRoute |
| 23 | method: 'post', |
| 24 | path: '/projects', |
| 25 | tags: ['Projects'], |
| 26 | summary: 'Create a project', |
| 27 | description: 'Create a new project within the organization', |
| 28 | request: { |
| 29 | body: { |
| 30 | content: { |
| 31 | 'application/json': { |
| 32 | schema: bodySchema, |
| 33 | }, |
| 34 | }, |
| 35 | }, |
| 36 | }, |
| 37 | responses: { |
| 38 | 201: { |
| 39 | description: 'Created project', |
| 40 | content: { |
| 41 | 'application/json': { |
| 42 | schema: ProjectEntity, |
| 43 | }, |
| 44 | }, |
| 45 | }, |
| 46 | 400: { ...errorResponse |
| 47 | 401: { ...errorResponse |
| 48 | 402: { |
| 49 | ...errorResponse, |
| 50 | description: 'Organization is not on the Pro plan', |
| 51 | }, |
| 52 | 403: { ...errorResponse |
| 53 | 409: { ...errorResponse |
| 54 | 429: { ...errorResponse |
| 55 | 500: { ...errorResponse |
| 56 | }, |
| 57 | }) |
| 58 | |
| 59 | export const handler = |
| 60 | hono.openapi(route |
| 61 | const key = |
| 62 | const body = |
| 63 | |
| 64 | const [existing] |
| 65 | .select({ id: |
| 66 | .from(projects) |
| 67 | .where( |
| 68 | and( |
| 69 | eq(projects.slug |
| 70 | eq(projects.organizationId |
| 71 | ) |
| 72 | ) |
| 73 | if (existing) { |
| 74 | throwHttp(409, 'Slug is already taken |
| 75 | } |
| 76 | |
| 77 | const [project] |
| 78 | .insert(projects) |
| 79 | .values({ |
| 80 | name: body.name |
| 81 | slug: body.slug |
| 82 | description: body.description |
| 83 | status: body.status |
| 84 | dueDate: body.dueDate |
| 85 | organizationId: key.organizationId |
| 86 | }) |
| 87 | .returning() |
| 88 | if (!project) |
| 89 | throwHttp(500, 'Failed to create project |
| 90 | } |
| 91 | return c.json |
| 92 | }) |
| 93 | } |