-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
125 lines (117 loc) · 3.03 KB
/
db.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
const async = require('async');
const orm = require('orm');
const settings = require('./settings');
if (require.main === module && process.argv.indexOf('--create-test-db') > -1) {
orm.connect(`${settings.partial_dsn}/`, function (err, db) {
db.driver.execQuery(`CREATE DATABASE IF NOT EXISTS test`, function (err, data) {
console.log("Test database was successfully created");
});
});
}
const db = orm.connect(settings.dsn);
db.on('connect', function (err) {
if (err) return console.error('Connection error: ' + err);
});
const functions = {
createTables: function (next) {
db.load("./models", function (err) {
if (err) throw err;
// create tables
db.sync(function (err) {
if (err) throw err;
next();
});
});
},
applyFixtures: function (next) {
this.truncateTables(function () {
async.series([
function (callback) {
db.models.users.create({
id: 1,
email: "user1@example.com",
password: "$2a$10$mhkqpUvPPs.zoRSTiGAEKODOJMljkOY96zludIIw.Pop1UvQCTx8u"
}, function (err) {
callback(null)
});
},
function (callback) {
db.models.users.create({
id: 2,
email: "user2@example.com",
password: "$2a$10$mhkqpUvPPs.zoRSTiGAEKODOJMljkOY96zludIIw.Pop1UvQCTx8u"
}, function (err) {
callback(null)
});
},
function (callback) {
db.models.pads.create({
id: 1,
name: "Pad 1",
user_id: 1
}, function (err) {
callback(null)
});
},
function (callback) {
db.models.pads.create({
id: 2,
name: "Pad 2",
user_id: 1
}, function (err) {
callback(null)
});
},
function (callback) {
db.models.notes.create({
id: 1,
name: "Note 1",
text: "Text",
user_id: 1,
pad_id: 1,
}, function (err) {
callback(null)
});
},
function (callback) {
db.models.notes.create({
id: 2,
name: "Note 2",
text: "Text",
user_id: 1,
pad_id: 1,
}, function (err) {
callback(null)
});
}
], function (err, results) {
next();
})
});
},
truncateTables: function (next) {
async.series([
function (callback) {
db.models.users.clear();
callback(null);
},
function (callback) {
db.models.pads.clear();
callback(null);
},
function (callback) {
db.models.notes.clear();
callback(null);
}
], function (err, results) {
next();
})
}
}
if (require.main === module) {
functions.createTables(function () {
console.log("All tables were successfully synchronized with the models");
process.exit(0)
});
}
module.exports = functions;