Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions apps/webservice/src/app/api/v1/release-channels/openapi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import type { Swagger } from "atlassian-openapi";

export const openapi: Swagger.SwaggerV3 = {
openapi: "3.0.0",
info: {
title: "Ctrlplane API",
version: "1.0.0",
},
paths: {
"/v1/release-channels": {
post: {
summary: "Create a release channel",
operationId: "createReleaseChannel",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["deploymentId", "name"],
properties: {
deploymentId: { type: "string" },
name: { type: "string" },
description: { type: "string", nullable: true },
},
},
},
},
},
responses: {
"200": {
description: "Release channel created successfully",
content: {
"application/json": {
schema: {
type: "object",
properties: {
id: { type: "string" },
deploymentId: { type: "string" },
name: { type: "string" },
description: { type: "string", nullable: true },
createdAt: { type: "string", format: "date-time" },
},
required: ["id", "deploymentId", "name", "createdAt"],
},
},
},
},
"500": {
description: "Failed to create release channel",
content: {
"application/json": {
schema: {
type: "object",
properties: { error: { type: "string" } },
required: ["error"],
},
},
},
},
"401": {
description: "Unauthorized",
content: {
"application/json": {
schema: {
type: "object",
properties: { error: { type: "string" } },
required: ["error"],
},
},
},
},
"403": {
description: "Forbidden",
content: {
"application/json": {
schema: {
type: "object",
properties: { error: { type: "string" } },
required: ["error"],
},
},
},
},
Comment on lines +49 to +84
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor duplicated error response schemas into reusable components

To improve maintainability and reduce duplication, consider defining a reusable ErrorResponse schema in the components section and referencing it in the error responses for status codes 500, 401, and 403.

Apply the following changes:

Add the ErrorResponse schema to components.schemas (after line 91):

+      schemas: {
+        ErrorResponse: {
+          type: "object",
+          properties: { error: { type: "string" } },
+          required: ["error"],
+        },
+      },

Update the error responses to reference the ErrorResponse schema.

For the 500 response (lines 53-57):

For the 401 response (lines 65-69):

For the 403 response (lines 77-81):

This change centralizes the error response schema and enhances maintainability.

Committable suggestion skipped: line range outside the PR's diff.

},
security: [{ bearerAuth: [] }],
},
},
},
components: {
securitySchemes: { bearerAuth: { type: "http", scheme: "bearer" } },
},
};
32 changes: 32 additions & 0 deletions apps/webservice/src/app/api/v1/release-channels/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { z } from "zod";
import { NextResponse } from "next/server";

import { takeFirst } from "@ctrlplane/db";
import { createReleaseChannel } from "@ctrlplane/db/schema";
import * as SCHEMA from "@ctrlplane/db/schema";
import { Permission } from "@ctrlplane/validators/auth";

import { authn, authz } from "../auth";
import { parseBody } from "../body-parser";
import { request } from "../middleware";

export const POST = request()
.use(authn)
.use(parseBody(createReleaseChannel))
.use(
authz(({ ctx, can }) =>
can
.perform(Permission.ReleaseChannelCreate)
.on({ type: "deployment", id: ctx.body.deploymentId }),
),
)
.handle<{ body: z.infer<typeof createReleaseChannel> }>(
async ({ db, body }) =>
db
.insert(SCHEMA.releaseChannel)
.values(body)
.returning()
.then(takeFirst)
.then((releaseChannel) => NextResponse.json(releaseChannel))
.catch((error) => NextResponse.json({ error }, { status: 500 })),
);
Comment on lines +23 to +32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance error handling and add transaction support.

The current implementation has several areas for improvement:

  1. Error handling should be more specific to provide better client feedback
  2. Raw error objects in responses could expose sensitive information
  3. Missing transaction support for data consistency

Consider applying this improvement:

   .handle<{ body: z.infer<typeof createReleaseChannel> }>(
-    async ({ db, body }) =>
+    async ({ db, body }) => {
+      try {
+        const releaseChannel = await db.transaction(async (trx) => {
+          const [result] = await trx
+            .insert(SCHEMA.releaseChannel)
+            .values(body)
+            .returning();
+          return result;
+        });
+        return NextResponse.json(releaseChannel);
+      } catch (error) {
+        if (error.code === '23505') { // PostgreSQL unique violation
+          return NextResponse.json(
+            { message: 'Release channel already exists' },
+            { status: 409 }
+          );
+        }
+        console.error('Failed to create release channel:', error);
+        return NextResponse.json(
+          { message: 'Internal server error' },
+          { status: 500 }
+        );
+      }
+    }
-      db
-        .insert(SCHEMA.releaseChannel)
-        .values(body)
-        .returning()
-        .then(takeFirst)
-        .then((releaseChannel) => NextResponse.json(releaseChannel))
-        .catch((error) => NextResponse.json({ error }, { status: 500 })),
   );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.handle<{ body: z.infer<typeof createReleaseChannel> }>(
async ({ db, body }) =>
db
.insert(SCHEMA.releaseChannel)
.values(body)
.returning()
.then(takeFirst)
.then((releaseChannel) => NextResponse.json(releaseChannel))
.catch((error) => NextResponse.json({ error }, { status: 500 })),
);
.handle<{ body: z.infer<typeof createReleaseChannel> }>(
async ({ db, body }) => {
try {
const releaseChannel = await db.transaction(async (trx) => {
const [result] = await trx
.insert(SCHEMA.releaseChannel)
.values(body)
.returning();
return result;
});
return NextResponse.json(releaseChannel);
} catch (error) {
if (error.code === '23505') { // PostgreSQL unique violation
return NextResponse.json(
{ message: 'Release channel already exists' },
{ status: 409 }
);
}
console.error('Failed to create release channel:', error);
return NextResponse.json(
{ message: 'Internal server error' },
{ status: 500 }
);
}
}
);

Loading