Skip to content
Merged
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
62 changes: 28 additions & 34 deletions apps/webservice/src/app/api/v1/release-channels/route.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,49 @@
import type { z } from "zod";
import { NextResponse } from "next/server";

import { and, eq, takeFirst, takeFirstOrNull } from "@ctrlplane/db";
import { buildConflictUpdateColumns, takeFirst } from "@ctrlplane/db";
import { createDeploymentVersionChannel } from "@ctrlplane/db/schema";
import * as SCHEMA from "@ctrlplane/db/schema";
import { Permission } from "@ctrlplane/validators/auth";
import { deploymentVersionCondition } from "@ctrlplane/validators/releases";

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

const schema = createDeploymentVersionChannel.extend({
releaseFilter: deploymentVersionCondition.optional(),
});

export const POST = request()
.use(authn)
.use(parseBody(createDeploymentVersionChannel))
.use(parseBody(schema))
.use(
authz(({ ctx, can }) =>
can
.perform(Permission.DeploymentVersionChannelCreate)
.on({ type: "deployment", id: ctx.body.deploymentId }),
),
)
.handle<{ body: z.infer<typeof createDeploymentVersionChannel> }>(
async ({ db, body }) => {
const deploymentVersionChannel = await db
.select()
.from(SCHEMA.deploymentVersionChannel)
.where(
and(
eq(SCHEMA.deploymentVersionChannel.deploymentId, body.deploymentId),
eq(SCHEMA.deploymentVersionChannel.name, body.name),
),
)
.then(takeFirstOrNull);

if (deploymentVersionChannel)
return NextResponse.json(
{
error: "Release channel already exists",
id: deploymentVersionChannel.id,
},
{ status: 409 },
);
.handle<{ body: z.infer<typeof schema> }>(({ db, body }) => {
const versionSelector = body.versionSelector ?? body.releaseFilter;

return db
.insert(SCHEMA.deploymentVersionChannel)
.values(body)
.returning()
.then(takeFirst)
.then((deploymentVersionChannel) =>
NextResponse.json(deploymentVersionChannel),
)
.catch((error) => NextResponse.json({ error }, { status: 500 }));
},
);
return db
.insert(SCHEMA.deploymentVersionChannel)
.values({ ...body, versionSelector })
.onConflictDoUpdate({
target: [
SCHEMA.deploymentVersionChannel.deploymentId,
SCHEMA.deploymentVersionChannel.name,
],
set: buildConflictUpdateColumns(SCHEMA.deploymentVersionChannel, [
"versionSelector",
]),
})
.returning()
.then(takeFirst)
.then((deploymentVersionChannel) =>
NextResponse.json(deploymentVersionChannel),
)
.catch((error) => NextResponse.json({ error }, { status: 500 }));
});
Loading