skip to Main Content

Here is a Rest Api method that sets the user rating. The database table contains the composite primary key: user_id + rate_id.

When user tries to set the same rating the framework throws an exception. I catch it and return response.

How to handle such these cases and make the method idempotent?

2

Answers


  1. Without more detail (and a code sample), it’s difficult to advise. However, in high-level, general terms you could do one of the following (presuming you are using a relational database):

    • catch the Exception thrown by your database: if it relates to a duplicate primary key then you could handle the case accordingly (ie perhaps ignore it and continue as if the INSERT operation had succeeded)
    • perform a SELECT operation on your database, just before you attempt to save the value. If there is already a value there, then use UPDATE rather than INSERT
    • some databases (eg MySQL) have extensions to standard SQL that allow you to do things like REPLACE INTO or INSERT IGNORE: you could use one of these instead of the standard INSERT statement
    Login or Signup to reply.
  2. You can use firstOrCreate() or updateOrCreate() methods of laravel query builder to prevent this exception and keep your method idempotent

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search