Skip to content

Commit 0c5e769

Browse files
committed
Refactored cookie-storage
1 parent 3a9f4b9 commit 0c5e769

16 files changed

+562
-479
lines changed

.eslintrc.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,10 @@
4343
"one-var": [2, {
4444
"uninitialized": "always"
4545
}],
46+
"one-var-declaration-per-line": [2, "initializations"],
4647
"max-len": 0,
4748
"no-param-reassign": 0,
49+
"no-use-before-define": 0,
4850
"no-underscore-dangle": 0,
4951
"object-curly-spacing": [2, "never"],
5052
"import/no-mutable-exports": 1,

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@
22

33
<!-- markdownlint-disable MD024 MD033 -->
44

5+
## 2.3.0
6+
7+
### Improvements
8+
9+
1. Upgraded to Webpack 3, ESLint 4.
10+
1. Refactored and decoupled inner modules.
11+
512
## 2.2.0
613

714
### Improvements

README.md

Lines changed: 66 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,26 @@
33
<!-- markdownlint-disable MD014 MD025 MD033 MD034 MD036 -->
44

55
This library manages an adapter that implements an interface similar to
6-
[Web Storage] to normalize the API for [document.cookie],
6+
[Web Storage] to normalize the API for [document.cookie] to be as
77
[window.localStorage] and [window.sessionStorage].
88

99
One of the advantages of this library is that the adapter stores the data
1010
as **JSON**, allowing to save `Object` and `Array<Any>` values, which
1111
is not the default behavior when using the native `window.localStorage`,
1212
`window.sessionStorage` or `document.cookie` storages.
1313

14-
It also provides a new [`memoryStorage`](#storage-or-default) mechanism that
15-
persists the data in memory (current browser tab), even if a forced refresh
16-
is done on the page. It is a mimic of `sessionStorage` and it could be used
17-
as fallback when the other storage mechanisms are not available, for example,
18-
some browsers navigating in private mode.
14+
It also provides a new mechanism -- [`memoryStorage`](#storage-or-default),
15+
that persists the data in memory (for current browser-tab), even if a forced
16+
refresh is done on the page. It is a mimic of `sessionStorage` and it could
17+
be used as fallback when the other storage mechanisms are not available, for
18+
example, some browsers navigating in private mode.
1919
Read more about [window.sessionStorage].
2020

2121
Another advantage with **proxy-storage** is that you can register
22-
[interceptors](#interceptors) as callback functions on the
23-
[WebStorage](#webstorage) prototype methods: `setItem`, `getItem`,
24-
`removeItem`, and `clear`, giving you the ability to intercept and
25-
modify the values to read, write, or delete.
22+
[interceptors](#interceptors) as functions for the prototype methods of
23+
[WebStorage](#webstorage) class: `setItem`, `getItem`, `removeItem`, and
24+
`clear`, giving you the ability to intercept and modify the values to read,
25+
write, or delete.
2626

2727
## Content
2828

@@ -40,7 +40,7 @@ modify the values to read, write, or delete.
4040

4141
## Installing the library
4242

43-
To include this library into your package manager with `npm` or `yarn`
43+
To include this library into your package manager with `npm` or `yarn`, run:
4444

4545
```shell
4646
# with npm
@@ -59,7 +59,7 @@ $ yarn add proxy-storage
5959
<script src="https://unpkg.com/proxy-storage/dist/proxy-storage.min.js"></script>
6060

6161
<!-- or from rawgit.com -->
62-
<script src="https://cdn.rawgit.com/jherax/proxy-storage/2.2.0/dist/proxy-storage.min.js"></script>
62+
<script src="https://cdn.rawgit.com/jherax/proxy-storage/2.3.0/dist/proxy-storage.min.js"></script>
6363
```
6464

6565
In the above case, [`proxyStorage`](#api) is included as a global object
@@ -98,7 +98,7 @@ import storage from 'proxy-storage';
9898

9999
// or get some API members
100100
import storage, { WebStorage, configStorage } from 'proxy-storage';
101-
const cookieStore = new WebStorage('memoryStorage');
101+
const cookieStore = new WebStorage('cookieStorage');
102102
```
103103

104104
### AMD
@@ -119,7 +119,7 @@ require(['proxy-storage'], function(proxyStorage) {
119119
});
120120
```
121121

122-
See an example with RequireJS here: http://jsfiddle.net/FdKTn/71/
122+
See an example with RequireJS here: http://jsfiddle.net/FdKTn/77/
123123

124124
[&#9751; Back to Index](#content)
125125

@@ -131,7 +131,7 @@ as **JSON**, allowing to save and retrieve **primitive**,
131131

132132
It also provides a new storage mechanism called **`memoryStorage`**
133133
which persists the data in memory (current tab in the browser), even
134-
if a forced refresh is done (similar to `sessionStorage`).
134+
if a forced refresh is done on the page, as `sessionStorage` does.
135135

136136
The [`WebStorage`](#webstorage) class has a static member called
137137
[`interceptors`](#interceptors) which lets you to register callback
@@ -158,7 +158,7 @@ the prototype:
158158
<br>The `options` parameter is used only with instances of `cookieStorage`.
159159
Read more details [here](#handling-cookies).
160160
- **`clear`**`()`: removes all items from the storage instance.
161-
- **`length`**: gets the number of items stored in the storage instance.
161+
- **`length`**: gets the number of items stored in the instance.
162162

163163
The `storage` object is a proxy for the first storage mechanism available,
164164
usually `localStorage`, which is established when the library is initialized.
@@ -173,22 +173,22 @@ The availability of the storage mechanisms is determined in the following order:
173173
of `memoryStorage` is similar to `sessionStorage`, which let you to persist
174174
data in the current session (browser tab)
175175

176-
As the `storage` object is a proxy of the first storage mechanism available,
177-
that means if `localStorage` is available to set and retreive data, it will be
178-
used, otherwise, if `localStorage` is not available, then it will try to use
179-
`cookieStorage`, and finally if none of the above are available, then the
180-
`storage` object will handle the `memoryStorage` as fallback.
176+
**Important**: As the `storage` object is a proxy for the first storage
177+
mechanism available, that means if `localStorage` is available to read and
178+
write data, it will be used, otherwise, if `localStorage` is not available,
179+
then `cookieStorage` will be used, and finally if none of the above are
180+
available, `memoryStorage` will be the fallback mechanism.
181181

182182
**Example**
183183

184184
```javascript
185185
import storage from 'proxy-storage';
186-
// 'storage' is the default module
186+
// for browser: storage = proxyStorage.default;
187187

188188
// use the default storage mechanism, usually localStorage
189-
storage.setItem('qwerty', [{ some: 'object', garbage: true }]);
189+
storage.setItem('qwerty', [{ garbage: true, some: 'object' }]);
190190
console.log(storage.getItem('qwerty'));
191-
// [{ some: 'object', garbage: true }]
191+
// [{ garbage: true, some: 'object' }]
192192

193193
storage.setItem('persisted', true);
194194
storage.setItem('o-really', { status: 'saved' });
@@ -201,8 +201,7 @@ console.log(storage.getItem('qwerty'));
201201
// removes all data in the current storage
202202
storage.clear();
203203
console.log(`items: ${storage.length}`);
204-
console.log(storage.getItem('o-really'));
205-
// null
204+
// items: 0
206205
```
207206

208207
**ProTip**: you can override the default storage mechanism by calling
@@ -243,14 +242,17 @@ Each instance inherits the following properties:
243242
<br>The `options` parameter is used only with instances of `cookieStorage`.
244243
Read more details [here](#handling-cookies).
245244
- **`clear`**`()`: removes all items from the storage instance.
246-
- **`length`**: gets the number of items stored in the storage instance.
245+
- **`length`**: gets the number of items stored in the instance.
247246

248247
You can create multiple instances of `WebStorage` to handle different
249248
storage mechanisms. For example, to store data in `cookies` and also in
250249
`sessionStorage`, you can do as follow:
251250

252251
```javascript
253252
import storage, { WebStorage } from 'proxy-storage';
253+
// for browser:
254+
// var storage = proxyStorage.default;
255+
// var WebStorage = proxyStorage.WebStorage;
254256

255257
// use the default storage mechanism, usually localStorage
256258
storage.setItem('tv-show', { name: 'Regular Show' });
@@ -265,13 +267,16 @@ const cookieStore = new WebStorage('cookieStorage');
265267
cookieStore.setItem('character', { name: 'Rigby' }, options);
266268
```
267269

268-
**Important**: If you request an instance of a storage mechanism that are not
270+
**Important**: If you request an instance of a storage mechanism that is not
269271
available, you will get an instance of the first storage mechanism available,
270-
this is in order to keep storing data. It is useful when you rely on a
272+
so you can continue storing data. It is useful when you rely on a
271273
specific storage mechanism. Let's see an example:
272274

273275
```javascript
274276
import { WebStorage, isAvailable } from 'proxy-storage';
277+
// for browser:
278+
// var WebStorage = proxyStorage.WebStorage;
279+
// var isAvailable = proxyStorage.isAvailable;
275280

276281
// let's suppose the following storage is not available
277282
isAvailable.sessionStorage = false;
@@ -280,8 +285,8 @@ import { WebStorage, isAvailable } from 'proxy-storage';
280285
// sessionStorage is not available. Falling back to memoryStorage
281286
sessionStore.setItem('ulugrun', 3.1415926);
282287

283-
// as sessionStorage is not available, the instance obtained
284-
// is the first storage mechanism available: memoryStorage
288+
// as sessionStorage is not available, the instance
289+
// obtained is the fallback mechanism: memoryStorage
285290
console.dir(sessionStore);
286291
```
287292

@@ -290,8 +295,8 @@ import { WebStorage, isAvailable } from 'proxy-storage';
290295
### Handling cookies
291296

292297
When you create an instance of `WebStorage` with `cookieStorage`, the
293-
method `setItem()` receives an optional argument as the last parameter,
294-
it configures the way how the cookie is stored.
298+
method `setItem()` receives an optional argument as the last parameter
299+
that configures the way how the cookie is stored.
295300

296301
Signature of `setItem`:
297302

@@ -303,7 +308,7 @@ Where the **`options`** parameter is an `object` with the following properties:
303308

304309
- `domain`_`{string}`_: the domain or subdomain where the cookie will be valid.
305310
- `path`_`{string}`_: relative path where the cookie is valid. _Default `"/"`_
306-
- `secure`_`{boolean}`_: if provided, creates a secure cookie, over HTTPS.
311+
- `secure`_`{boolean}`_: if provided, creates a secure cookie over HTTPS.
307312
- `expires`_`{Date, object}`_: the cookie expiration date.
308313
You can pass an object describing the expiration:
309314
- `date`_`{Date}`_: if provided, this date will be applied, otherwise the
@@ -318,6 +323,7 @@ Where the **`options`** parameter is an `object` with the following properties:
318323

319324
```javascript
320325
import { WebStorage } from 'proxy-storage';
326+
// for browser: WebStorage = proxyStorage.WebStorage;
321327

322328
const cookieStore = new WebStorage('cookieStorage');
323329

@@ -357,12 +363,11 @@ when calling `setItem(key, value, options)` or `removeItem(key, options)`.
357363

358364
If you have created the cookie with **proxyStorage**, it will handle the
359365
metadata internally, so that you can call `removeItem(key)` with no more
360-
arguments.
366+
arguments. Otherwise you will need to provide the metadata **`path`** or
367+
**`domain`**:
361368

362369
![cookies](https://www.dropbox.com/s/wlvgm0t8xc07me1/cookies-metadata.gif?dl=1)
363370

364-
Otherwise you need to provide the metadata `path` or `domain` as mentioned before:
365-
366371
```javascript
367372
// change the value of an external cookie in /answers
368373
cookieStore.setItem('landedAnswers', 999, {
@@ -397,7 +402,7 @@ Object.keys(sessionStore).forEach((key) => {
397402
console.log(key, sessionStore[key]);
398403
});
399404

400-
// or this way (not recommended) ...
405+
// or this way (not recommended either)
401406
for (let key in sessionStore) {
402407
console.log(key, sessionStore[key]);
403408
}
@@ -406,12 +411,12 @@ for (let key in sessionStore) {
406411
It is also applied not only when reading, but also when writing to storage:
407412

408413
```javascript
409-
// not recommended: not synchronized
414+
// not recommended: not synchronized with the real storage
410415
var title = cookieStorage['title'];
411416
var session = cookieStorage.sessionId;
412417
cookieStorage['sessionId'] = 'E6URTG5';
413418

414-
// good practice: sync external changes
419+
// good practice: it is synchronized for external changes
415420
var title = cookieStorage.getItem('title');
416421
var session = cookieStorage.getItem('sessionId');
417422
cookieStorage.setItem('sessionId', 'E6URTG5');
@@ -427,6 +432,7 @@ in the storage instance, e.g.
427432

428433
```javascript
429434
import { WebStorage } from 'proxy-storage';
435+
// for browser: WebStorage = proxyStorage.WebStorage;
430436

431437
function clearAllStorages() {
432438
new WebStorage('localStorage').clear();
@@ -435,6 +441,13 @@ function clearAllStorages() {
435441
}
436442
```
437443

444+
**Important**: When handling `cookieStorage`, the method `clear()` only will
445+
remove the cookies with no metadata or those created through **proxyStorage**.
446+
Take into account that if you want to remove a cookie that was created from
447+
another page, you need to set the `domain` or `path` attributes in the
448+
`options` parameter when calling `removeItem(key, options)`.<br>
449+
See [handling-cookies](#handling-cookies).
450+
438451
[&#9751; Back to Index](#content)
439452

440453
### Interceptors
@@ -456,6 +469,9 @@ the _value_ passed and returned in each callback.
456469

457470
```javascript
458471
import storage, { WebStorage } from 'proxy-storage';
472+
// for browser:
473+
// var storage = proxyStorage.default;
474+
// var WebStorage = proxyStorage.WebStorage;
459475

460476
// adds first interceptor for 'setItem'
461477
WebStorage.interceptors('setItem', (key, value/*, options*/) => {
@@ -500,11 +516,11 @@ console.log(data);
500516

501517
**_@type_ `Object`**
502518

503-
Gets and sets the storage mechanism to use by default.
504-
It contains the following methods:
519+
Sets the [default storage](##storage-or-default) mechanism, or get the current
520+
default storage mechanism. This object contains the following methods:
505521

506522
- **`get`**`()`: returns a `string` with the name of the current storage mechanism.
507-
- **`set`**`(storageType)`: sets the current storage mechanism. `storageType`
523+
- **`set`**`(storageType)`: sets the default storage mechanism. `storageType`
508524
must be one of the following strings: `"localStorage"`, `"sessionStorage"`,
509525
`"cookieStorage"`, or `"memoryStorage"`. If the storage type provided is
510526
not valid, it will throw an exception.
@@ -513,6 +529,9 @@ It contains the following methods:
513529

514530
```javascript
515531
import storage, { configStorage } from 'proxy-storage';
532+
// for browser:
533+
// var storage = proxyStorage.default;
534+
// var configStorage = proxyStorage.configStorage;
516535

517536
// gets the default storage mechanism
518537
let storageName = configStorage.get();
@@ -537,12 +556,13 @@ storage.setItem('currentStorage', storageName);
537556

538557
**_@type_ `Object`**
539558

540-
Determines which storage mechanisms are available to read, write, or delete.
559+
Determines which storage mechanisms are available to _read, write,_
560+
or _delete_ data.
541561

542562
It contains the following flags:
543563

544564
- **`localStorage`**: is set to `true` if the local storage is available.
545-
- **`cookieStorage`**: is set to `true` if the cookie storage is available.
565+
- **`cookieStorage`**: is set to `true` if the document cookies are available.
546566
- **`sessionStorage`**: is set to `true` if the session storage is available.
547567
- **`memoryStorage`**: always is set to `true`.
548568

@@ -648,9 +668,9 @@ repository. See [LICENSE](LICENSE) file for more information.
648668
<!-- LINKS -->
649669

650670
[Web Storage]: https://developer.mozilla.org/en-US/docs/Web/API/Storage
671+
[document.cookie]: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
651672
[window.localStorage]: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
652673
[window.sessionStorage]: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
653-
[document.cookie]: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
654674
[UMD]: http://davidbcalhoun.com/2014/what-is-amd-commonjs-and-umd/
655675
[CommonJS]: https://blog.risingstack.com/node-js-at-scale-module-system-commonjs-require/
656676
[ES2015 Export]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

0 commit comments

Comments
 (0)