-
Notifications
You must be signed in to change notification settings - Fork 0
/
datastore.js
80 lines (70 loc) · 2.2 KB
/
datastore.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
73
74
75
76
77
78
79
80
var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password', {
// data is stored in memory, change storage type for persistence
// http://sequelize.readthedocs.io/en/latest/api/sequelize/
dialect:'sqlite',
storage:':memory:',
});
var Token;
// Stores key-value pair in database
function set(key, value) {
if (typeof(key) !== 'string')
return Promise.reject(new DatastoreKeyNeedToBeStringException(key));
return Token.find({ where: { key } })
.then(token => {
return token
? token.update({ value })
: Token.create({ key, value });
});
}
// Fetches the value matching key from the database
function get(key) {
if (typeof(key) !== 'string')
return Promise.reject(new DatastoreKeyNeedToBeStringException(key));
return Token.findOne({ where: { key } }).then(resolveValue);
}
function resolveValue(data) {
return (data === null) ? null : data.value;
}
function connect() {
return sequelize.authenticate()
.then(_ => {
console.log('Connection has been established successfully.');
// define a new table 'token'
Token = sequelize.define('token', {
key: {
type: Sequelize.STRING
},
value: {
type: Sequelize.STRING
},
});
return Token.sync();
})
.then(_ => Token)
.catch(reason => {
console.log('Unable to connect to the database: ', reason);
// improve error result by throwing expection.
throw new DatastoreUnknownException("connect", null, reason);
});
}
function DatastoreKeyNeedToBeStringException(keyObject) {
this.type = this.constructor.name;
this.description = "Datastore can only use strings as keys, got " + keyObject.constructor.name + " instead.";
this.key = keyObject;
}
function DatastoreUnknownException(method, args, ex) {
this.type = this.constructor.name;
this.description = "An unknown error happened during the operation " + method;
this.method = method;
this.args = args;
this.error = ex;
}
var datastore = {
set: set,
get: get,
connect: connect
};
module.exports = {
data: datastore
};