From df59f07cfd65bfb370284bd7cfa90f2913716020 Mon Sep 17 00:00:00 2001 From: bduran Date: Wed, 11 Sep 2024 14:00:17 -0700 Subject: [PATCH] cleanup tags on failure --- src/packages/plan/gql.ts | 11 +++++++++++ src/packages/plan/plan.ts | 24 ++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/packages/plan/gql.ts b/src/packages/plan/gql.ts index 10c1fd0..16c79f5 100644 --- a/src/packages/plan/gql.ts +++ b/src/packages/plan/gql.ts @@ -61,6 +61,17 @@ export default { } } `, + DELETE_TAGS: `#graphql + mutation DeleteTags($tagIds: [Int!]! = []) { + delete_tags( + where: { + id: { _in: $tagIds } + } + ) { + affected_rows + } + } + `, GET_TAGS: `#graphql query GetTags { tags(order_by: { name: desc }) { diff --git a/src/packages/plan/plan.ts b/src/packages/plan/plan.ts index 89df699..d61f71c 100644 --- a/src/packages/plan/plan.ts +++ b/src/packages/plan/plan.ts @@ -52,6 +52,7 @@ export async function importPlan(req: Request, res: Response) { }; let createdPlan: PlanSchema | null = null; + let createdTags: Tag[] = []; try { const { activities, simulation_arguments }: PlanTransfer = await new Promise(resolve => { @@ -143,7 +144,7 @@ export async function importPlan(req: Request, res: Response) { {}, ); - await fetch(GQL_API_URL, { + const createdTagsResponse = await fetch(GQL_API_URL, { body: JSON.stringify({ query: gql.CREATE_TAGS, variables: { tags: Object.values(activityTags) }, @@ -152,6 +153,16 @@ export async function importPlan(req: Request, res: Response) { method: 'POST', }); + const { data } = (await createdTagsResponse.json()) as { + data: { + insert_tags: { returning: Tag[] }; + }; + }; + + if (data && data.insert_tags && data.insert_tags.returning.length) { + createdTags = data.insert_tags.returning; + } + const tagsResponse = await fetch(GQL_API_URL, { body: JSON.stringify({ query: gql.GET_TAGS, @@ -294,14 +305,23 @@ export async function importPlan(req: Request, res: Response) { logger.error(`POST /importPlan: Error occurred during plan ${name} import`); logger.error(error); + // cleanup the imported plan if it failed along the way if (createdPlan) { + // delete the plan - activities associated to the plan will be automatically cleaned up await fetch(GQL_API_URL, { body: JSON.stringify({ query: gql.DELETE_PLAN, variables: { id: createdPlan.id } }), headers, method: 'POST', }); + + // if any activity tags were created as a result of this import, remove them + await fetch(GQL_API_URL, { + body: JSON.stringify({ query: gql.DELETE_TAGS, variables: { tagIds: createdTags.map(({ id }) => id) } }), + headers, + method: 'POST', + }); } - res.send(500); + res.sendStatus(500); } }