Dmitry Fadeev
Dmitry Fadeev

Reputation: 2083

Fetch: how to use etags?

I'm planning to use Etags to validate the edited item to avoid mid-air collisions (if the item has been modified by other processes or users in the DB). here is the plan:

Questions:

Is this a good approach?

How to store it nicely in item object using fetch? More precisely, how to combine the header value (Etag) with what comes back from response.json() in a nice way?

Thank you!

Upvotes: 4

Views: 5419

Answers (1)

Fraser
Fraser

Reputation: 17094

  1. Is this a good approach?

Yes it is the intended use/documented approach.

  1. How to store it nicely in item object using fetch?

This is debateable, but you could just wrap the etag header in with your data and pass that object. e.g.

    fetch('/data.json')
        .then(r => ({
            etag: r.headers.get('etag'), 
            json: r.json()
        }))
        .then(data => { 
            // do something with your etag and data
            console.log(data.etag);
            data.json.then(console.log)
        })
        .catch(console.error.bind(console));

See

Avoiding mid-air collisions With the help of the ETag and the If-Match headers, you can detect mid-air edit collisions.

For example, when editing a wiki, the current wiki content may be hashed and put into an Etag header in the response:

ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" When saving changes to a wiki page (posting data), the POST request will contain the If-Match header containing the ETag values to check freshness against.

If-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4" If the hashes don't match, it means that the document has been edited in-between and a 412 Precondition Failed error is thrown.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag

Upvotes: 0

Related Questions