Code review / cleanup for store & update


#1

I have one method to store and one method to update a contact. For me my code looks a bit messy and i think this could be improved by some code cleanup.

Do you think i could put the store & update in one method?
Or any other tips to clean up the code?

'use strict';

const Contact = use('App/Models/Contact');

class ContactController {
.....
async store({ request, response }) {
    try {
      let contact = new Contact();

      contact.fill(request.all());

      await contact.save();

      return response.json({
        status: 'success',
        data: contact
      });
    } catch (error) {
      response.status(400).json({
        status: 'error',
        message: error
      });
    }
  }

  async update({ request, response }) {
    try {
      let contact = await Contact.query()
        .with('country')
        .where('pseudo_id', request.params.id)
        .first();

      contact.merge(request.all());

      await contact.save();

      return response.json({
        status: 'success',
        data: contact
      });
    } catch (error) {
      response.status(400).json({
        status: 'error',
        message: error
      });
    }
  }

#2

Hey @kayyyy! :wave:

You could remove the try/catch block and use the global error handler for that.

Also, the return could be simplified by sending a simple JSON.


#3

Thanks for your answer, i’ll use the global error handler and the validators :slight_smile:
But what do you mean with a simple JSON - Just returning a 200 code?

return response.status(200).json();

Or just

return contact

#4

I mean no need to use response.json, you can directly send back the object.