Skip to content

Instantly share code, notes, and snippets.

@jeferson-sb
Created July 10, 2021 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeferson-sb/f5ee5ec361c8b9203133f5ef6a3b9a65 to your computer and use it in GitHub Desktop.
Save jeferson-sb/f5ee5ec361c8b9203133f5ef6a3b9a65 to your computer and use it in GitHub Desktop.
import { openDB, deleteDB } from 'idb';
export const init = async ({ name, storeName, version }) => {
await openDB(name, version, {
upgrade(db, oldVersion, newVersion, transaction) {
const store = db.createObjectStore(storeName, {
autoIncrement: true,
});
},
});
};
export const destroy = async name => {
await deleteDB(name);
};
const useIndexedDB = ({ name, storeName, version = 1 }) => {
init({ name, storeName, version });
const insert = async (key, value) => {
const db = await openDB(name, version);
await db.put(storeName, value, key);
};
const get = async key => {
const db = await openDB(name, version);
return await db
.transaction(storeName, 'readwrite')
.objectStore(storeName)
.get(key);
};
const getAll = async () => {
const db = await openDB(name, version);
return await db.transaction(storeName).objectStore(storeName).getAll();
};
const getFromIndex = async (indexName, key) => {
const db = await openDB(name, version);
return await db.getFromIndex(storeName, indexName, key);
};
const remove = async key => {
const db = await openDB(name, version);
await db.delete(storeName, key);
};
const isStale = async (cache, seconds) => {
const currentDate = new Date();
const createdDate = new Date(cache.createdAt);
createdDate.setSeconds(createdDate.getSeconds() + seconds);
return createdDate < currentDate;
};
return { insert, get, getAll, getFromIndex, isStale, remove };
};
export default useIndexedDB;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment