Skip to content

Commit

Permalink
cleanup tags on failure
Browse files Browse the repository at this point in the history
  • Loading branch information
duranb committed Sep 23, 2024
1 parent beabbe8 commit 7f104aa
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
11 changes: 11 additions & 0 deletions src/packages/plan/gql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) {
Expand Down
24 changes: 22 additions & 2 deletions src/packages/plan/plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down Expand Up @@ -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) },
Expand All @@ -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,
Expand Down Expand Up @@ -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);
}
}

Expand Down

0 comments on commit 7f104aa

Please sign in to comment.