Code Review / If item exist or not


#1

I want to check if there’s already a record in the database. If not set the lastInvoiceNumber to a number. Otherwise, take the number from the last item.

So far this is my code:

    const checkIfInvoiceExist = await Invoice.first();

    let lastInvoiceNumber = null;

    if (checkIfInvoiceExist === null) {
      // TODO get default number from database
      lastInvoiceNumber = 10000;
    } else {
      /*
       * Get the latest invoice number from the last record
       */
      let lastInvoice = await Database.select('invoice_number')
        .from('invoices')
        .orderBy('invoice_number', 'desc')
        .first();

      lastInvoiceNumber = ++lastInvoice.invoice_number;
    }

    /*
     * Save the new invoice
     */
    const invoice = await Invoice.create({
      invoice_number: lastInvoiceNumber,
      ......

Is this code fine, or could i improve this code ( maybe with ES6 )?
The downside with this code, i check if a record exist with every new invoice.

But the database query to check if the record exist has only to be done once.
Because if the first record is created, i don’t need this query anymore of course.

I could make just a first dummy entry in the database for the very first record, but i don’t think that a good solution.


#2
const lastInvoice = await Database.select('invoice_number')
    .from('invoices')
    .orderBy('invoice_number', 'desc')
    .first();


if (lastInvoice ) {

  lastInvoiceNumber = ++lastInvoice.invoice_number;

} else {

  // TODO get default number from database
  lastInvoiceNumber = 10000;
}