etag object tools
npm install mharj-etag-tools``bash`
npm i mharj-etag-tools
`typescript`
interface IEtagObject
readonly etag: string | null;
readonly data: T;
}
Cache validation example with state (i.e. redux)
`typescript``
const todo = getState().todo; // IEtagObject
const headers = new Headers();
if (haveETag(todo)) { // Checks if todo is IWithEtagObject type (has actual ETag value)
headers.set('if-none-match', getETag(todo)); // Attaches ETag header from last state
}
const res = await fetch('https://jsonplaceholder.typicode.com/todos/1', {headers});
if (res.status === 200) {
const data = await res.json();
const todoEtagObject = wrapEtag(data, getEtagHeader(res));
dispatch(storeTodo(todoEtagObject)); // updates IEtagObject
}
if (res.status === 304) {
// do nothing as state is already up to date
}