record.js/dist/record.cjs.js

2 lines
2.2 KiB
JavaScript

var __defProp=Object.defineProperty;var __markAsModule=target=>__defProp(target,"__esModule",{value:true});var __export=(target,all)=>{__markAsModule(target);for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};__export(exports,{default:()=>record_default});/*! Record.js v0.8.0 | MIT | https://github.com/n2geoff/record.js */class Record{constructor(opts){this.store=(opts||{}).store;this.debug=(opts||{}).debug||false;this.records=[];if(this.store&&localStorage){this._log("Initializing localStorage for "+this.store);let existing=this._load()||[];this.records=[...existing]}}_log(){if(this.debug){console.log(...arguments)}}add(entry){if(Array.isArray(entry)){let entries=[];entry.forEach(()=>{if(!entry.id){entry.id=Math.random().toString(36).substr(2,9)}this.records.push(entry);this.entries.push(entry)});this._save();return entries}else{if(!entry.id){entry.id=Math.random().toString(36).substr(2,9)}this.records.push(entry);this._save();return entry}}update(entry){var idx=this.records.indexOf(entry);if(this.records[idx].id===entry.id){this.records.splice(idx,1,entry);this._save();return entry}else{return false}}find(key){if(!key){return this.records}if(typeof key==="string"||typeof key==="number"){return this.records.filter(record=>{return record.id===key})}let value=Object.keys(key);return this.records.filter(record=>{if(value.indexOf("id")!==-1){return record.id===key.id}return value.every(val=>{return record[val]===key[val]})})}remove(entry){if(!entry||Array.isArray(entry)){this._log(console.error("remove() accepts a single object"));return[]}let entries=this.find(entry);entries.forEach(item=>{this.records.splice(this.records.indexOf(item),1)});this._save();return entries}clear(){this.records=[];this._save()}_save(){if(this.store&&localStorage){localStorage.setItem(this.store,JSON.stringify(this.records))}}_load(){if(this.store&&localStorage){return JSON.parse(localStorage.getItem(this.store))||[]}}dump(){function download(filename,content){let a=document.createElement("a");let file=new Blob([content],{type:"text/plain"});a.href=URL.createObjectURL(file);a.download=filename;a.click()}download(`${this.store||"data"}.json`,JSON.stringify(this._load(),null,4))}}var record_default=Record;