natty-storage
storage plus for javascript
开发者的体验至关重要!
natty
系列的小工具,以垂直的思路和工匠的精神,在微小的技术点上追求极致的精美,专注于提升前端同学的开发体验。如果对你有帮助,考虑支持一下吧 :D
特点
- 支持异步方式使用
localStorage
和sessionStorage
,避免阻塞,并优雅地捕获异常(如超出浏览器最大限制)。当然,同步方式使用依然是默认的使用方式。 - 支持以路径(
Path
)方式设置、获取和删除数据,相对于直接使用原生localStorage/sessionStorage
对象,大大减少了代码量。 - 封装了三种有效性判断,标记(
id
)、有效期长(duration
)、有效期至(until
),不再重复编码。 - 隐身模式下,有些浏览器不支持
localStorage
,此时自动降级为variable
模式。 gzip
后的只有2.3K
。
TODO:这里的每一个特点都加上demo说明。
nattyStorage(options)
创建缓存对象的实例
let storage = nattyStorage({
async: true,
type: 'localStorage',
key: 'ChinaCity',
id: 'v1.0',
duration: 1000*60*10,
until: 1464759086797
});
options
async
(可选):布尔值
是否开启异步方式使用,默认为false
。如果开启,则set/get/has/remove
四个方法的返回值都是Promise
实例,可以调用then
方法。
默认情况下,以同步方式使用
let storage = nattyStorage({
key: 'foo'
});
try {
storage.set('x', 'x');
} catch (error) {
}
console.log(storage.get('x'));
开启异步方式使用
let storage = nattyStorage({
async: true,
key: 'foo'
});
storage.set('x', 'x').then(function(){
console.log(storage.get('x'));
}).catch(function(error){
});
type
(可选):枚举值
指定缓存对象存储数据的方式,可选值为localStorage
、sessionStorage
和variable
。默认为localStorage
。
当指定type
为localStorage/sessionStorage
,但浏览器的localStorage/sessionStorage
不可用时(比如部分浏览器的隐身模式下),则自动降级到varable
方式存储。
key
(必选):字符串
指定缓存对象存储数据所使用的唯一标识。如果两个缓存对象的key
值相同,则缓存的数据也是相同的。
id
(可选):字符串
通过一个标记来判断缓存对象所存储的数据是否有效。id
不同则缓存失效。
通常id
的值是一个字符串标识,比如版本号。
duration
(可选):毫秒数
通过"有效期长"来判断缓存对象所存储的数据是否有效。过期则缓存失效,不过期则顺延。
until
(可选):时间戳
通过"有效期至"来判断缓存对象所存储的数据是否有效。过期则缓存失效。
set()
设置数据包括添加新数据和修改已有的数据,都很方便。
storage.set({x:'x'}).then(function(){
}).catch(function(e){
});
storage.set('x').then().catch();
storage.set('foo', 'x').then().catch();
storage.set('foo.bar', 'x').then().catch();
storage.set('fo\\.o.bar', 'x').then().catch();
get()
获取数据支持获取全部数据和以路径方式获取部分数据。
storage.get().then(function(data){
}).catch(function(e){
});
storage.get('foo').then().catch();
storage.get('foo.bar').then().catch();
storage.get('fo\\.o.bar').then().catch();
has()
判断数据是否存在
storage.has('x.y').then(function(result){
}).catch();
storage.has().then().catch();
remove()
删除数据会同时删除指定的键和对应的值。
storage.remove('x.y').then().catch();
storage.remove().then().catch();
destroy()
销毁缓存对象实例
storage.destroy();
外部依赖
nattyStorage
依赖现代浏览器的两个对象。在非现代浏览器下,可以通过引入polyfill
解决。
Promise
对象,推荐的polyfill
:lieJSON
对象,推荐的polyfill
:json2
IE8和IE9的兼容性
如果需要兼容IE8
和IE9
,需要引入es5-shim
和es5-sham
。
安装
npm install es5-shim --save
将下面的代码添加到nattyStorage
标签之前
dev
把代码clone
到本地,在根目录下执行:
npm install
npm run dev
build
npm run build