Skip to content

Instantly share code, notes, and snippets.

@markosmk
Last active December 8, 2022 11:11
Show Gist options
  • Save markosmk/7d701649dce0fad8a436e79992790e9d to your computer and use it in GitHub Desktop.
Save markosmk/7d701649dce0fad8a436e79992790e9d to your computer and use it in GitHub Desktop.
Simple Class to use LocalStorage how ApiRest
'use strict';
import { v4 as uuidv4 } from 'uuid';
const NAME_DB = 'accounts';
export class RestApiLocalStorage {
currentItems = [];
constructor() {
this.getData();
}
getData() {
const DB = window.localStorage.getItem(NAME_DB);
if (!DB || DB !== 'undefined') {
this.currentItems = JSON.parse(DB);
} else {
this.currentItems = [];
window.localStorage.setItem(NAME_DB, JSON.stringify(this.currentItems));
}
}
saveData(data) {
if (!this.currentItems) {
this.currentItems = [];
}
const newData = data ? [...this.currentItems, data] : this.currentItems;
window.localStorage.setItem(NAME_DB, JSON.stringify(newData));
this.getData();
}
getAll() {
return this.currentItems;
}
get(id) {
return this.currentItems.find((item) => item.id === id);
}
post(data) {
this.saveData({ id: uuidv4(), ...data });
return this.currentItems;
}
put(id, data) {
this.currentItems = this.currentItems.map((item) => {
if (item.id === id) {
item = { ...item, ...data };
}
return item;
});
this.saveData();
return this.currentItems;
}
destroy(id) {
this.currentItems = this.currentItems.filter((item) => item.id !== id);
this.saveData();
return this.currentItems;
}
}
const instance = new RestApiLocalStorage();
export default instance;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment