All files / lib/lambda deleteDraft.ts

85.29% Statements 29/34
77.41% Branches 24/31
100% Functions 3/3
84.84% Lines 28/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124                    1x                         1x 1x 1x   1x 1x                     1x         7x   7x 1x           6x   6x 36x 6x 1x           5x   5x             5x 5x 1x           4x 4x   4x   4x 4x                                     1x 1x                     3x          
import { getDraftPackage } from "libs/api/package";
import { response } from "libs/handler-lib";
import * as os from "libs/opensearch-lib";
import { getDomainAndNamespace } from "libs/utils";
import { APIGatewayEvent, SEATOOL_STATUS } from "shared-types";
import { isStateUser } from "shared-utils";
import { z } from "zod";
 
import { authenticatedMiddy, ContextWithAuthenticatedUser } from "./middleware";
 
const deleteDraftEventSchema = z
  .object({
    body: z
      .object({
        id: z.string().trim().min(1),
      })
      .strict(),
  })
  .passthrough();
 
export type DeleteDraftEvent = APIGatewayEvent & z.infer<typeof deleteDraftEventSchema>;
type DeleteDraftContext = ContextWithAuthenticatedUser;
 
const isVersionConflictError = (error: unknown) => {
  Eif (error && typeof error === "object") {
    const osType = (error as { meta?: { body?: { error?: { type?: string } } } }).meta?.body?.error
      ?.type;
    Eif (osType === "version_conflict_engine_exception") {
      return true;
    }
  }
 
  if (error instanceof Error) {
    return error.message.includes("version_conflict_engine_exception");
  }
 
  return false;
};
 
export const handler = authenticatedMiddy({
  opensearch: true,
  setToContext: true,
  eventSchema: deleteDraftEventSchema,
}).handler(async (event: DeleteDraftEvent, context: DeleteDraftContext) => {
  const { authenticatedUser } = context;
 
  if (!authenticatedUser || !isStateUser(authenticatedUser)) {
    return response({
      statusCode: 403,
      body: { message: "Only state users can delete drafts." },
    });
  }
 
  const id = event.body.id.toUpperCase();
 
  const stateCode = id.slice(0, 2);
  const userStates = authenticatedUser.states?.map((state) => state.toUpperCase()) || [];
  if (!userStates.includes(stateCode)) {
    return response({
      statusCode: 403,
      body: { message: "Not authorized to view this resource" },
    });
  }
 
  const packageResult = await getDraftPackage(id);
 
  Iif (!packageResult || !packageResult.found || !packageResult._source) {
    return response({
      statusCode: 404,
      body: { message: "No record found for the given id" },
    });
  }
 
  const submission = packageResult._source;
  if (submission.deleted || submission.seatoolStatus !== SEATOOL_STATUS.DRAFT) {
    return response({
      statusCode: 409,
      body: { message: `Package ${submission.id} is not an active draft.` },
    });
  }
 
  const timestamp = new Date().toISOString();
  const { domain, index } = getDomainAndNamespace("draftmain");
  const hasVersionData =
    typeof packageResult._seq_no === "number" && typeof packageResult._primary_term === "number";
 
  try {
    await os.updateData(domain, {
      index,
      id: submission.id,
      refresh: true,
      ...(hasVersionData && {
        if_seq_no: packageResult._seq_no,
        if_primary_term: packageResult._primary_term,
      }),
      body: {
        doc: {
          deleted: true,
          changedDate: timestamp,
          makoChangedDate: timestamp,
          statusDate: timestamp,
        },
        doc_as_upsert: false,
      },
    });
  } catch (error) {
    Eif (isVersionConflictError(error)) {
      return response({
        statusCode: 409,
        body: {
          message: "Draft was updated by another user. Refresh this page and try deleting again.",
        },
      });
    }
 
    throw error;
  }
 
  return response({
    statusCode: 200,
    body: { message: "Draft deleted", id: submission.id },
  });
});