Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 21 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
![Lockr logo](http://i.imgur.com/m5kPjkB.png)
[![Code
![Lockr logo](http://i.imgur.com/m5kPjkB.png)[![Code
Climate](https://codeclimate.com/github/tsironis/lockr/badges/gpa.svg)](https://codeclimate.com/github/tsironis/lockr)


> A minimal API wrapper for localStorage. Simple as your high-school locker.

Lockr (pronounced /ˈlɒkəʳ/) is an extremely lightweight library (<2kb when minified), designed to facilitate how you interact with localStorage. Saving objects and arrays, numbers or other data types, accessible via a Redis-like API, heavily inspired by [node_redis](https://github.com/mranney/node_redis/).

## How to use lockr
How to use lockr
----------------

In order to user lockr, you firstly need to install it in your project.

```js
bower install lockr
```

or you use npm to install
or you use npm to install

```js
npm i lockr --save
Expand All @@ -27,27 +26,30 @@ or maybe download it manually from [here](https://raw.github.com/tsironis/lockr/
<script src="/path/to/lockr.js" type="text/javascript"></script>
```

## API reference
API reference
-------------

```Lockr.set``` - arguments: *[ key, value ]* {String, Number, Array or Object}
`Lockr.set` - arguments: *[ key, value ]* {String, Number, Array or Object}

> Set a key to a particular value or a hash object (```Object``` or ```Array```) under a hash key.
> Set a key to a particular value or a hash object (`Object` or `Array`) under a hash key. You can set the local-key expires;

*Example*

```js
Lockr.set('username', 'Coyote'); // Saved as string
Lockr.set('user_id', 12345); // Saved as number
Lockr.set('users', [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]);
Lockr.set('username', 'Coyote', {expires: 6}); //expires: 6 minutes
```

---

```Lockr.get``` - arguments: *[ key or hash_key, default value ]*
`Lockr.get` - arguments: *[ key or hash_key, default value ]*

> Returns the saved value for given key, even if the saved value is hash object. If value is null or undefined it returns a default value.

*Example*

```js
Lockr.get('username');
> "Coyote"
Expand All @@ -68,9 +70,9 @@ Lockr.get('score', 0):

---

```Lockr.rm``` - arguments: *[ key ]* {String}
`Lockr.rm` - arguments: *[ key ]* {String}

> Remove a key from ```localStorage``` entirely.
> Remove a key from `localStorage` entirely.

*Example*

Expand All @@ -85,7 +87,7 @@ Lockr.get('username');

---

```Lockr.sadd``` - arguments *[ key, value ]*{String, Number, Array or Object}
`Lockr.sadd` - arguments *[ key, value ]*{String, Number, Array or Object}

> Adds a unique value to a particular set under a hash key.

Expand All @@ -99,7 +101,7 @@ Lockr.sadd("wat", 1); // [1, 2]

---

```Lockr.smembers``` - arguments *[ key ]*
`Lockr.smembers` - arguments *[ key ]*

> Returns the values of a particular set under a hash key.

Expand All @@ -113,7 +115,7 @@ Lockr.smembers("wat"); // [42, 1337]

---

```Lockr.sismember``` - arguments *[ key, value ]*
`Lockr.sismember` - arguments *[ key, value ]*

> Returns whether the value exists in a particular set under a hash key.

Expand All @@ -127,7 +129,7 @@ Lockr.sismember("wat", 2); // false

---

```Lockr.srem``` - arguments *[ key, value ]*
`Lockr.srem` - arguments *[ key, value ]*

> Removes a value from a particular set under a hash key.

Expand All @@ -142,19 +144,20 @@ Lockr.smembers("wat"); // [2]

---

```Lockr.getAll``` - arguments: *null*
`Lockr.getAll` - arguments: *null*

> Returns all saved values & objects, in an ```Array```
> Returns all saved values & objects, in an `Array`

*Example*

```js
Lockr.getAll();
> ["Coyote", 12345, [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]]
```

---

```Lockr.flush()``` - arguments: *null*
`Lockr.flush()` - arguments: *null*

> Empties localStorage().

Expand Down
2 changes: 2 additions & 0 deletions gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ module.exports = function(grunt) {
// Task configuration.
jshint: {
options: {
asi: false,
curly: true,
eqeqeq: true,
immed: true,
Expand All @@ -25,6 +26,7 @@ module.exports = function(grunt) {
boss: true,
eqnull: true,
browser: true,
indent: 2,
globals: {
jQuery: true
}
Expand Down
83 changes: 44 additions & 39 deletions lockr.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,66 +16,73 @@
'use strict';

if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/)
{
Array.prototype.indexOf = function(elt /*, from*/ ) {
var len = this.length >>> 0;

var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;

for (; from < len; from++)
{
for (; from < len; from++) {
if (from in this &&
this[from] === elt)
this[from] === elt)
return from;
}
return -1;
};
}

Lockr.prefix = "";
Lockr.expires = new Date().getTime()+1e6*6*6*24*365; //the default expires more than 10 years

Lockr._getPrefixedKey = function(key, options) {
options = options || {};

if (options.noPrefix) {
return key;
} else {
return this.prefix + key;
}

};

Lockr.set = function (key, value, options) {
var query_key = this._getPrefixedKey(key, options);
Lockr.getExpirationTime = function(options) {
options = options || {};
if (options.expires) {
return new Date().getTime() + options.expires * 60 * 1000;
} else {
return this.expires;
};
}

try {
localStorage.setItem(query_key, JSON.stringify({"data": value}));
Lockr.set = function(key, value, options) {
var query_key = this._getPrefixedKey(key, options),
expires = this.getExpirationTime(options);
try {
localStorage.setItem(query_key, JSON.stringify({"data": value, "timestamp":expires}));
} catch (e) {
if (console) console.warn("Lockr didn't successfully save the '{"+ key +": "+ value +"}' pair, because the localStorage is full.");
if (console) console.warn("Lockr didn't successfully save the '{" + key + ": " + value + "}' pair, because the localStorage is full.");
}
};

Lockr.get = function (key, missing, options) {
Lockr.get = function(key, missing, options) {
var query_key = this._getPrefixedKey(key, options),
value;
value;

try {
value = JSON.parse(localStorage.getItem(query_key));
if (!value.timestamp) {
value.timestamp = this.getExpirationTime(options);
};
} catch (e) {
if(localStorage[query_key]) {
value = {data: localStorage.getItem(query_key)};
} else{
value = null;
}
if (localStorage[query_key]) {
value = { data: localStorage.getItem(query_key), timestamp: this.getExpirationTime(options) };
} else {
value = null;
}
}
if(value === null) {
if (value === null) {
return missing;
} else if (typeof value === 'object' && typeof value.data !== 'undefined') {
} else if (typeof value === 'object' && typeof value.data !== 'undefined' && new Date().getTime() < value.timestamp) {
return value.data;
} else {
return missing;
Expand All @@ -84,7 +91,7 @@

Lockr.sadd = function(key, value, options) {
var query_key = this._getPrefixedKey(key, options),
json;
json;

var values = Lockr.smembers(key);

Expand All @@ -94,17 +101,17 @@

try {
values.push(value);
json = JSON.stringify({"data": values});
json = JSON.stringify({ "data": values });
localStorage.setItem(query_key, json);
} catch (e) {
console.log(e);
if (console) console.warn("Lockr didn't successfully add the "+ value +" to "+ key +" set, because the localStorage is full.");
if (console) console.warn("Lockr didn't successfully add the " + value + " to " + key + " set, because the localStorage is full.");
}
};

Lockr.smembers = function(key, options) {
var query_key = this._getPrefixedKey(key, options),
value;
value;

try {
value = JSON.parse(localStorage.getItem(query_key));
Expand All @@ -119,8 +126,6 @@
};

Lockr.sismember = function(key, value, options) {
var query_key = this._getPrefixedKey(key, options);

return Lockr.smembers(key).indexOf(value) > -1;
};

Expand All @@ -132,7 +137,7 @@
return allKeys;
}

allKeys.forEach(function (key) {
allKeys.forEach(function(key) {
if (key.indexOf(Lockr.prefix) !== -1) {
keys.push(key.replace(Lockr.prefix, ''));
}
Expand All @@ -141,17 +146,17 @@
return keys;
};

Lockr.getAll = function () {
Lockr.getAll = function() {
var keys = Lockr.keys();
return keys.map(function (key) {
return keys.map(function(key) {
return Lockr.get(key);
});
};

Lockr.srem = function(key, value, options) {
var query_key = this._getPrefixedKey(key, options),
json,
index;
json,
index;

var values = Lockr.smembers(key, value);

Expand All @@ -160,20 +165,20 @@
if (index > -1)
values.splice(index, 1);

json = JSON.stringify({"data": values});
json = JSON.stringify({ "data": values });

try {
localStorage.setItem(query_key, json);
} catch (e) {
if (console) console.warn("Lockr couldn't remove the "+ value +" from the set "+ key);
if (console) console.warn("Lockr couldn't remove the " + value + " from the set " + key);
}
};

Lockr.rm = function (key) {
Lockr.rm = function(key) {
localStorage.removeItem(key);
};

Lockr.flush = function () {
Lockr.flush = function() {
if (Lockr.prefix.length) {
Lockr.keys().forEach(function(key) {
localStorage.removeItem(Lockr._getPrefixedKey(key));
Expand Down
2 changes: 1 addition & 1 deletion lockr.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions npm-debug.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/iojs', '/usr/local/bin/npm', 'run', 'dev' ]
2 info using npm@3.3.12
3 info using node@v5.4.1
4 verbose stack Error: missing script: dev
4 verbose stack at run (/usr/local/lib/node_modules/npm/lib/run-script.js:147:19)
4 verbose stack at /usr/local/lib/node_modules/npm/lib/run-script.js:57:5
4 verbose stack at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:345:5
4 verbose stack at checkBinReferences_ (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:309:45)
4 verbose stack at final (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:343:3)
4 verbose stack at then (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:113:5)
4 verbose stack at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:300:12
4 verbose stack at tryToString (evalmachine.<anonymous>:414:3)
4 verbose stack at FSReqWrap.readFileAfterClose [as oncomplete] (evalmachine.<anonymous>:401:12)
5 verbose cwd /Users/Tom/Sites/github/lockr
6 error Darwin 15.5.0
7 error argv "/usr/local/bin/iojs" "/usr/local/bin/npm" "run" "dev"
8 error node v5.4.1
9 error npm v3.3.12
10 error missing script: dev
11 error If you need help, you may report this error at:
11 error <https://github.com/npm/npm/issues>
12 verbose exit [ 1, true ]
Loading