All files / lib/lambda/update updatePackage.ts

98.5% Statements 66/67
88.09% Branches 37/42
100% Functions 6/6
98.5% Lines 66/67

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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265                            1x 3x 3x 1x     2x   2x                             2x                           1x                 4x 4x 1x   3x 3x   3x 1x           2x 1x           1x 1x       1x   1x                                 1x                       1x             7x 7x 1x               6x 6x 2x           4x 4x 1x           3x 3x   2x 2x   2x 1x           1x   1x   1x                                   1x           1x               1x 17x 1x         16x 16x 14x   16x       16x 16x       16x 2x                     14x   14x 14x 1x           13x 2x     11x 7x     4x 4x             4x 4x            
import { response } from "libs/handler-lib";
import { APIGatewayEvent } from "aws-lambda";
import { getPackage } from "libs/api/package";
import { produceMessage } from "libs/api/kafka";
import { ItemResult } from "shared-types/opensearch/main";
import { getPackageType } from "./getPackageType";
import { events } from "shared-types";
import { z } from "zod";
 
/** @typedef {object} json
 * @property {object} body
 * @property {string} body.packageId
 * @property {string} body.action
 */
const sendDeleteMessage = async (packageId: string) => {
  const topicName = process.env.topicName as string;
  if (!topicName) {
    throw new Error("Topic name is not defined");
  }
 
  const currentTime = Date.now();
 
  await produceMessage(
    topicName,
    packageId,
    JSON.stringify({
      id: packageId,
      deleted: true,
      isAdminChange: true,
      adminChangeType: "delete",
      makoChangedDate: currentTime,
      changedDate: currentTime,
      statusDate: currentTime,
      timestamp: currentTime,
    }),
  );
 
  return response({
    statusCode: 200,
    body: { message: `${packageId} has been deleted.` },
  });
};
 
/** @typedef {object} json
 * @property {object} body
 * @property {string} body.packageId
 * @property {string} body.action
 * @property {object} body.updatedFields
 * @property {string} body.updatedFields.title
 */
 
const sendUpdateValuesMessage = async ({
  currentPackage,
  updatedFields,
  changeReason,
}: {
  currentPackage: ItemResult;
  updatedFields: object;
  changeReason?: string;
}) => {
  const topicName = process.env.topicName as string;
  if (!topicName) {
    throw new Error("Topic name is not defined");
  }
  const invalidFields = Object.keys(updatedFields).filter(
    (field) => !(field in currentPackage._source),
  );
  if (invalidFields.length > 0) {
    return response({
      statusCode: 400,
      body: { message: `Cannot update invalid field(s): ${invalidFields.join(", ")}` },
    });
  }
 
  if ("id" in updatedFields) {
    return response({
      statusCode: 400,
      body: { message: "ID is not a valid field to update" },
    });
  }
 
  const fieldNames = Object.keys(updatedFields).join(", ");
  const changeMadeText = `${fieldNames} ${
    Object.keys(updatedFields).length > 1 ? "have" : "has"
  } been updated`;
 
  const currentTime = Date.now();
 
  await produceMessage(
    topicName,
    currentPackage._id,
    JSON.stringify({
      id: currentPackage._id,
      ...updatedFields,
      isAdminChange: true,
      adminChangeType: "update-values",
      changeMade: changeMadeText,
      changeReason,
      makoChangedDate: currentTime,
      changedDate: currentTime,
      statusDate: currentTime,
      timestamp: currentTime,
    }),
  );
 
  return response({
    statusCode: 200,
    body: { message: `${changeMadeText} in package ${currentPackage._id}.` },
  });
};
 
/** @typedef {object} json
 * @property {object} body
 * @property {string} body.packageId
 * @property {string} body.action
 * @property {string} body.updatedId
 */
const sendUpdateIdMessage = async ({
  currentPackage,
  updatedId,
}: {
  currentPackage: ItemResult;
  updatedId: string;
}) => {
  const topicName = process.env.topicName as string;
  if (!topicName) {
    throw new Error("Topic name is not defined");
  }
  // ID and changeMade are excluded; the rest of the object has to be spread into the new package
  const {
    id: _id,
    changeMade: _changeMade,
    origin: _origin,
    ...remainingFields
  } = currentPackage._source;
  if (updatedId === currentPackage._id) {
    return response({
      statusCode: 400,
      body: { message: "New ID required to update package" },
    });
  }
  // check if a package with this new ID already exists
  const packageExists = await getPackage(updatedId);
  if (packageExists?.found) {
    return response({
      statusCode: 400,
      body: { message: "This ID already exists" },
    });
  }
  // use event of current package to determine how ID should be formatted
  const packageEvent = await getPackageType(currentPackage._id);
  const packageSubmissionTypeSchema = events[packageEvent as keyof typeof events].baseSchema;
 
  const idSchema = packageSubmissionTypeSchema.shape.id;
  const parsedId = idSchema.safeParse(updatedId);
 
  if (!parsedId.success) {
    return response({
      statusCode: 400,
      body: parsedId.error.message,
    });
  }
 
  await sendDeleteMessage(currentPackage._id);
 
  const currentTime = Date.now();
 
  await produceMessage(
    topicName,
    updatedId,
    JSON.stringify({
      id: updatedId,
      idToBeUpdated: currentPackage._id,
      ...remainingFields,
      origin: "OneMAC",
      changeMade: "ID has been updated.",
      isAdminChange: true,
      adminChangeType: "update-id",
      makoChangedDate: currentTime,
      changedDate: currentTime,
      statusDate: currentTime,
      timestamp: currentTime,
    }),
  );
 
  return response({
    statusCode: 200,
    body: { message: `The ID of package ${currentPackage._id} has been updated to ${updatedId}.` },
  });
};
 
const updatePackageEventBodySchema = z.object({
  packageId: z.string(),
  action: z.enum(["update-values", "update-id", "delete"]),
  updatedId: z.string().optional(),
  updatedFields: z.record(z.unknown()).optional(),
  changeReason: z.string().optional(),
});
 
export const handler = async (event: APIGatewayEvent) => {
  if (!event.body) {
    return response({
      statusCode: 400,
      body: { message: "Event body required" },
    });
  }
  try {
    const parseEventBody = (body: unknown) => {
      return updatePackageEventBodySchema.parse(typeof body === "string" ? JSON.parse(body) : body);
    };
    let body = {
      packageId: "",
      action: "",
    };
    if (typeof event.body === "string") {
      body = JSON.parse(event.body);
    } else E{
      body = event.body;
    }
    if (!body.packageId || !body.action) {
      return response({
        statusCode: 400,
        body: { message: "Package ID and action are required" },
      });
    }
    const {
      packageId,
      action,
      updatedId = packageId,
      updatedFields = {},
      changeReason,
    } = parseEventBody(event.body);
 
    const currentPackage = await getPackage(packageId);
    if (!currentPackage || currentPackage.found == false) {
      return response({
        statusCode: 404,
        body: { message: "No record found for the given id" },
      });
    }
 
    if (action === "delete") {
      return await sendDeleteMessage(packageId);
    }
 
    if (action === "update-id") {
      return await sendUpdateIdMessage({ currentPackage, updatedId });
    }
 
    Eif (action === "update-values") {
      return await sendUpdateValuesMessage({
        currentPackage,
        updatedFields,
        changeReason,
      });
    }
  } catch (err) {
    console.error("Error has occured modifying package:", err);
    return response({
      statusCode: 500,
      body: { message: err.message || "Internal Server Error" },
    });
  }
};