Skip to content

Commit

Permalink
feat(sifrr-storage): migrate to es6
Browse files Browse the repository at this point in the history
  • Loading branch information
aadityataparia committed Jul 30, 2019
1 parent aca9f30 commit e86cf65
Show file tree
Hide file tree
Showing 14 changed files with 192 additions and 226 deletions.
94 changes: 53 additions & 41 deletions packages/browser/sifrr-storage/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ Browser key-value(JSON) storage library with cow powers. ~2KB alternative to [lo

| Type | Size |
| :----------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
| Normal (`dist/sifrr.storage.js`) | [![Normal](https://img.badgesize.io/sifrr/sifrr/master/packages/browser/sifrr-storage/dist/sifrr.storage.js?maxAge=600)](https://github.com/sifrr/sifrr/blob/master/packages/browser/sifrr-storage/dist/sifrr.storage.js) |
| Minified (`dist/sifrr.storage.min.js`) | [![Minified](https://img.badgesize.io/sifrr/sifrr/master/packages/browser/sifrr-storage/dist/sifrr.storage.min.js?maxAge=600)](https://github.com/sifrr/sifrr/blob/master/packages/browser/sifrr-storage/dist/sifrr.storage.min.js) |
| Normal (`dist/sifrr.storage.js`) | [![Normal](https://img.badgesize.io/sifrr/sifrr/master/packages/browser/sifrr-storage/dist/sifrr.storage.js?maxAge=600)](https://github.com/sifrr/sifrr/blob/master/packages/browser/sifrr-storage/dist/sifrr.storage.js) |
| Minified (`dist/sifrr.storage.min.js`) | [![Minified](https://img.badgesize.io/sifrr/sifrr/master/packages/browser/sifrr-storage/dist/sifrr.storage.min.js?maxAge=600)](https://github.com/sifrr/sifrr/blob/master/packages/browser/sifrr-storage/dist/sifrr.storage.min.js) |
| Minified + Gzipped (`dist/sifrr.storage.min.js`) | [![Minified + Gzipped](https://img.badgesize.io/sifrr/sifrr/master/packages/browser/sifrr-storage/dist/sifrr.storage.min.js?compression=gzip&maxAge=600)](https://github.com/sifrr/sifrr/blob/master/packages/browser/sifrr-storage/dist/sifrr.storage.min.js) |

## Types of storages available (in default priority order)

- IndexedDB (Persisted - on page refresh or open/close)
- WebSQL (Persisted - on page refresh or open/close)
- LocalStorage (Persisted - on page refresh or open/close)
- Cookies (Persisted - on page refresh or open/close), Sent to server with every request
- JsonStorage (In memory - deleted on page refresh or open/close)
- IndexedDB (Persisted - on page refresh or open/close)
- WebSQL (Persisted - on page refresh or open/close)
- LocalStorage (Persisted - on page refresh or open/close)
- Cookies (Persisted - on page refresh or open/close), Sent to server with every request
- JsonStorage (In memory - deleted on page refresh or open/close)

## How to use

Expand Down Expand Up @@ -57,6 +57,10 @@ const Storage = require('@sifrr/storage');
```js
import Storage from '@sifrr/storage';
// use Storage instead of Sifrr.Storage in examples if you are using this

// or
// if you want to use one type of store without support checking based on priority
import { IndexedDB, WebSQL, LocalStorage, Cookies, JsonStorage } from '@sifrr/storage';
```

## API
Expand All @@ -65,17 +69,17 @@ Sifrr.Storage uses Promises.

### Initialization

- Initialize a storage with a type
- Initialize a storage with a type

```js
let storage = new Sifrr.Storage(type)
let storage = new Sifrr.Storage(type);
```

where type is one of `indexeddb`, `websql`, `localstorage`, `cookies`, `jsonstorage`.

_Note_: If that type is not supported in the browser, then first supported storage will be selected based on priority order.

- Initialize with options
- Initialize with options

```js
// Options with default values
Expand All @@ -85,8 +89,8 @@ let options = {
version: 1, // version number (integer / float / string), 1 is treated same as '1'
desciption: 'Sifrr Storage', // description (text)
size: 5 * 1024 * 1024 // Max db size in bytes only for websql (integer)
}
storage = new Sifrr.Storage(options)
};
storage = new Sifrr.Storage(options);
```

**Initializing with same priority, name and version will give same instance.**
Expand All @@ -105,11 +109,15 @@ storage.version; // version number
// insert single key-value
let key = 'key';
let value = { value: 'value' };
storage.set(key, value).then(() => {/* Do something here */});
storage.set(key, value).then(() => {
/* Do something here */
});

// insert multiple key-values
let data = { a: 'b', c: { d: 'e' } }
storage.set(data).then(() => {/* Do something here */});
let data = { a: 'b', c: { d: 'e' } };
storage.set(data).then(() => {
/* Do something here */
});
```

**Note** Cookies are trucated after ~628 characters in chrome (total of key + value characters), other browsers may tructae at other values as well. Use cookies for small data only
Expand All @@ -124,20 +132,24 @@ storage.store = `key=value; expires=...; path=/`;

```js
// get single key-value
storage.get('key').then((value) => console.log(value)); // > { key: { value: 'value' } }
storage.get('key').then(value => console.log(value)); // > { key: { value: 'value' } }

// get multiple key-values
storage.get(['a', 'c']).then((value) => console.log(value)); // > { a: 'b', c: { d: 'e' } }
storage.get(['a', 'c']).then(value => console.log(value)); // > { a: 'b', c: { d: 'e' } }
```

### Deleting a key

```js
// delete single key-value
storage.del('key').then(() => {/* Do something here */});
storage.del('key').then(() => {
/* Do something here */
});

// delete multiple key-values
storage.del(['a', 'c']).then(() => {/* Do something here */});
storage.del(['a', 'c']).then(() => {
/* Do something here */
});
```

### Updating a key
Expand All @@ -147,21 +159,21 @@ storage.del(['a', 'c']).then(() => {/* Do something here */});
### Get all data in table

```js
storage.all().then((data) => console.log(data)); // > { key: { value: 'value' }, a: 'b', c: { d: 'e' } }
storage.all().then(data => console.log(data)); // > { key: { value: 'value' }, a: 'b', c: { d: 'e' } }
```

### Get all keys in table

```js
storage.keys().then((keys) => console.log(keys)); // > ['key', 'a', 'c']
storage.keys().then(keys => console.log(keys)); // > ['key', 'a', 'c']
```

### Clear table

```js
storage.clear().then(() => {
// checking if data is deleted
storage.all().then((data) => console.log(data)); // > {}
storage.all().then(data => console.log(data)); // > {}
});
```

Expand All @@ -181,25 +193,25 @@ should be `string`

can be any of these types:

- `Array`,
- `ArrayBuffer`,
- `Blob`,
- `Float32Array`,
- `Float64Array`,
- `Int8Array`,
- `Int16Array`,
- `Int32Array`,
- `Number`,
- `Object`,
- `Uint8Array`,
- `Uint16Array`,
- `Uint32Array`,
- `Uint8ClampedArray`,
- `String`
- `Array`,
- `ArrayBuffer`,
- `Blob`,
- `Float32Array`,
- `Float64Array`,
- `Int8Array`,
- `Int16Array`,
- `Int32Array`,
- `Number`,
- `Object`,
- `Uint8Array`,
- `Uint16Array`,
- `Uint32Array`,
- `Uint8ClampedArray`,
- `String`

### Gotchas

- When using localStorage, websql or cookies, binary data will be serialized before being saved (and retrieved). This serialization will incur a size increase when binary data is saved, and might affect performance.
- Since object[key] is `undefined` when key is not present in the object, `undefined` is not supported as a value.
- `null` value has buggy behaviour in localstorage, as it returns `null` when value is not present.
- If you want to save falsy values, you can save `false` or `0` which are supported by all storages.
- When using localStorage, websql or cookies, binary data will be serialized before being saved (and retrieved). This serialization will incur a size increase when binary data is saved, and might affect performance.
- Since object[key] is `undefined` when key is not present in the object, `undefined` is not supported as a value.
- `null` value has buggy behaviour in localstorage, as it returns `null` when value is not present.
- If you want to save falsy values, you can save `false` or `0` which are supported by all storages.
63 changes: 20 additions & 43 deletions packages/browser/sifrr-storage/src/sifrr.storage.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
const storages = require('./storages');
const JsonStorage = require('./storages/jsonstorage');
import IndexedDB from './storages/indexeddb';
import WebSQL from './storages/websql';
import LocalStorage from './storages/localstorage';
import Cookies from './storages/cookies';
import JsonStorage from './storages/jsonstorage';

let storages = {};
storages[IndexedDB.type] = IndexedDB;
storages[WebSQL.type] = WebSQL;
storages[LocalStorage.type] = LocalStorage;
storages[Cookies.type] = Cookies;
storages[JsonStorage.type] = JsonStorage;

class SifrrStorage {
constructor(options) {
if (typeof options === 'string') options = { priority: [options] };
else options = options || {};
this._options = Object.assign(this.constructor.defaultOptions, options);
options.priority = options.priority || [];

this._options = options;
return this.storage;
}

get storage() {
let storage = this.supportedStore();
const storage = this.supportedStore();
if (typeof storage === 'undefined')
throw Error('No available storage supported in this browser');
let matchingInstance = this.constructor._matchingInstance(this._options, storage.type);
if (matchingInstance) {
return matchingInstance;
} else {
let storageInstance = new storage(this._options);
this.constructor._add(storageInstance);
return storageInstance;
}
return new storage(this._options);
}

get priority() {
Expand All @@ -35,41 +40,13 @@ class SifrrStorage {

supportedStore() {
for (let i = 0; i < this.priority.length; i++) {
let store = this.constructor.availableStores[this.priority[i]];
let store = storages[this.priority[i]];
if (store && new store(this._options).isSupported()) return store;
}
}

static _matchingInstance(options, type) {
let allInstances = this.all,
i;
let length = allInstances.length;
for (i = 0; i < length; i++) {
if (allInstances[i]._isEqual(options, type)) return allInstances[i];
}
return false;
}

static _add(instance) {
this.all.push(instance);
}

static get defaultOptions() {
return {
priority: [],
name: 'SifrrStorage',
version: 1,
description: 'Sifrr Storage',
size: 5 * 1024 * 1024
};
}

static json(data) {
return new JsonStorage({}, data);
}
}

SifrrStorage.availableStores = storages;
SifrrStorage.all = [];

module.exports = SifrrStorage;
export { IndexedDB, WebSQL, LocalStorage, Cookies, JsonStorage };
export default SifrrStorage;
14 changes: 0 additions & 14 deletions packages/browser/sifrr-storage/src/storages.js

This file was deleted.

5 changes: 3 additions & 2 deletions packages/browser/sifrr-storage/src/storages/cookies.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const Storage = require('./storage');
import Storage from './storage';
const date = new Date(0).toUTCString();
const equal = '%3D',
equalRegex = new RegExp(equal, 'g');

class Cookies extends Storage {
constructor(options) {
super(options);
return this.constructor._matchingInstance(this);
}

_parsedData() {
Expand Down Expand Up @@ -53,4 +54,4 @@ class Cookies extends Storage {
}
}

module.exports = Cookies;
export default Cookies;
5 changes: 3 additions & 2 deletions packages/browser/sifrr-storage/src/storages/indexeddb.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const Storage = require('./storage');
import Storage from './storage';

class IndexedDB extends Storage {
constructor(options) {
super(options);
return this.constructor._matchingInstance(this);
}

_parsedData() {
Expand Down Expand Up @@ -66,4 +67,4 @@ class IndexedDB extends Storage {
}
}

module.exports = IndexedDB;
export default IndexedDB;
18 changes: 13 additions & 5 deletions packages/browser/sifrr-storage/src/storages/jsonstorage.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
const Storage = require('./storage');
import Storage from './storage';

class JsonStorage extends Storage {
constructor(options, data = {}) {
constructor(options) {
super(options);
this.table = Storage.parse(data);
return this.constructor._matchingInstance(this);
}

_parsedData() {
return this.table;
}

get table() {
return this._table || {};
}

set table(v) {
this._table = v;
}

get store() {
return this.table;
return true;
}

static get type() {
return 'jsonstorage';
}
}

module.exports = JsonStorage;
export default JsonStorage;
5 changes: 3 additions & 2 deletions packages/browser/sifrr-storage/src/storages/localstorage.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const Storage = require('./storage');
import Storage from './storage';

class LocalStorage extends Storage {
constructor(options) {
super(options);
return this.constructor._matchingInstance(this);
}

_parsedData() {
Expand Down Expand Up @@ -51,4 +52,4 @@ class LocalStorage extends Storage {
}
}

module.exports = LocalStorage;
export default LocalStorage;

0 comments on commit e86cf65

Please sign in to comment.