-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
61 lines (47 loc) · 1.23 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'use strict';
var uuid = require('uuid');
var level = require('level');
var ttl = require('level-ttl');
var TTL_LIMIT = 1000 * 60 * 60 * 24; // 24 hours
var RevisitToken = function (options) {
if (!(this instanceof RevisitToken)) {
return new RevisitToken(options);
}
if (!options) {
options = {};
}
var dbPath = options.db || './db-tokens';
var defaultTTL = parseInt(options.ttl, 10) || TTL_LIMIT;
var frequency = parseInt(options.frequency, 10) || 10000;
var db = level(dbPath, {
createIfMissing: true,
valueEncoding: 'json'
});
db = ttl(db, { checkFrequency: frequency || 10000 });
this.generate = function (next) {
this.putToken(uuid.v4(), next);
};
this.putToken = function (token, ttl, next) {
if (typeof ttl == 'function') {
next = ttl;
ttl = defaultTTL;
}
db.put('token!' + token, token, {
ttl: ttl
}, function (err) {
if (err) {
return next(err);
}
next(null, token);
});
};
this.getToken = function (token, next) {
db.get('token!' + token, function (err, token) {
if (err || !token) {
return next(new Error('No token found'));
}
next(null, token);
});
};
};
module.exports = RevisitToken;