New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

natty-storage

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

natty-storage - npm Package Compare versions

Comparing version 1.0.0-rc4 to 1.0.0-rc5

49

dist/natty-storage.js

@@ -5,7 +5,7 @@ (function webpackUniversalModuleDefinition(root, factory) {

else if(typeof define === 'function' && define.amd)
define("NattyStorage", [], factory);
define("nattyStorage", [], factory);
else if(typeof exports === 'object')
exports["NattyStorage"] = factory();
exports["nattyStorage"] = factory();
else
root["NattyStorage"] = factory();
root["nattyStorage"] = factory();
})(this, function() {

@@ -86,3 +86,3 @@ return /******/ (function(modules) { // webpackBootstrap

var VERSION = undefined;
(VERSION = "1.0.0-rc4");
(VERSION = "1.0.0-rc5");

@@ -126,3 +126,3 @@ var support = {

/**
* let ls = new NattyStorage({
* let ls = new nattyStorage({
* type: 'localstorage', // sessionstorage, variable

@@ -135,3 +135,3 @@ * key: 'city',

var NattyStorage = (function () {
var Storage = (function () {
/**

@@ -142,6 +142,6 @@ * 构造函数

function NattyStorage() {
function Storage() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
_classCallCheck(this, NattyStorage);
_classCallCheck(this, Storage);

@@ -152,4 +152,5 @@ var t = this;

// 必须配置`key`!!! 无论什么类型!!!
if (!t.config.key) {
throw new Error('`key` is missing, please check the options passed in `NattyStorage` constructor.');
throw new Error('`key` is missing, please check the options passed in `nattyStorage` constructor.');
}

@@ -159,4 +160,4 @@

t._CHECK_KEY = 'NattyStorageCheck:' + t.config.key;
t._DATA_KEY = 'NattyStorageData:' + t.config.key;
t._CHECK_KEY = 'nattyStorageCheck:' + t.config.key;
t._DATA_KEY = 'nattyStorageData:' + t.config.key;
t._placeholderUsed = FALSE;

@@ -174,3 +175,3 @@

_createClass(NattyStorage, [{
_createClass(Storage, [{
key: '_lazyInit',

@@ -397,11 +398,13 @@ value: function _lazyInit() {

return NattyStorage;
return Storage;
})();
NattyStorage.version = VERSION;
NattyStorage.support = {};
NattyStorage.support.localStorage = support.localStorage;
NattyStorage.support.sessionStorage = support.sessionStorage;
NattyStorage._variable = {};
var nattyStorage = function nattyStorage(options) {
return new Storage(options);
};
nattyStorage.version = VERSION;
nattyStorage._variable = variable;
nattyStorage.support = support;
/**

@@ -411,3 +414,3 @@ * 执行全局配置

*/
NattyStorage.setGlobal = function (options) {
nattyStorage.setGlobal = function (options) {
runtimeGlobalConfig = extend({}, defaultGlobalConfig, options);

@@ -422,3 +425,3 @@ return undefined;

*/
NattyStorage.getGlobal = function (property) {
nattyStorage.getGlobal = function (property) {
return property ? runtimeGlobalConfig[property] : runtimeGlobalConfig;

@@ -428,3 +431,2 @@ };

function createStorage(storage) {
// TODO 降级到variable模式
storage = win[storage];

@@ -454,4 +456,5 @@ return {

var variable = {};
function createVariable() {
var storage = NattyStorage._variable;
var storage = variable;
return {

@@ -577,3 +580,3 @@ set: function set(key, value) {

module.exports = NattyStorage;
module.exports = nattyStorage;

@@ -580,0 +583,0 @@ /***/ },

@@ -1,1 +0,1 @@

!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("NattyStorage",[],e):"object"==typeof exports?exports.NattyStorage=e():t.NattyStorage=e()}(this,function(){return function(t){function e(n){if(r[n])return r[n].exports;var a=r[n]={exports:{},id:n,loaded:!1};return t[n].call(a.exports,a,a.exports,e),a.loaded=!0,a.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";t.exports=r(1)},function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t){var e={x:"x"},r="natty-storage-test",n=o(t);n.set(r,e);var a=JSON.stringify(n.get(r))===JSON.stringify(e);return n.remove(r),a}function o(t){return t=y[t],{set:function(e,r){t.setItem(e,JSON.stringify(r))},get:function(e){var r=t.getItem(e);if(!r)return m;try{r=JSON.parse(r)}catch(n){}return r},remove:function(e){t.removeItem(e)}}}function i(){var t=K._variable;return{set:function(e,r){t[e]=r},get:function(e){return e in t?t[e]:m},remove:function(e){delete t[e]}}}function c(t){return t.split(w).reverse().join(w)}function s(t){var e;if(-1===t.indexOf("\\."))e=t.split(".");else{e=c(t).split(/\.(?!\\)/).reverse();for(var r=0,n=e.length;n>r;r++)e[r]=c(e[r].replace(/\.\\/g,"."))}return e}function u(t,e,r){for(var n=s(t),a=r;n.length;){var o=n.shift();if(n.length)a[o]=a[o]||{},a=a[o];else{if(!p(a))throw new Error("Cannot create property `"+o+"` on non-object value, path:`"+t+"`");a[o]=e}}return r}function f(t,e,r){if(r=r||!1,r===!0||-1===t.indexOf("."))return e[t];for(var n=s(t);n.length;){var a=n.shift();if(e=f(a,e,!0),"object"!=typeof e||void 0===e){n.length&&(e=void 0);break}}return e}function l(t,e,r){if(r=r||-1===t.indexOf("."))return e.hasOwnProperty(t);for(var n=s(t);n.length;){var a=n.shift(),o=e.hasOwnProperty(a);if(!o||!n.length)return o;if(e=f(a,e,!0),!p(e))return b}}function d(t,e){for(var r=s(t),n=e;r.length;){var a=r.shift();r.length?(n[a]=n[a]||{},n=n[a]):delete n[a]}return e}function _(t){var e=S;for(var r in t){e=b;break}return e}var g=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}(),h=r(2),v=h.extend,p=h.isPlainObject,y=window,k="undefined"!=typeof y,m=null,w="",S=!0,b=!S,O="_placeholder",x=void 0;x="1.0.0-rc4";var D={localStorage:k&&!!y.localStorage&&a("localStorage"),sessionStorage:k&&!!y.sessionStorage&&a("sessionStorage")},E={type:"localStorage",key:w,tag:w,duration:0,until:0},A=v({},E),K=function(){function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];n(this,t);var r=this;if(r.config=v({},A,e),!r.config.key)throw new Error("`key` is missing, please check the options passed in `NattyStorage` constructor.");r._storage=D[r.config.type]?o(r.config.type):i(),r._CHECK_KEY="NattyStorageCheck:"+r.config.key,r._DATA_KEY="NattyStorageData:"+r.config.key,r._placeholderUsed=b,r._createStamp=+new Date}return g(t,[{key:"_lazyInit",value:function(){var t=this;t._checkData=t._storage.get(t._CHECK_KEY),t._isNew=t._checkData===m,t._isNew||t.isOutdated()?t._storage.set(t._DATA_KEY,t._data={}):(t._data=t._storage.get(t._DATA_KEY),t._data===m&&t._storage.set(t._DATA_KEY,t._data={})),t._storage.set(t._CHECK_KEY,t._checkData={tag:t.config.tag,lastUpdate:t._createStamp,duration:t.config.duration,until:t.config.until})}},{key:"isOutdated",value:function(){var t=this;if(t.config.tag&&t.config.tag!==t._checkData.tag)return S;var e=+new Date;return t._checkData.duration&&e-t._checkData.lastUpdate>t._checkData.duration?S:t._checkData.until&&e>t._checkData.until?S:b}},{key:"set",value:function(t,e){var r=this,n=arguments.length;return new Promise(function(a,o){try{r._data||r._lazyInit(),1===n?p(t)?r._data=t:(r._data[O]=t,r._placeholderUsed=S):u(t,e,r._data),r._storage.set(r._DATA_KEY,r._data),a()}catch(i){o(i)}})}},{key:"get",value:function(t){var e=this;return new Promise(function(r,n){try{var a=void 0;e._data||e._lazyInit(),a=t?f(t,e._data):e._placeholderUsed?e._data[O]:e._data,r(a)}catch(o){n(o)}})}},{key:"has",value:function(t){var e=this;return new Promise(function(r,n){try{if(e._data||e._lazyInit(),e._placeholderUsed||_(e._data))r(e._data.hasOwnProperty(O)?{has:!0,value:e._data[O]}:{});else{if(!t)throw new Error("a `path` argument should be passed into the `has` method");r(l(t,e._data)?{has:!0,value:f(t,e._data)}:{})}}catch(a){n(a)}})}},{key:"remove",value:function(t){var e=this;return new Promise(function(r,n){try{e._data||e._lazyInit(),t?(d(t,e._data),e._storage.set(e._DATA_KEY,e._data)):e.set({}),r()}catch(a){n(a)}})}},{key:"destroy",value:function(){var t=this;t._storage.remove(t._CHECK_KEY),t._storage.remove(t._DATA_KEY)}},{key:"dump",value:function(){JSON&&console&&console.log(JSON.stringify(this._data,m,4))}}]),t}();K.version=x,K.support={},K.support.localStorage=D.localStorage,K.support.sessionStorage=D.sessionStorage,K._variable={},K.setGlobal=function(t){A=v({},E,t)},K.getGlobal=function(t){return t?A[t]:A},t.exports=K},function(t,e,r){"use strict";var n=null,a=function(t){return function(){for(var e=arguments,r=t(e[0],e[1]),n=2,a=e.length;a>n;n++)r=t(r,e[n]);return r}},o="object",i=function(t){return typeof t===o},c=function(t){return t!==n&&t===t.window},s=function(t){return t!==n&&i(t)&&!c(t)&&Object.getPrototypeOf(t)===Object.prototype},u=Array.isArray,f=function l(){var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];for(var r in e)e.hasOwnProperty(r)&&void 0!==e[r]&&(u(e[r])?t[r]=[].concat(e[r]):s(e[r])?t[r]=l({},e[r]):t[r]=e[r]);return t};t.exports={extend:a(f),isPlainObject:s}}])});
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("nattyStorage",[],e):"object"==typeof exports?exports.nattyStorage=e():t.nattyStorage=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var a=n[r]={exports:{},id:r,loaded:!1};return t[r].call(a.exports,a,a.exports,e),a.loaded=!0,a.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){"use strict";t.exports=n(1)},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t){var e={x:"x"},n="natty-storage-test",r=o(t);r.set(n,e);var a=JSON.stringify(r.get(n))===JSON.stringify(e);return r.remove(n),a}function o(t){return t=y[t],{set:function(e,n){t.setItem(e,JSON.stringify(n))},get:function(e){var n=t.getItem(e);if(!n)return w;try{n=JSON.parse(n)}catch(r){}return n},remove:function(e){t.removeItem(e)}}}function i(){var t=P;return{set:function(e,n){t[e]=n},get:function(e){return e in t?t[e]:w},remove:function(e){delete t[e]}}}function c(t){return t.split(m).reverse().join(m)}function u(t){var e;if(-1===t.indexOf("\\."))e=t.split(".");else{e=c(t).split(/\.(?!\\)/).reverse();for(var n=0,r=e.length;r>n;n++)e[n]=c(e[n].replace(/\.\\/g,"."))}return e}function s(t,e,n){for(var r=u(t),a=n;r.length;){var o=r.shift();if(r.length)a[o]=a[o]||{},a=a[o];else{if(!p(a))throw new Error("Cannot create property `"+o+"` on non-object value, path:`"+t+"`");a[o]=e}}return n}function f(t,e,n){if(n=n||!1,n===!0||-1===t.indexOf("."))return e[t];for(var r=u(t);r.length;){var a=r.shift();if(e=f(a,e,!0),"object"!=typeof e||void 0===e){r.length&&(e=void 0);break}}return e}function l(t,e,n){if(n=n||-1===t.indexOf("."))return e.hasOwnProperty(t);for(var r=u(t);r.length;){var a=r.shift(),o=e.hasOwnProperty(a);if(!o||!r.length)return o;if(e=f(a,e,!0),!p(e))return O}}function d(t,e){for(var n=u(t),r=e;n.length;){var a=n.shift();n.length?(r[a]=r[a]||{},r=r[a]):delete r[a]}return e}function _(t){var e=b;for(var n in t){e=O;break}return e}var g=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),h=n(2),v=h.extend,p=h.isPlainObject,y=window,k="undefined"!=typeof y,w=null,m="",b=!0,O=!b,S="_placeholder",x=void 0;x="1.0.0-rc5";var D={localStorage:k&&!!y.localStorage&&a("localStorage"),sessionStorage:k&&!!y.sessionStorage&&a("sessionStorage")},E={type:"localStorage",key:m,tag:m,duration:0,until:0},A=v({},E),K=function(){function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];r(this,t);var n=this;if(n.config=v({},A,e),!n.config.key)throw new Error("`key` is missing, please check the options passed in `nattyStorage` constructor.");n._storage=D[n.config.type]?o(n.config.type):i(),n._CHECK_KEY="nattyStorageCheck:"+n.config.key,n._DATA_KEY="nattyStorageData:"+n.config.key,n._placeholderUsed=O,n._createStamp=+new Date}return g(t,[{key:"_lazyInit",value:function(){var t=this;t._checkData=t._storage.get(t._CHECK_KEY),t._isNew=t._checkData===w,t._isNew||t.isOutdated()?t._storage.set(t._DATA_KEY,t._data={}):(t._data=t._storage.get(t._DATA_KEY),t._data===w&&t._storage.set(t._DATA_KEY,t._data={})),t._storage.set(t._CHECK_KEY,t._checkData={tag:t.config.tag,lastUpdate:t._createStamp,duration:t.config.duration,until:t.config.until})}},{key:"isOutdated",value:function(){var t=this;if(t.config.tag&&t.config.tag!==t._checkData.tag)return b;var e=+new Date;return t._checkData.duration&&e-t._checkData.lastUpdate>t._checkData.duration?b:t._checkData.until&&e>t._checkData.until?b:O}},{key:"set",value:function(t,e){var n=this,r=arguments.length;return new Promise(function(a,o){try{n._data||n._lazyInit(),1===r?p(t)?n._data=t:(n._data[S]=t,n._placeholderUsed=b):s(t,e,n._data),n._storage.set(n._DATA_KEY,n._data),a()}catch(i){o(i)}})}},{key:"get",value:function(t){var e=this;return new Promise(function(n,r){try{var a=void 0;e._data||e._lazyInit(),a=t?f(t,e._data):e._placeholderUsed?e._data[S]:e._data,n(a)}catch(o){r(o)}})}},{key:"has",value:function(t){var e=this;return new Promise(function(n,r){try{if(e._data||e._lazyInit(),e._placeholderUsed||_(e._data))n(e._data.hasOwnProperty(S)?{has:!0,value:e._data[S]}:{});else{if(!t)throw new Error("a `path` argument should be passed into the `has` method");n(l(t,e._data)?{has:!0,value:f(t,e._data)}:{})}}catch(a){r(a)}})}},{key:"remove",value:function(t){var e=this;return new Promise(function(n,r){try{e._data||e._lazyInit(),t?(d(t,e._data),e._storage.set(e._DATA_KEY,e._data)):e.set({}),n()}catch(a){r(a)}})}},{key:"destroy",value:function(){var t=this;t._storage.remove(t._CHECK_KEY),t._storage.remove(t._DATA_KEY)}},{key:"dump",value:function(){JSON&&console&&console.log(JSON.stringify(this._data,w,4))}}]),t}(),j=function(t){return new K(t)};j.version=x,j._variable=P,j.support=D,j.create=function(t){return new K(t)},j.setGlobal=function(t){A=v({},E,t)},j.getGlobal=function(t){return t?A[t]:A};var P={};t.exports=j},function(t,e,n){"use strict";var r=null,a=function(t){return function(){for(var e=arguments,n=t(e[0],e[1]),r=2,a=e.length;a>r;r++)n=t(n,e[r]);return n}},o="object",i=function(t){return typeof t===o},c=function(t){return t!==r&&t===t.window},u=function(t){return t!==r&&i(t)&&!c(t)&&Object.getPrototypeOf(t)===Object.prototype},s=Array.isArray,f=function l(){var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];for(var n in e)e.hasOwnProperty(n)&&void 0!==e[n]&&(s(e[n])?t[n]=[].concat(e[n]):u(e[n])?t[n]=l({},e[n]):t[n]=e[n]);return t};t.exports={extend:a(f),isPlainObject:u}}])});
{
"name": "natty-storage",
"version": "1.0.0-rc4",
"version": "1.0.0-rc5",
"description": "",

@@ -5,0 +5,0 @@ "repository": "https://github.com/Jias/natty-storage.git",

@@ -5,59 +5,61 @@ # natty-storage

> The experience for developers is crucial!
> Widgets of `Natty` series, with vertical thinking and the spirit of the craftsman, concentrates on improving the user experiences of Web developers. if it does help you, please give a support. :D
> 开发者的体验至关重要!
> `natty`系列的小工具,以垂直的思路和工匠的精神,在微小的技术点上追求极致的精美,专注于提升前端同学的开发体验。如果对你有帮助,考虑支持一下吧 :D
## Characteristic
## 特点
* It uses `localStorage` and `sessionStorage` asynchronously(`Promise`) which is non-blocking, and it can decently catch exceptions (for instance, the biggest limitation of browsers is exceeded)。
* It supports using path (`Path`) to set、retrieve and delete data, and it significantly reduces los of code compared with using native objects.
* It encapsulates three estimation of validity(`validity`), including tags(`tag`)、long validity(`duration`)、validUntil(`validUntil`), to avoid redundant coding.
* In the incognito mode, `localStorage` is not supported in some browsers, now it is automatically demoted to the `variable` mode.
* After `gzip`, only `2.3K`.
* 以异步(`Promise`)方式使用`localStorage`和`sessionStorage`,不再阻塞,并优雅地捕获异常(如超出浏览器最大限制)。
* 支持以路径(`Path`)方式设置、获取和删除数据,相对于直接使用原生对象,大大减少了代码量。
* 封装了三种有效性(`validity`)判断,标记(`tag`)、有效期长(`duration`)、有效期至(`until`),不再重复编码。
* 隐身模式下,有些浏览器不支持`localStorage`,此时自动降级为`variable`模式。
* `gzip`后的只有`2.3K`。
> TODO:demo added as further explaination for each characteristic
> TODO:这里的每一个特点都加上demo说明。
## Create the cache object
## 创建缓存对象
create the object cache instances
创建缓存对象的实例
```js
let ls = new NattyStorage({
type: 'localStorage',
key: 'foo',
tag: '1.0',
...
let storage = nattyStorage({
type: 'localStorage', // 缓存方式
key: 'ChinaCity', // !!! 唯一必选的参数,用于内部存储
tag: 'v1.0', // 缓存的标记,用于判断是否有效
duration: 1000*60*10, // 缓存的有效期长,以毫秒数指定
until: 1464759086797 // 缓存的到期时间,以具体日期时间的时间戳指定
});
```
#### `type`(optionally):enumerations
#### `type`(可选):枚举值
Specify how the cache object stores data. optional values are `localStorage`、`sessionStorage` and`variable`. The default value is `localStorage`。
指定缓存对象存储数据的方式,可选值为`localStorage`、`sessionStorage`和`variable`。默认为`localStorage`。
When the value of `type` is `localStorage` and the `localStorage` is not available (such as in incognito mode in some browsers),it is automatically demoted to `variable` mode to store data.
当指定`type`为`localStorage/sessionStorage`,但浏览器的`localStorage/sessionStorage`不可用时(比如部分浏览器的隐身模式下),则自动降级到`varable`方式存储。
#### `key`(required):string
#### `key`(必选):字符串
A unique identification of the cache object. If `key` of two cache objects are the same, then cached data also should be the same.
指定缓存对象存储数据所使用的唯一标识。如果两个缓存对象的`key`值相同,则缓存的数据也是相同的。
#### `tag`(optionally):string
#### `tag`(可选):字符串
Using tags to find out whether the stored data is valid or invalid。If the tags are differnt, the cache is invalidated.
通过一个标记来判断缓存对象所存储的数据是否有效。`tag`不同则缓存失效。
> Used for caching the data which is not likely to change, such as city data.
> 通常tag的值是一个字符串标识,比如版本号。
#### `duration`(optionally):timestamp
#### `duration`(可选):毫秒数
Using "long validity" to find out whether the stored data is valid or invalid. The cache is invalidated when it expires, or it would be postpone to the expiry date。
通过"有效期长"来判断缓存对象所存储的数据是否有效。过期则缓存失效,不过期则顺延。
#### `until`(optionally):timestamp
#### `until`(可选):时间戳
Using "validUntil" to find out whether the stored data is valid or invalid. The cache is invalidated when it expires.
通过"有效期至"来判断缓存对象所存储的数据是否有效。过期则缓存失效。
## Set Data
Setting data includes adding new data and modifying existing data .
## 设置数据
设置数据包括添加新数据和修改已有的数据,都很方便。
```js
// set complete data
ls.set({x:'x'}).then(function(){
// 设置完整数据
storage.set({x:'x'}).then(function(){
// do something

@@ -68,22 +70,22 @@ }).catch(function(e){

// set any type of complete data
ls.set('x').then().catch();
// 设置任意类型的完整数据
storage.set('x').then().catch();
// set specified data
ls.set('foo', 'x').then().catch();
// 设置指定键的数据
storage.set('foo', 'x').then().catch();
// set the data for the specified path
ls.set('foo.bar', 'x').then().catch();
// 设置指定路径的数据
storage.set('foo.bar', 'x').then().catch();
// if there is `.` in the path , it needs to be escaped
ls.set('fo\\.o.bar', 'x').then().catch();
// 如果路径中的某个键包含`.`号, 转义即可
storage.set('fo\\.o.bar', 'x').then().catch();
```
## Get Data
## 获取数据
Getting complete data and getting some data by means of a path are supported
获取数据支持获取全部数据和以路径方式获取部分数据。
```js
// get complete data
ls.get().then(function(data){
// 获取完整数据
storage.get().then(function(data){
// do something with data

@@ -94,18 +96,18 @@ }).catch(function(e){

// get specified data
ls.get('foo').then().catch();
// 获取指定的键的数据
storage.get('foo').then().catch();
// get the data for the specified path
ls.get('foo.bar').then().catch();
// 获取指定的路径的数据
storage.get('foo.bar').then().catch();
// if there is `.` in the path , it needs to be escaped
ls.get('fo\\.o.bar').then().catch();
// 如果路径中的某个键包含`.`号, 转义即可
storage.get('fo\\.o.bar').then().catch();
```
## Determine whether data exists.
## 判断数据是否存在
```js
// Based on the specified path, determine whether data exists
ls.has('x.y').then(function(result){
// presence
// 根据指定的路径,判断数据是否存在
storage.has('x.y').then(function(result){
// 存在
// {

@@ -116,3 +118,3 @@ // has: true,

//
// absent
// 不存在
// {

@@ -124,40 +126,59 @@ // has: false,

// If you don't specify a path, you need to determine whether the global value is set
// If the global value is not set,and you don't specify a path, it will report an error
ls.has().then().catch();
// 不指定路径,判断是否设置过全量的值
// 如果没有设置过全量的值,又没有指定查找路径,则报错
storage.has().then().catch();
```
## Delete Data
## 删除数据
when data is deleted, the key you specify and the corresponding value will be deleted.
删除数据会同时删除指定的键和对应的值。
```js
// delete the data and key values of the specified path
ls.remove('x.y').then().catch();
// 删除设置指定路径的数据和键
storage.remove('x.y').then().catch();
// clean up the data
ls.remove().then().catch();
// 清空数据为{}
storage.remove().then().catch();
```
## Destroy instance
## 销毁实例
destroy the cache object instance
销毁缓存对象实例
```js
ls.destory();
storage.destory();
```
## External dependencies
## 外部依赖
`NattyStorage` is based on two objects of modern browsers. If it is not on modern browsers, it should be solved by introducing `polyfill`.
`nattyStorage`依赖现代浏览器的两个对象。在非现代浏览器下,可以通过引入`polyfill`解决。
* `Promise` object, recommended `polyfill`:[lie](https://github.com/calvinmetcalf/lie)
* `JSON` object, recommended `polyfill`:[json2](https://github.com/douglascrockford/JSON-js)
* `Promise`对象,推荐的`polyfill`:[lie](https://github.com/calvinmetcalf/lie)
* `JSON`对象,推荐的`polyfill`:[json2](https://github.com/douglascrockford/JSON-js)
## Develop
## IE8和IE9的兼容性
`clone` the code, and to be run in the root directory:
如果需要兼容`IE8`和`IE9`,需要引入`es5-shim`和`es5-sham`。
安装
```shell
npm install es5-shim --save
```
将下面的代码添加到`nattyStorage`标签之前
```html
<!--[if lt IE 10]>
<script type="text/javascript" src="./node_modules/es5-shim/es5-shim.min.js"></script>
<script type="text/javascript" src="./node_modules/es5-shim/es5-sham.min.js"></script>
<![endif]-->
```
## 开发
把代码`clone`到本地,在根目录下执行:
```shell
npm install

@@ -167,2 +188,6 @@ npm run dev

## 构建
```shell
npm run build
```

@@ -52,3 +52,3 @@ "use strict";

/**
* let ls = new NattyStorage({
* let ls = new nattyStorage({
* type: 'localstorage', // sessionstorage, variable

@@ -60,3 +60,3 @@ * key: 'city',

*/
class NattyStorage {
class Storage {
/**

@@ -71,4 +71,5 @@ * 构造函数

// 必须配置`key`!!! 无论什么类型!!!
if (!t.config.key) {
throw new Error('`key` is missing, please check the options passed in `NattyStorage` constructor.');
throw new Error('`key` is missing, please check the options passed in `nattyStorage` constructor.');
}

@@ -78,4 +79,4 @@

t._CHECK_KEY = 'NattyStorageCheck:' + t.config.key;
t._DATA_KEY = 'NattyStorageData:' + t.config.key;
t._CHECK_KEY = 'nattyStorageCheck:' + t.config.key;
t._DATA_KEY = 'nattyStorageData:' + t.config.key;
t._placeholderUsed = FALSE;

@@ -299,8 +300,10 @@

NattyStorage.version = VERSION;
NattyStorage.support = {};
NattyStorage.support.localStorage = support.localStorage;
NattyStorage.support.sessionStorage = support.sessionStorage;
NattyStorage._variable = {};
let nattyStorage = (options) => {
return new Storage(options);
}
nattyStorage.version = VERSION;
nattyStorage._variable = variable;
nattyStorage.support = support;
/**

@@ -310,3 +313,3 @@ * 执行全局配置

*/
NattyStorage.setGlobal = (options) => {
nattyStorage.setGlobal = (options) => {
runtimeGlobalConfig = extend({}, defaultGlobalConfig, options);

@@ -321,3 +324,3 @@ return this;

*/
NattyStorage.getGlobal = (property) => {
nattyStorage.getGlobal = (property) => {
return property ? runtimeGlobalConfig[property] : runtimeGlobalConfig;

@@ -328,3 +331,2 @@ }

function createStorage(storage) {
// TODO 降级到variable模式
storage = win[storage]

@@ -340,3 +342,3 @@ return {

get: function (key) {
var value = storage.getItem(key);
let value = storage.getItem(key);
// alert(localStorage[key]);

@@ -356,4 +358,5 @@ if (!value) return NULL;

let variable = {};
function createVariable() {
let storage = NattyStorage._variable;
let storage = variable;
return {

@@ -479,2 +482,2 @@ set: function (key, value) {

module.exports = NattyStorage;
module.exports = nattyStorage;
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc