Skip to content

Commit 02858b6

Browse files
committed
accept custom id generators
1 parent e04bdd7 commit 02858b6

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

README.md

+12
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,18 @@ or a custom ID
107107
var db = new Store("data",{saveId:'myKey'});
108108
```
109109

110+
### custom ID generator
111+
We use uuid v4 for ID generation if you don't pass an id when save a data. If you want, you can pass custom generator.
112+
```javascript
113+
var i = 0;
114+
var db = new Store("data",{
115+
idGenerator: function() {
116+
i = i + 1;
117+
return i;
118+
}
119+
});
120+
```
121+
110122

111123
## Tests
112124

Store.es6.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ const save = function(id, o, cb) {
102102
id = null;
103103
}
104104
if (typeof id !== "string") {
105-
id = uuid.v4();
105+
id = this._idGenerator();
106106
}
107107
const file = this._getFileName(id);
108108
o = clone(o);
@@ -243,6 +243,7 @@ class Store {
243243
this._pretty = opt.pretty === true;
244244
this._memory = opt.memory === true || opt.type === 'memory';
245245
this._saveId = opt.saveId;
246+
this._idGenerator = typeof opt.idGenerator === "function" ? opt.idGenerator : uuid.v4;
246247

247248
if (isJSONFile(this.name)) {
248249
this.name = this.name.split(".json")[0];

Store.spec.es6.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ describe("The jfs module", () => {
1414
fs.unlink(NAME + '.json', (err) => {
1515
exec("rm -rf ./" + NAME, (err, out) => {
1616
console.log(out);
17-
if (err != null) {
17+
if (err !== null) {
1818
console.error(err);
1919
}
2020
done();
@@ -84,6 +84,19 @@ describe("The jfs module", () => {
8484
});
8585
});
8686

87+
it("can autosave the id with a custom generator", (done) => {
88+
const store = new Store(NAME, {
89+
idGenerator: () => "customId",
90+
saveId: true
91+
});
92+
store.save({}, (err, id) => {
93+
store.get(id, (err, o) => {
94+
o.id.should.equal("customId");
95+
done();
96+
});
97+
});
98+
});
99+
87100
it("can save an object synchronously", () => {
88101
const store = new Store(NAME);
89102
const data = {

0 commit comments

Comments
 (0)