-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathloader.js
executable file
·189 lines (171 loc) · 5.65 KB
/
loader.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#! /usr/local/bin/node
/*jslint node:true */
// loader.js
// ------------------------------------------------------------------
//
// Load JSON collections into an API BaaS organization + app.
//
// created: Thu Feb 5 19:29:44 2015
// last saved: <2017-April-26 09:03:07>
var fs = require('fs'),
path = require('path'),
q = require('q'),
Getopt = require('node-getopt'),
common = require('./lib/common.js'),
_ = require('lodash'),
startTime,
dataDir = path.join('./', 'data'),
usergrid = require('usergrid'),
re1 = new RegExp('\\s{2,}', 'g'),
batchNum = 0,
batchSize = 25,
count = 0,
getopt = new Getopt([
['c' , 'config=ARG', 'the configuration json file, which contains Usergrid/Baas org, app, and credentials'],
['o' , 'org=ARG', 'the Usergrid/BaaS organization.'],
['a' , 'app=ARG', 'the Usergrid/BaaS application.'],
['u' , 'username=ARG', 'app user with permissions to create collections. (only if not using client creds!)'],
['p' , 'password=ARG', 'password for the app user.'],
['i' , 'clientid=ARG', 'clientid for the Baas app. (only if not using user creds!)'],
['s' , 'clientsecret=ARG', 'clientsecret for the clientid.'],
['e' , 'endpoint=ARG', 'the BaaS endpoint (if not https://apibaas-trial.apigee.net)'],
['A' , 'anonymous', 'connect to BaaS anonymously. In lieu of user+pw or client id+secret.'],
['F' , 'file=ARG', 'upload just THIS .json file'],
['v' , 'verbose'],
['h' , 'help']
]).bindHelp();
// monkeypatch ug client to allow batch create.
// http://stackoverflow.com/a/24334895/48082
usergrid.client.prototype.batchCreate = function (type, entities, callback) {
if (!entities.length) { callback(); }
var data = _.map(entities, function(entity) {
var data = (entity instanceof usergrid.entity) ? entity.get() : entity;
return _.omit(data, 'metadata', 'created', 'modified', 'type', 'activated');
});
var options = {
method: 'POST',
endpoint: type,
body: data
};
var self = this;
this.request(options, function (e, data) {
var entities = [];
if (e) {
if (self.logging) { common.logWrite('could not save entities'); }
if (typeof(callback) === 'function') { callback(e, data); }
return;
}
if (data && data.entities) {
entities = _.map(data.entities, function(data) {
var options = {
type: type,
client: self,
uuid: data.uuid,
data: data || {}
};
var entity = new usergrid.entity(options);
entity._json = JSON.stringify(options.data, null, 2);
return entity;
});
}
else {
e = "No data available";
}
if (typeof(callback) === 'function') {
return callback(e, entities);
}
});
};
function postBatch(batch, ugClient, collection, cb) {
var splitTime = new Date(),
value = splitTime - startTime;
batchNum++;
common.logWrite('batch %d', batchNum);
ugClient.batchCreate(collection, batch, function (e, entities) {
cb(e, entities);
});
}
function arrayToChunks(chunkSize, a) {
var chunks = [];
for (var i=0, L=a.length; i<L; i+=chunkSize) {
chunks.push(a.slice(i,i+chunkSize));
}
return chunks;
}
var toBatches = _.curry(arrayToChunks)(batchSize);
function doUploadWork (ugClient, collectionName, data, cb) {
toBatches(data)
.reduce(function(promise, batch) {
return promise.then(function() {
var d = q.defer();
postBatch(batch, ugClient, collectionName,
function(e, data) {
d.resolve({});
});
return d.promise;
});
}, q({}))
.then(function () {
cb(null);
}, function(e) {
cb(e);
});
}
// data.forEach(function(item){
// count++;
// stack.push(item);
// // if (count % 100 === 0) {
// // process.stdout.write('.');
// // }
// if (count % batchSize === 0) {
// //process.stdout.write('.');
// }
// if ((count != data.length) && (count % (100 * batchSize) === 0)) {
// var splitTime = new Date(),
// value = splitTime - startTime;
// common.logWrite(' %d elapsed %s', count, common.elapsedToHHMMSS(value));
// }
// });
//
// if (stack.length > 0) {
// //process.stdout.write('.');
// postBatch(stack, ugClient, collectionName, function(e, data) {
// stack = [];
// cb(null);
// });
// }
function main(args) {
var collection, baasConn, opt = getopt.parse(args);
try {
baasConn = common.processOptions(opt, getopt);
common.logWrite('start');
startTime = new Date();
common.usergridAuth(baasConn, function (e, ugClient){
if (e) {
common.logWrite(JSON.stringify(e, null, 2) + '\n');
process.exit(1);
}
fs.readdir(dataDir, function (err,files){
files.forEach(function(filename) {
if (filename.endsWith('.json')) {
if ( ! opt.options.file || opt.options.file == filename) {
var shortname = filename.split('.json')[0];
console.log('uploading ' + shortname);
var data = JSON.parse(fs.readFileSync(path.join(dataDir, filename), 'utf8'));
doUploadWork(ugClient, shortname, data, function(e) {
var endTime = new Date(), value = endTime - startTime;
common.logWrite('finis');
common.logWrite('elapsed %d: %s', value, common.elapsedToHHMMSS(value));
});
}
}
});
});
});
}
catch (exc1) {
console.log("Exception:" + exc1);
console.log(exc1.stack);
}
}
main(process.argv.slice(2));