-
Notifications
You must be signed in to change notification settings - Fork 302
/
JobsManager.js
362 lines (333 loc) · 10.1 KB
/
JobsManager.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
var request = require('request');
var extend = require('util')._extend;
var Promise = require('bluebird');
var fs = require('fs');
var ArgumentError = require('rest-facade').ArgumentError;
var Auth0RestClient = require('../Auth0RestClient');
var RetryRestClient = require('../RetryRestClient');
/**
* Simple facade for consuming a REST API endpoint.
* @external RestClient
* @see https://github.com/ngonzalvez/rest-facade
*/
/**
* @class
* Abstract the creation as well as the retrieval of async jobs.
* @constructor
* @memberOf module:management
*
* @param {Object} options The client options.
* @param {String} options.baseUrl The URL of the API.
* @param {Object} [options.headers] Headers to be included in all requests.
* @param {Object} [options.retry] Retry Policy Config
*/
var JobsManager = function(options) {
if (options === null || typeof options !== 'object') {
throw new ArgumentError('Must provide client options');
}
if (options.baseUrl === null || options.baseUrl === undefined) {
throw new ArgumentError('Must provide a base URL for the API');
}
if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) {
throw new ArgumentError('The provided base URL is invalid');
}
var clientOptions = {
errorFormatter: { message: 'message', name: 'error' },
headers: options.headers,
query: { repeatParams: false }
};
this.options = options;
/**
* Provides an abstraction layer for consuming the
* {@link https://auth0.com/docs/api/v2#!/Jobs Jobs endpoint}.
*
* @type {external:RestClient}
*/
var auth0RestClient = new Auth0RestClient(
options.baseUrl + '/jobs/:id',
clientOptions,
options.tokenProvider
);
this.jobs = new RetryRestClient(auth0RestClient, options.retry);
/**
* Provides an abstraction layer for consuming the
* {@link https://auth0.com/docs/api/v2#!/Jobs/:id/errors Errors endpoint}.
*
* @type {external:RestClient}
*/
var jobErrorsRestClient = new Auth0RestClient(
options.baseUrl + '/jobs/:id/errors',
clientOptions,
options.tokenProvider
);
this.jobErrors = new RetryRestClient(jobErrorsRestClient, options.retry);
/**
* Provides an abstraction layer for consuming the
* {@link https://auth0.com/docs/api/v2#!/Jobs/post_users_exports Create job to export users endpoint}
*
* @type {external:RestClient}
*/
const usersExportsRestClient = new Auth0RestClient(
options.baseUrl + '/jobs/users-exports',
clientOptions,
options.tokenProvider
);
this.usersExports = new RetryRestClient(usersExportsRestClient, options.retry);
};
/**
* Get a job by its ID.
*
* @method get
* @memberOf module:management.JobsManager.prototype
*
* @example
* var params = {
* id: '{JOB_ID}'
* };
*
* management.jobs.get(params, function (err, job) {
* if (err) {
* // Handle error.
* }
*
* // Retrieved job.
* console.log(job);
* });
*
* @param {Object} params Job parameters.
* @param {String} params.id Job ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
JobsManager.prototype.get = function(params, cb) {
if (!params.id || typeof params.id !== 'string') {
throw new ArgumentError('The id parameter must be a valid job id');
}
if (cb && cb instanceof Function) {
return this.jobs.get(params, cb);
}
// Return a promise.
return this.jobs.get(params);
};
/**
* Given a path to a file and a connection id, create a new job that imports the
* users contained in the file or JSON string and associate them with the given
* connection.
*
* @method importUsers
* @memberOf module:management.JobsManager.prototype
*
* @example
* var params = {
* connection_id: '{CONNECTION_ID}',
* users: '{PATH_TO_USERS_FILE}',
* upsert: true, //optional
* send_completion_email: false //optional
* };
*
* management.jobs.importUsers(params, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Object} data Users import data.
* @param {String} data.connectionId Connection for the users insertion.
* @param {String} data.users Path to the users data file.
* @param {String} data.users_json JSON data for the users.
* @param {String} data.upsert OPTIONAL: set to true to upsert users, defaults to false
* @param {String} data.send_completion_email OPTIONAL: defaults to true
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
JobsManager.prototype.importUsers = function(data, cb) {
var options = this.options;
var headers = extend({}, options.headers);
headers['Content-Type'] = 'multipart/form-data';
var url = options.baseUrl + '/jobs/users-imports';
var method = 'POST';
var upsert = data.upsert === true ? 'true' : 'false';
var send_completion_email = data.send_completion_email === false ? 'false' : 'true';
var promise = options.tokenProvider.getAccessToken().then(function(access_token) {
return new Promise(function(resolve, reject) {
request(
{
url: url,
method: method,
headers: extend({ Authorization: `Bearer ${access_token}` }, headers),
formData: {
users: {
value: data.users_json
? Buffer.from(data.users_json)
: fs.createReadStream(data.users),
options: {
filename: data.users_json ? 'users.json' : data.users
}
},
connection_id: data.connection_id,
upsert: upsert,
send_completion_email: send_completion_email
}
},
function(err, res) {
if (err) {
reject(err);
return;
}
// `superagent` uses the error parameter in callback on http errors.
// the following code is intended to keep that behaviour (https://github.com/visionmedia/superagent/blob/master/lib/node/response.js#L170)
var type = (res.statusCode / 100) | 0;
var isErrorResponse = 4 === type || 5 === type;
if (isErrorResponse) {
var error = new Error('cannot ' + method + ' ' + url + ' (' + res.statusCode + ')');
error.status = res.statusCode;
error.method = method;
error.text = res.text;
try {
if (!error.text && res.body) {
error.text = JSON.parse(res.body).message;
}
} catch (ex) {
// Ignore the error.
}
reject(error);
}
resolve(res);
}
);
});
});
// Don't return a promise if a callback was given.
if (cb && cb instanceof Function) {
promise.then(cb.bind(null, null)).catch(cb);
return;
}
return promise;
};
/**
* Export all users to a file using a long running job.
*
* @method exportUsers
* @memberOf module:management.JobsManager.prototype
*
* @example
* var data = {
* connection_id: 'con_0000000000000001',
* format: 'csv',
* limit: 5,
* fields: [
* {
* "name": "user_id"
* },
* {
* "name": "name"
* },
* {
* "name": "email"
* },
* {
* "name": "identities[0].connection",
* "export_as": "provider"
* },
* {
* "name": "user_metadata.some_field"
* }
* ]
* }
*
* management.jobs.exportUsers(data, function (err, results) {
* if (err) {
* // Handle error.
* }
*
* // Retrieved job.
* console.log(results);
* });
*
* @param {Object} data Users export data.
* @param {String} [data.connection_id] The connection id of the connection from which users will be exported
* @param {String} [data.format] The format of the file. Valid values are: "json" and "csv".
* @param {Number} [data.limit] Limit the number of records.
* @param {Object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
JobsManager.prototype.exportUsers = function(data, cb) {
if (cb && cb instanceof Function) {
return this.usersExports.create(data, cb);
}
return this.usersExports.create(data);
};
/**
* Given a job ID, retrieve the failed/errored items
*
* @method get
* @memberOf module:management.JobsManager.prototype
*
* @example
* var params = {
* id: '{JOB_ID}'
* };
*
* management.jobs.errors(params, function (err, job) {
* if (err) {
* // Handle error.
* }
*
* // Retrieved job.
* console.log(job);
* });
*
* @param {Object} params Job parameters.
* @param {String} params.id Job ID.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
JobsManager.prototype.errors = function(params, cb) {
if (!params.id || typeof params.id !== 'string') {
throw new ArgumentError('The id parameter must be a valid job id');
}
if (cb && cb instanceof Function) {
return this.jobErrors.get(params, cb);
}
// Return a promise.
return this.jobErrors.get(params);
};
/**
* Send a verification email to a user.
*
* @method verifyEmail
* @memberOf module:management.JobsManager.prototype
*
* @example
* var params = {
* user_id: '{USER_ID}'
* };
*
* management.jobs.verifyEmail(function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Object} data User data object.
* @param {String} data.user_id ID of the user to be verified.
* @param {Function} [cb] Callback function.
*
* @return {Promise|undefined}
*/
JobsManager.prototype.verifyEmail = function(data, cb) {
if (!data.user_id || typeof data.user_id !== 'string') {
throw new ArgumentError('Must specify a user ID');
}
if (cb && cb instanceof Function) {
return this.jobs.create({ id: 'verification-email' }, data, cb);
}
// Return a promise.
return this.jobs.create({ id: 'verification-email' }, data);
};
module.exports = JobsManager;