added dump() to export data to json file

This commit is contained in:
Geoff Doty 2018-04-15 17:59:09 -04:00
parent 92c41ad79f
commit 9e6a3e5324
5 changed files with 54 additions and 29 deletions

View File

@ -2,9 +2,9 @@
> A minimalistic object collection library > A minimalistic object collection library
**Record.js** aims to provide a lite, *2kb*, *no dependency* collection utility to help build simple in-memory or local storage data sets. Records are stored as `JSON`. **Record.js** aims to provide a lite, *2kb*, *zero-dependency* collection utility to help build simple in-memory or local storage data records. Records are stored as arrays in a `JSON` object.
> SOON: ability to export json collections Records can export raw JSON records, with no internals, via `.dump()`
## WIP ## WIP
@ -24,7 +24,7 @@ add something to the collection
pets.add({"name": "Fluffy", "type": "cat"}); pets.add({"name": "Fluffy", "type": "cat"});
// [{"id": "123fk91j7", "name": "Fluffy", "type": "cat"}] // [{"id": "123fk91j7", "name": "Fluffy", "type": "cat"}]
an `id` field is auto-generated if not provided, this allows easy record retrival via an `id` field is auto-generated if not provided, this allows easy record retrieval via
pets.find("123fk91j7"); pets.find("123fk91j7");
// [{"id": "123fk91j7", "name": "Fluffy", "type": "cat"}] // [{"id": "123fk91j7", "name": "Fluffy", "type": "cat"}]
@ -53,17 +53,26 @@ The public API is very simple, you really only need 3 methods: `add`, `remove`,
| `.add(object)` | Adds entry to collection and returns entry(s) added | | `.add(object)` | Adds entry to collection and returns entry(s) added |
| `.remove(id|object)` | Removes entry(s) from collection and returns removed | | `.remove(id|object)` | Removes entry(s) from collection and returns removed |
| `.find(id|object)` | find all, find by id, or find by filter, returns array of entries | | `.find(id|object)` | find all, find by id, or find by filter, returns array of entries |
| `.count()` | returns number of records in collection | | `.dump()` | saves records to JSON file |
#### Length (Count Records)
As `Records` are just plain JavaScript Arrays, you can use `.length` to determine the number of
results returned, for example:
```js
let cats = pets.find({"type": "cat"}); // []
cats.length; // 0
```
> NOTICE: `find` is special, changes based on what you pass in, an id, an object, or nothing at all > NOTICE: `find` is special, changes based on what you pass in, an id, an object, or nothing at all
- Additional [API Documentation](docs/api.md) - Additional [API Documentation](docs/api.md)
### Options ### Options
Records.js constructor supports a few options passed in as an `object` Records.js constructor supports a few options passed in as an `object`
- store: localStorage KEY to use. This actives localStorage if available - store: localStorage KEY to use. This actives localStorage if available
- debug: may logout useful information, maybe not;) - debug: may logout useful information, maybe not;)
## Tests ## Tests

18
dist/record.js vendored
View File

@ -1,4 +1,4 @@
/*! Record.js | MIT | https://github.com/n2geoff/record.js */ /*! Record.js v0.6.0 | MIT | https://github.com/n2geoff/record.js */
(function (root, factory) { (function (root, factory) {
"use strict"; "use strict";
if (typeof module === "object" && module.exports) { if (typeof module === "object" && module.exports) {
@ -113,10 +113,6 @@
this._save(); this._save();
} }
count() {
return this.records.length;
}
_save() { _save() {
if (this.store && localStorage) { if (this.store && localStorage) {
localStorage.setItem(this.store, JSON.stringify(this.records)); localStorage.setItem(this.store, JSON.stringify(this.records));
@ -129,7 +125,17 @@
} }
} }
dump() {} 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));
}
} }
return Record; return Record;

4
dist/record.min.js vendored
View File

@ -1,2 +1,2 @@
/*! Record.js | MIT | https://github.com/n2geoff/record.js */ /*! Record.js v0.6.0 | MIT | https://github.com/n2geoff/record.js */
(function(r,t){"use strict";"object"==typeof module&&module.exports?module.exports=t(r.Record):r.Record=t(r.Record)}(this,function(){"use strict";return class{constructor(r){if(this.store=(r||{}).store,this.debug=(r||{}).debug||!1,this.records=[],this.store&&localStorage){this._log("Initializing localStorage for "+this.store);let r=this._load()||[];this.records=[...r]}}_log(){this.debug&&console.log(...arguments)}add(r){if(Array.isArray(r)){let t=[];return r.forEach(()=>{r.id||(r.id=Math.random().toString(36).substr(2,9)),this.records.push(r),this.entries.push(r)}),this._save(),t}return r.id||(r.id=Math.random().toString(36).substr(2,9)),this.records.push(r),this._save(),r}find(r){if(!r)return this.records;if("string"==typeof r||"number"==typeof r)return this.records.filter(t=>t.id===r);let t=Object.keys(r);return this.records.filter(e=>-1!==t.indexOf("id")?e.id===r.id:t.every(t=>e[t]===r[t]))}remove(r){if(!r||Array.isArray(r))return this._log(console.error("remove() accepts a single object")),[];let t=this.find(r);return t.forEach(r=>{this.records.splice(this.records.indexOf(r),1)}),this._save(),t}clear(){this.records=[],this._save()}count(){return this.records.length}_save(){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(t,e){"use strict";"object"==typeof module&&module.exports?module.exports=e(t.Record):t.Record=e(t.Record)}(this,function(){"use strict";return class{constructor(t){if(this.store=(t||{}).store,this.debug=(t||{}).debug||!1,this.records=[],this.store&&localStorage){this._log("Initializing localStorage for "+this.store);let t=this._load()||[];this.records=[...t]}}_log(){this.debug&&console.log(...arguments)}add(t){if(Array.isArray(t)){let e=[];return t.forEach(()=>{t.id||(t.id=Math.random().toString(36).substr(2,9)),this.records.push(t),this.entries.push(t)}),this._save(),e}return t.id||(t.id=Math.random().toString(36).substr(2,9)),this.records.push(t),this._save(),t}find(t){if(!t)return this.records;if("string"==typeof t||"number"==typeof t)return this.records.filter(e=>e.id===t);let e=Object.keys(t);return this.records.filter(r=>-1!==e.indexOf("id")?r.id===t.id:e.every(e=>r[e]===t[e]))}remove(t){if(!t||Array.isArray(t))return this._log(console.error("remove() accepts a single object")),[];let e=this.find(t);return e.forEach(t=>{this.records.splice(this.records.indexOf(t),1)}),this._save(),e}clear(){this.records=[],this._save()}_save(){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(t,e){let r=document.createElement("a"),s=new Blob([e],{type:"text/plain"});r.href=URL.createObjectURL(s),r.download=t,r.click()}(`${this.store||"data"}.json`,JSON.stringify(this._load(),null,4))}}});

View File

@ -1,6 +1,6 @@
{ {
"name": "record.js", "name": "record.js",
"version": "0.5.0", "version": "0.6.0",
"description": "dead-simple storage-collection library", "description": "dead-simple storage-collection library",
"main": "src/record.js", "main": "src/record.js",
"directories": { "directories": {

View File

@ -1,4 +1,4 @@
/*! Record.js | MIT | https://github.com/n2geoff/record.js */ /*! Record.js v0.6.0 | MIT | https://github.com/n2geoff/record.js */
(function (root, factory) { (function (root, factory) {
"use strict"; "use strict";
if (typeof module === "object" && module.exports) { if (typeof module === "object" && module.exports) {
@ -21,7 +21,7 @@
* @example * @example
* // create a new record (in-memory) * // create a new record (in-memory)
* let pets = new Record(); * let pets = new Record();
* *
* @example * @example
* // create a new record (localStorage) * // create a new record (localStorage)
* let pets = new Record({"store": "pets"}); * let pets = new Record({"store": "pets"});
@ -208,19 +208,12 @@
this._save(); this._save();
} }
/**
* @returns {number} count of records in collection
*/
count() {
return this.records.length;
}
// save to localstorage // save to localstorage
/** /**
* save a record to storage if available * save a record to storage if available
* *
* @private * @private
* *
* @memberof Record * @memberof Record
*/ */
_save() { _save() {
@ -231,9 +224,9 @@
/** /**
* load records from storage if exists * load records from storage if exists
* *
* @private * @private
* *
* @returns {array} of loaded records * @returns {array} of loaded records
* @memberof Record * @memberof Record
*/ */
@ -243,7 +236,24 @@
} }
} }
dump() {} /**
* Dumps data to JSON file
*
* Uses 'store' as file name with a '.json' extension
*
* @return {object} JSON Object of records
*/
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));
}
} }
return Record; return Record;