@@ -52,6 +52,7 @@ export async function importPlan(req: Request, res: Response) {
5252 } ;
5353
5454 let createdPlan : PlanSchema | null = null ;
55+ let createdTags : Tag [ ] = [ ] ;
5556
5657 try {
5758 const { activities, simulation_arguments } : PlanTransfer = await new Promise ( resolve => {
@@ -143,7 +144,7 @@ export async function importPlan(req: Request, res: Response) {
143144 { } ,
144145 ) ;
145146
146- await fetch ( GQL_API_URL , {
147+ const createdTagsResponse = await fetch ( GQL_API_URL , {
147148 body : JSON . stringify ( {
148149 query : gql . CREATE_TAGS ,
149150 variables : { tags : Object . values ( activityTags ) } ,
@@ -152,6 +153,16 @@ export async function importPlan(req: Request, res: Response) {
152153 method : 'POST' ,
153154 } ) ;
154155
156+ const { data } = ( await createdTagsResponse . json ( ) ) as {
157+ data : {
158+ insert_tags : { returning : Tag [ ] } ;
159+ } ;
160+ } ;
161+
162+ if ( data && data . insert_tags && data . insert_tags . returning . length ) {
163+ createdTags = data . insert_tags . returning ;
164+ }
165+
155166 const tagsResponse = await fetch ( GQL_API_URL , {
156167 body : JSON . stringify ( {
157168 query : gql . GET_TAGS ,
@@ -294,14 +305,23 @@ export async function importPlan(req: Request, res: Response) {
294305 logger . error ( `POST /importPlan: Error occurred during plan ${ name } import` ) ;
295306 logger . error ( error ) ;
296307
308+ // cleanup the imported plan if it failed along the way
297309 if ( createdPlan ) {
310+ // delete the plan - activities associated to the plan will be automatically cleaned up
298311 await fetch ( GQL_API_URL , {
299312 body : JSON . stringify ( { query : gql . DELETE_PLAN , variables : { id : createdPlan . id } } ) ,
300313 headers,
301314 method : 'POST' ,
302315 } ) ;
316+
317+ // if any activity tags were created as a result of this import, remove them
318+ await fetch ( GQL_API_URL , {
319+ body : JSON . stringify ( { query : gql . DELETE_TAGS , variables : { tagIds : createdTags . map ( ( { id } ) => id ) } } ) ,
320+ headers,
321+ method : 'POST' ,
322+ } ) ;
303323 }
304- res . send ( 500 ) ;
324+ res . sendStatus ( 500 ) ;
305325 }
306326}
307327
0 commit comments