-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbinit.js
86 lines (84 loc) · 2.31 KB
/
dbinit.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
var cradle = require('cradle'),
debug = require('debug')('initdb'),
products = require('./products'),
host = process.env.DB_HOST || 'localhost',
port = process.env.DB_PORT || 5984,
username = process.env.DB_USER || 'root',
password = process.env.DB_PASSWORD || 'root',
db = new(cradle.Connection)(host, port, {
auth: {
username: username,
password: password
}
}).database('energy'),
charMap = {
'á': 'a',
'é': 'e',
'í': 'i',
'ó': 'o',
'ú': 'u',
'ñ': 'n'
},
getSafeText = function (input) {
return Array.prototype.map.call(input.toLowerCase(), function (x) {
return charMap[x] || x;
}).join('').replace(/^\s+|\s+$/g, '').replace(/\W+/g, '-');
};
debug('Deploying db');
function prepareProductsForDB() {
products.forEach(function (p) {
p._id = '' + p.code;
p.type = 'product';
p.safeCategoryName = getSafeText(p.categoryName);
});
}
function putData() {
debug('Storing views');
db.save('_design/products', {
all: {
map: function (doc) {
if (doc.type === 'product') {
emit(doc._id, null);
}
}
},
categories: {
map: function (doc) {
if (doc.type === 'product') {
emit([doc.safeCategoryName, doc.categoryName, doc.categoryId], doc._id);
}
},
reduce: "_count"
}
});
debug('About to insert ' + products.length + ' products');
prepareProductsForDB();
db.save(products, function (err, res) {
if (err) {
console.error(err);
console.trace(err.stack);
return;
}
debug('Ok');
});
}
db.exists(function (err, exists) {
if (err) {
console.error(err);
console.trace(err.stack);
} else if (exists) {
debug('Cleaning existing db');
db.destroy(function () {
debug('Creating db');
db.create(function () {
putData();
});
});
} else {
debug('Database does not exists.');
debug('Creating db');
db.create(putData, function () {
putData();
});
}
});