Create a record if no specific row exist


#1

I have a settings table which should only have one row. Now I want to check if a record/row exists, if not create the record.

This is my attempt, is this the right way to solve this problem?

async update({ request }) {
    const all = request.all();
    try {
      let settings = await Settings.firstOrFail();
      settings.merge(all);

      await settings.save();

      return settings;
    } catch (error) {
      let settings = new Settings();
      settings.fill(request.all());

      await settings.save();

      return settings;
    }
  }

#2

try{}catch(){} concept is about to process two scenarios:

  • First one if your code works fine and the you can process it
  • Second one If your code trhows an error then you should manage it here

Maybe would be more Eloquent if you do


const data = await ModelName.query().firstOrFail().fetch()

if(data){
     don´t make registration......................................
}else{
   make a new record
}


#3

This was also my first attempt.
But firstOrFail throws an exception like

message: "E_MISSING_DATABASE_ROW: Cannot find database row for Setting model↵> More details: https://err.sh/adonisjs/errors/E_MISSING_DATABASE_ROW"
name: "ModelNotFoundException"
status: 404

So the if statement will never go trough.
And Adonis throws also this error in the console

warning:
  WARNING: Adonis has detected an unhandled promise rejection, which may
  cause undesired behavior in production.
  To stop this warning, use catch() on promises or wrap await
  calls inside try/catch.

So i could make something like

    const settings = Settings.query()
      .firstOrFail()
      .catch(() => {
        console.log('error');
      });

But this is almost the same as my first version …