Sobes.tech
Junior — Middle

Can you give examples of methods that are idempotent?

sobes.tech AI

Answer from AI

Idempotence means that multiple executions of a method with the same input data will not change the system's state after the first call.

Examples of idempotent methods in Node.js:

  • HTTP methods GET, PUT, DELETE are considered idempotent by default.
  • A method that updates a record in a database to set a specific value, for example:
app.put('/user/:id', (req, res) => {
  // Update user with id
  User.updateOne({ _id: req.params.id }, { name: req.body.name })
    .then(() => res.send('Updated'));
});
  • Resource deletion method:
app.delete('/item/:id', (req, res) => {
  Item.deleteOne({ _id: req.params.id })
    .then(() => res.send('Deleted'));
});

Repeated calls to PUT or DELETE with the same parameters will not change the state after the first successful call, which is the essence of idempotence.