2
\$\begingroup\$

I have a service within a larger set of microservices that's handling a RPC call. My function mainly just parses through the request, uses the data to insert data into our MongoDB database, and then returns the data that got stored into the database (should be idempotent).

Endpoint Function

type GAPFType = {
  facultyId: number,
  created: number,
  lastModified: number,
  status: Status,
  attachedDocuments: Array<DocumentType>
};

type CallbackType = {
  error: ?string,
  payload: ?GAPFType
};

const submitGAPFBackend = async (
  gapfRequest: GAPFType
): Promise<CallbackType> => {
  logger.info("Enter submitGAPFBackend with request body %j", gapfRequest);

  const { facultyId } = gapfRequest;
  if (facultyId === undefined) {
    logger.error("facultyId missing from request body: %j", gapfRequest);
    return invalidSubmitGAPFCallError;
  }

  const gapf = createSubmitGAPFObject(gapfRequest);
  logger.info("Request GAPF object: %j", gapf);

  try {
    const submittedForm = await GAPFApplication.submit(gapf);
    const submittedData = getSubmittedGAPF(submittedForm);
    logger.info("DB response with filtered data: %j", submittedData);

    const payload = GAPF.create(submittedData);
    logger.info("Response payload data: %j", payload);
    return { error: null, payload: payload };
  } catch (error) {
    logger.error("Error: %j", error.message);
    return { error: error, payload: null };
  }
};

Helper Functions

export const createSubmitGAPFObject = gapfRequest => {
  const now = getUNIXTimestamp();
  const {
    facultyId,
    status = "SUBMITTED",
    created = now,
    attachedDocuments = [{}]
  } = gapfRequest;

  return {
    facultyId: facultyId,
    created: created,
    lastModified: now,
    status: status,
    attachedDocuments: attachedDocuments
  };
};

export const getSubmittedGAPF = submittedForm => {
  return {
    facultyId: submittedForm.facultyId,
    created: submittedForm.created,
    lastModified: submittedForm.lastModified,
    status: submittedForm.status,
    attachedDocuments: submittedForm.attachedDocuments.map(doc => {
      // removing _id from document data
      return {
        name: doc.name,
        link: doc.link,
        attachedDate: doc.attachedDate
      };
    })
  };
};

export const invalidSubmitGAPFCallError = {
  error: {
    message: "facultyId missing from request body",
    status: grpc.status.INVALID_ARGUMENT
  },
  payload: null
};

export const getUNIXTimestamp = () => {
  return Math.floor(Date.now() / 1000);
};

I don't program in Javascript often, so I was hoping to get some feedback on writing cleaner or more idiomatic code. The original code has docstrings, but I've left those out for brevity. And the type annotations are from flow.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.