-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (61 loc) · 1.66 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
62
63
64
65
66
67
68
69
70
71
72
var _ = require('lodash')
var debug = require('debug')('koa:generic-session-rethinkdb')
function RethinkSession(opts) {
this.connection = opts.connection
this.dbName = opts.db || 'sessions'
this.tableName = opts.table || 'sessions'
}
RethinkSession.prototype.setup = function*() {
var errors = []
try {
yield this.connection.dbCreate(this.dbName)
} catch (e) {
errors.push(e)
}
try {
yield this.connection.db(this.dbName).tableCreate(this.tableName)
} catch (e) {
errors.push(e)
}
try {
yield this.connection.db(this.dbName).table(this.tableName).indexCreate('sid')
} catch (e) {
errors.push(e)
}
return errors
}
RethinkSession.prototype.table = function() {
return this.connection.db(this.dbName).table(this.tableName)
}
RethinkSession.prototype.get = function* (sid) {
debug('get', sid)
var res = yield this.table().getAll(sid, {index: 'sid'})
debug('got', res[0])
return res[0]
}
RethinkSession.prototype.set = function* (sid, session) {
// check if there is a doc with that id
debug('set', sid, session)
var res = yield this.table().getAll(sid, {index: 'sid'})
if (res[0]) {
res = res[0]
var payload = _.extend({
sid: sid,
id: res.id
}, session)
return yield this.table().get(res.id).replace(payload)
} else {
return yield this.table().insert(_.extend({
sid: sid
}, session))
}
}
RethinkSession.prototype.destroy = function* (sid) {
debug('destroy', sid)
var res = yield this.table().getAll(sid, {index: 'sid'})
if (res[0]) {
debug('found session to destroy', res[0])
return yield this.table().get(res[0].id).delete()
}
}
module.exports = RethinkSession