Skip to content

Commit

Permalink
Use indexedDB for persistant data
Browse files Browse the repository at this point in the history
With the regular localStorage implementation, people can access that very data and manipulate it to their likings. While this isn't necessarily a bad thing, it's safer for indexedDB to be used so its more private, plus, it doesn't mess with the user's already existing localStorage data.

Regards.
  • Loading branch information
akabutnicer authored Feb 21, 2024
1 parent 21a2708 commit 6de5162
Showing 1 changed file with 51 additions and 8 deletions.
59 changes: 51 additions & 8 deletions packages/emoji-mart/src/helpers/store.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,60 @@
function getIDB() {
try {
if (typeof indexedDB !== 'undefined') {
return indexedDB;
}
if (typeof webkitIndexedDB !== 'undefined') {
return webkitIndexedDB;
}
if (typeof mozIndexedDB !== 'undefined') {
return mozIndexedDB;
}
if (typeof OIndexedDB !== 'undefined') {
return OIndexedDB;
}
if (typeof msIndexedDB !== 'undefined') {
return msIndexedDB;
}
} catch (e) {
return;
}
}

var idb = getIDB();

function getStore(callback, error) {
const db = idb.open("emoji-mart-db");
db.onupgradeneeded = function () {
db.result.createObjectStore("emoji-store");
};
db.onsuccess = ({ result }) => {
const store = result
.transaction("emoji-store", "readwrite")
.objectStore("emoji-store");
callback(store);
};
db.onerror = error;
}
function runStoreCommand(command: string, args, success) {
getStore((store) => {
const request = store[command](...args);
request.onsuccess = success;
request.onerror = function () {
throw "Error running emoji-mart command: " + command;
};
});
}
function set(key: string, value: string) {
try {
window.localStorage[`emoji-mart.${key}`] = JSON.stringify(value)
runStoreCommand("put", value, key);
} catch (error) {}
}

function get(key: string): any {
try {
const value = window.localStorage[`emoji-mart.${key}`]

if (value) {
return JSON.parse(value)
}
return runStoreCommand("get", key, function ({ result }) {
return result;
});
} catch (error) {}
}

export default { set, get }
export default { set, get };

0 comments on commit 6de5162

Please sign in to comment.