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

storage plus for javascript

  • 1.0.0-rc1
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

natty-storage

storage plus for javascript

开发者的体验至关重要,请加星(★Star)支持Natty系列的js工具库,必有收获!

特点

  • 以异步(Promise)方式使用localStoragesessionStorage,减少阻塞,并优雅地捕获异常(如超出浏览器最大限制)。
  • 支持以路径(Path)方式设置、获取和删除数据,相对于直接使用原生对象,大大减少了代码量。
  • 封装了三种有效性(validity)判断,标记(tag)、有效期长(duration)、有效期至(validUntil),不再重复编码。
  • 隐身模式下,有些浏览器不支持localStorage,此时自动降级为variable模式。
  • TODO: gzip后的大小?

TODO:这里的每一个特点都加上demo说明。

创建缓存实例

创建缓存对象的实例

let ls = new NattyStorage({
    type: 'localStorage',
    key: 'foo',
    tag: '1.0',
    ...
});
type(可选):枚举值

指定缓存对象存储数据的方式,可选值为localStoragesessionStoragevariable。默认为localStorage

当指定type值为localStoragelocalStorage不可用时(比如部分浏览器的隐身模式下),则自动降级到varable方式存储。

key(必选):字符串

指定缓存对象存储数据所使用的唯一标识。如果两个缓存对象的key值相同,则缓存的数据也是相同的。

tag(可选):字符串

通过一个标记来判断缓存对象所存储的数据是否有效。标记不同则缓存失效。

通常用于缓存一些不经常变化的数据,比如城市数据。

duration(可选):时间戳

通过"有效期长"来判断缓存对象所存储的数据是否有效。过期则缓存失效,不过期则顺延。

until(可选):时间戳

通过"有效期至"来判断缓存对象所存储的数据是否有效。过期则缓存失效。

设置数据

设置数据包括添加新数据和修改已有的数据,都很方便。

// 设置完整数据
ls.set({x:'x'}).then(function(){
    // do something
}).catch(function(e){
    // deal the error
});

// 设置任意类型的完整数据
ls.set('x').then().catch();

// 设置指定键的数据
ls.set('foo', 'x').then().catch();

// 设置指定路径的数据
ls.set('foo.bar', 'x').then().catch();

// 如果路径中的某个键包含`.`号, 转义即可
ls.set('fo\\.o.bar', 'x').then().catch();

获取数据

// 获取完整数据
ls.get().then(function(data){
    // do something with data
}).catch(function(e){
    // deal the error
});

// 获取指定的键的数据
ls.get('foo').then().catch();

// 获取指定的路径的数据
ls.get('foo.bar').then().catch();

// 如果路径中的某个键包含`.`号, 转义即可
ls.get('fo\\.o.bar').then().catch();

删除数据

删除数据会同时删除指定的键和对应的值。

// 删除设置指定路径的数据和键
ls.remove('x.y').then().catch();

// 清空数据为{}
ls.remove().then().catch();

销毁实例

销毁缓存对象实例

ls.destory();

依赖

NattyStorage依赖现代浏览器的两个对象。在非现代浏览器下,可以通过引入polyfill解决。

  • Promise对象,推荐的polyfilllie
  • JSON对象,推荐的polyfilljson2

开发

把代码clone到本地,在根目录下执行:

npm install
npm run dev

Keywords

FAQs

Package last updated on 27 May 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

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