1
\$\begingroup\$

I'm quite new to the language and I just started using async/await. I've written this function for an API that I'm developing. It checks what is sent by the user, specially the status that he wants to set. The function will just update the application if it gets refused but, in case it gets accepted, it will also create an allocation based on the other fields that the user added.

const application_update = async (request, response) => {
  try {
    const { id } = request.params;
    if (!ObjectId.isValid(id)) throw 'invalid objectid';
    const { status, garden, start_date, end_date } = request.body;
    if (_.isEmpty(status) || !['Aceite', 'Recusado'].includes(status)) throw 'status empty or invalid';
    const { user } = await Application.findById(id);
    if (!user) throw 'invalid application';
    if (status == 'Aceite') {
      const now = moment().format();
      const a = await Allocation
        .findOne({ $or: [{ garden, start_date: { $lt: now }, end_date: { $gt: now } },
          { user, start_date: { $lt: now }, end_date: { $gt: now } }] });
      if (a) throw 'invalid request';
      const body = { user, garden, start_date, end_date };
      const allocation = new Allocation(body);
      const all = await allocation.save();
      if (!all) throw 'error creating the allocation document';
    }
    const app = await Application.findByIdAndUpdate(id, { status }, { new: true, runValidators: true });
    if (!app) throw 'error updating the application document';
    response.status(200).send(app);
  } catch (error) {
    response.status(400).send({ error });
  }
};

The code doesn't include but Mongoose verifications are in place so I can control if he doesn't fill the fields used for the allocation.

What could be improved? I feel like I'm using way too many ifs but I believe they're needed to make sure all the fields exists and to retrieve the response as soon as possible if any of them fail.

\$\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.