11import { type ActionFunctionArgs , json } from "@remix-run/server-runtime" ;
22import {
3+ Prisma ,
34 type RuntimeEnvironment ,
45 type Organization ,
56 type Project ,
@@ -61,9 +62,16 @@ async function upsertEnvironment(
6162 type : RuntimeEnvironmentType ,
6263 isBranchableEnvironment : boolean
6364) {
64- const existingEnvironment = project . environments . find ( ( env ) => env . type === type ) ;
65+ const existingEnvironment = project . environments . find (
66+ ( env ) => env . type === type && env . parentEnvironmentId === null
67+ ) ;
6568
66- if ( ! existingEnvironment ) {
69+ if ( existingEnvironment ) {
70+ await updateEnvConcurrencyLimits ( { ...existingEnvironment , organization, project } ) ;
71+ return { status : "updated" , environment : existingEnvironment } ;
72+ }
73+
74+ try {
6775 const newEnvironment = await createEnvironment ( {
6876 organization,
6977 project,
@@ -72,8 +80,23 @@ async function upsertEnvironment(
7280 } ) ;
7381 await updateEnvConcurrencyLimits ( { ...newEnvironment , organization, project } ) ;
7482 return { status : "created" , environment : newEnvironment } ;
75- } else {
76- await updateEnvConcurrencyLimits ( { ...existingEnvironment , organization, project } ) ;
77- return { status : "updated" , environment : existingEnvironment } ;
83+ } catch ( error ) {
84+ if ( error instanceof Prisma . PrismaClientKnownRequestError && error . code === "P2002" ) {
85+ const existingAfterConflict = await prisma . runtimeEnvironment . findFirst ( {
86+ where : {
87+ organizationId : organization . id ,
88+ projectId : project . id ,
89+ type,
90+ parentEnvironmentId : null ,
91+ } ,
92+ } ) ;
93+
94+ if ( existingAfterConflict ) {
95+ await updateEnvConcurrencyLimits ( { ...existingAfterConflict , organization, project } ) ;
96+ return { status : "updated" , environment : existingAfterConflict } ;
97+ }
98+ }
99+
100+ throw error ;
78101 }
79102}
0 commit comments