|
| 1 | +import { ActionFunctionArgs, json } from "@remix-run/server-runtime"; |
| 2 | +import { z } from "zod"; |
| 3 | +import { prisma } from "~/db.server"; |
| 4 | +import { createEnvironment } from "~/models/organization.server"; |
| 5 | +import { authenticateApiRequestWithPersonalAccessToken } from "~/services/personalAccessToken.server"; |
| 6 | +import { marqs } from "~/v3/marqs/index.server"; |
| 7 | + |
| 8 | +const ParamsSchema = z.object({ |
| 9 | + organizationId: z.string(), |
| 10 | +}); |
| 11 | + |
| 12 | +/** |
| 13 | + * It will create a staging environment for all the projects where there isn't one already |
| 14 | + */ |
| 15 | +export async function action({ request, params }: ActionFunctionArgs) { |
| 16 | + // Next authenticate the request |
| 17 | + const authenticationResult = await authenticateApiRequestWithPersonalAccessToken(request); |
| 18 | + |
| 19 | + if (!authenticationResult) { |
| 20 | + return json({ error: "Invalid or Missing API key" }, { status: 401 }); |
| 21 | + } |
| 22 | + |
| 23 | + const user = await prisma.user.findUnique({ |
| 24 | + where: { |
| 25 | + id: authenticationResult.userId, |
| 26 | + }, |
| 27 | + }); |
| 28 | + |
| 29 | + if (!user) { |
| 30 | + return json({ error: "Invalid or Missing API key" }, { status: 401 }); |
| 31 | + } |
| 32 | + |
| 33 | + if (!user.admin) { |
| 34 | + return json({ error: "You must be an admin to perform this action" }, { status: 403 }); |
| 35 | + } |
| 36 | + |
| 37 | + const { organizationId } = ParamsSchema.parse(params); |
| 38 | + |
| 39 | + const organization = await prisma.organization.findUnique({ |
| 40 | + where: { |
| 41 | + id: organizationId, |
| 42 | + }, |
| 43 | + include: { |
| 44 | + projects: { |
| 45 | + include: { environments: true }, |
| 46 | + }, |
| 47 | + }, |
| 48 | + }); |
| 49 | + |
| 50 | + if (!organization) { |
| 51 | + return json({ error: "Organization not found" }, { status: 404 }); |
| 52 | + } |
| 53 | + |
| 54 | + let created = 0; |
| 55 | + |
| 56 | + for (const project of organization.projects) { |
| 57 | + const stagingEnvironment = project.environments.find((env) => env.type === "STAGING"); |
| 58 | + |
| 59 | + if (!stagingEnvironment) { |
| 60 | + const staging = await createEnvironment(organization, project, "STAGING"); |
| 61 | + await marqs?.updateEnvConcurrencyLimits({ ...staging, organization, project }); |
| 62 | + created++; |
| 63 | + } else { |
| 64 | + await marqs?.updateEnvConcurrencyLimits({ ...stagingEnvironment, organization, project }); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return json({ success: true, created, total: organization.projects.length }); |
| 69 | +} |
0 commit comments