-
Notifications
You must be signed in to change notification settings - Fork 24
/
registry.js
750 lines (741 loc) · 44.5 KB
/
registry.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
var azure_iot_common_1 = require("azure-iot-common");
var azure_iot_http_base_1 = require("azure-iot-http-base");
var ConnectionString = require("./connection_string");
var twin_1 = require("./twin");
var query_1 = require("./query");
var device_1 = require("./device");
// tslint:disable-next-line:no-var-requires
var packageJson = require('../package.json');
var ArgumentError = azure_iot_common_1.errors.ArgumentError;
/**
* The Registry class provides access to the IoT Hub device identity service.
* Users of the SDK should instantiate this class with one of the factory methods:
* {@link azure-iothub.Registry.fromConnectionString|fromConnectionString} or {@link azure-iothub.Registry.fromSharedAccessSignature|fromSharedAccessSignature}.
*
* The protocol used for device identity registry operations is HTTPS.
*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_05_001: [The Registry constructor shall accept a transport object]*/
var Registry = (function () {
/**
* @private
* @constructor
* @param {Object} config An object containing the necessary information to connect to the IoT Hub instance:
* - host: the hostname for the IoT Hub instance
* - sharedAccessSignature: A shared access signature with valid access rights and expiry.
*/
function Registry(config, restApiClient) {
if (!config) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_023: [The `Registry` constructor shall throw a `ReferenceError` if the config object is falsy.]*/
throw new ReferenceError('The \'config\' parameter cannot be \'' + config + '\'');
}
else if (!config.host || !config.sharedAccessSignature) {
/*SRS_NODE_IOTHUB_REGISTRY_05_001: [** The `Registry` constructor shall throw an `ArgumentException` if the config object is missing one or more of the following properties:
- `host`: the IoT Hub hostname
- `sharedAccessSignature`: shared access signature with the permissions for the desired operations.]*/
throw new ArgumentError('The \'config\' argument is missing either the host or the sharedAccessSignature property');
}
this._config = config;
/*SRS_NODE_IOTHUB_REGISTRY_16_024: [The `Registry` constructor shall use the `restApiClient` provided as a second argument if it is provided.]*/
/*SRS_NODE_IOTHUB_REGISTRY_16_025: [The `Registry` constructor shall use `azure-iothub.RestApiClient` if no `restApiClient` argument is provided.]*/
// This httpRequestBuilder parameter is used only for unit-testing purposes and should not be used in other situations.
this._restApiClient = restApiClient || new azure_iot_http_base_1.RestApiClient(config, packageJson.name + '/' + packageJson.version);
}
/**
* @method module:azure-iothub.Registry#create
* @description Creates a new device identity on an IoT hub.
* @param {Object} deviceInfo The object must include a `deviceId` property
* with a valid device identifier.
* @param {Function} done The function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* {@link module:azure-iothub.Device|Device}
* object representing the created device
* identity, and a transport-specific response
* object useful for logging or debugging.
*/
Registry.prototype.create = function (deviceInfo, done) {
if (!deviceInfo) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_07_001: [The `create` method shall throw `ReferenceError` if the `deviceInfo` argument is falsy. **]*/
throw new ReferenceError('deviceInfo cannot be \'' + deviceInfo + '\'');
}
else if (!deviceInfo.deviceId) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_07_001: [The create method shall throw ArgumentError if the first argument does not contain a deviceId property.]*/
throw new ArgumentError('The object \'deviceInfo\' is missing the property: deviceId');
}
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_026: [The `create` method shall construct an HTTP request using information supplied by the caller, as follows:
```
PUT /devices/<encodeURIComponent(deviceInfo.deviceId)>?api-version=<version> HTTP/1.1
Authorization: <sharedAccessSignature>
Content-Type: application/json; charset=utf-8
If-Match: *
Request-Id: <guid>
<deviceInfo>
```]*/
var path = azure_iot_common_1.endpoint.devicePath(encodeURIComponent(deviceInfo.deviceId)) + azure_iot_common_1.endpoint.versionQueryString();
var httpHeaders = {
'Content-Type': 'application/json; charset=utf-8'
};
var normalizedDeviceInfo = JSON.parse(JSON.stringify(deviceInfo));
this._normalizeAuthentication(normalizedDeviceInfo);
this._restApiClient.executeApiCall('PUT', path, httpHeaders, normalizedDeviceInfo, function (err, device, httpResponse) {
if (err) {
done(err);
}
else {
done(null, new device_1.Device(device), httpResponse);
}
});
};
/**
* @method module:azure-iothub.Registry#update
* @description Updates an existing device identity on an IoT hub with
* the given device information.
* @param {Object} deviceInfo An object which must include a `deviceId`
* property whose value is a valid device
* identifier.
* @param {Function} done The function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* {@link module:azure-iothub.Device|Device}
* object representing the updated device
* identity, and a transport-specific response
* object useful for logging or debugging.
*/
Registry.prototype.update = function (deviceInfo, done) {
if (!deviceInfo) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_043: [The `update` method shall throw `ReferenceError` if the `deviceInfo` argument is falsy.]*/
throw new ReferenceError('deviceInfo cannot be \'' + deviceInfo + '\'');
}
else if (!deviceInfo.deviceId) {
/* Codes_SRS_NODE_IOTHUB_REGISTRY_07_003: [The update method shall throw ArgumentError if the first argument does not contain a deviceId property.]*/
throw new ArgumentError('The object \'deviceInfo\' is missing the property: deviceId');
}
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_027: [The `update` method shall construct an HTTP request using information supplied by the caller, as follows:
```
PUT /devices/<encodeURIComponent(deviceInfo.deviceId)>?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
<deviceInfo>
```]*/
var path = azure_iot_common_1.endpoint.devicePath(encodeURIComponent(deviceInfo.deviceId)) + azure_iot_common_1.endpoint.versionQueryString();
var httpHeaders = {
'Content-Type': 'application/json; charset=utf-8',
'If-Match': '*'
};
var normalizedDeviceInfo = JSON.parse(JSON.stringify(deviceInfo));
this._normalizeAuthentication(normalizedDeviceInfo);
this._restApiClient.executeApiCall('PUT', path, httpHeaders, normalizedDeviceInfo, function (err, device, httpResponse) {
if (err) {
done(err);
}
else {
done(null, new device_1.Device(device), httpResponse);
}
});
};
/**
* @method module:azure-iothub.Registry#get
* @description Requests information about an existing device identity
* on an IoT hub.
* @param {String} deviceId The identifier of an existing device identity.
* @param {Function} done The function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* {@link module:azure-iothub.Device|Device}
* object representing the created device
* identity, and a transport-specific response
* object useful for logging or debugging.
*/
Registry.prototype.get = function (deviceId, done) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_05_006: [The get method shall throw ReferenceError if the supplied deviceId is falsy.]*/
if (!deviceId) {
throw new ReferenceError('deviceId is \'' + deviceId + '\'');
}
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_028: [The `get` method shall construct an HTTP request using information supplied by the caller, as follows:
```
GET /devices/<encodeURIComponent(deviceInfo.deviceId)>?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Request-Id: <guid>
```]*/
var path = azure_iot_common_1.endpoint.devicePath(encodeURIComponent(deviceId)) + azure_iot_common_1.endpoint.versionQueryString();
this._restApiClient.executeApiCall('GET', path, null, null, function (err, device, httpResponse) {
if (err) {
done(err);
}
else {
done(null, new device_1.Device(device), httpResponse);
}
});
};
/**
* @method module:azure-iothub.Registry#list
* @description Requests information about the first 1000 device
* identities on an IoT hub.
* @param {Function} done The function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), an
* array of
* {@link module:azure-iothub.Device|Device}
* objects representing the listed device
* identities, and a transport-specific response
* object useful for logging or debugging.
*/
Registry.prototype.list = function (done) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_029: [The `list` method shall construct an HTTP request using information supplied by the caller, as follows:
```
GET /devices?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Request-Id: <guid>
```]*/
var path = azure_iot_common_1.endpoint.devicePath('') + azure_iot_common_1.endpoint.versionQueryString();
this._restApiClient.executeApiCall('GET', path, null, null, function (err, devices, httpResponse) {
if (err) {
done(err);
}
else {
done(null, devices ? devices.map(function (device) { return new device_1.Device(device); }) : [], httpResponse);
}
});
};
/**
* @method module:azure-iothub.Registry#delete
* @description Removes an existing device identity from an IoT hub.
* @param {String} deviceId The identifier of an existing device identity.
* @param {Function} done The function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), an
* always-null argument (for consistency with
* the other methods), and a transport-specific
* response object useful for logging or
* debugging.
*/
Registry.prototype.delete = function (deviceId, done) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_07_007: [The delete method shall throw ReferenceError if the supplied deviceId is falsy.]*/
if (!deviceId) {
throw new ReferenceError('deviceId is \'' + deviceId + '\'');
}
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_030: [The `delete` method shall construct an HTTP request using information supplied by the caller, as follows:
```
DELETE /devices/<encodeURIComponent(deviceInfo.deviceId)>?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
If-Match: *
Request-Id: <guid>
```]*/
var path = azure_iot_common_1.endpoint.devicePath(encodeURIComponent(deviceId)) + azure_iot_common_1.endpoint.versionQueryString();
var httpHeaders = {
'If-Match': '*'
};
this._restApiClient.executeApiCall('DELETE', path, httpHeaders, null, done);
};
/**
* @method module:azure-iothub.Registry#addDevices
* @description Adds an array of devices.
*
* @param {Object} devices An array of objects which must include a `deviceId`
* property whose value is a valid device
* identifier.
* @param {Function} done The function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* BulkRegistryOperationResult
* and a transport-specific response object useful
* for logging or debugging.
*/
Registry.prototype.addDevices = function (devices, done) {
this._processBulkDevices(devices, 'create', null, null, null, done);
};
/**
* @method module:azure-iothub.Registry#updateDevices
* @description Updates an array of devices.
*
* @param {Object} devices An array of objects which must include a `deviceId`
* property whose value is a valid device
* identifier.
* @param {boolean} forceUpdate if `forceUpdate` is true then the device will be
* updated regardless of an etag. Otherwise the etags
* must match.
* @param {Function} done The function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* BulkRegistryOperationResult
* and a transport-specific response object useful
* for logging or debugging.
*/
Registry.prototype.updateDevices = function (devices, forceUpdate, done) {
this._processBulkDevices(devices, null, forceUpdate, 'Update', 'UpdateIfMatchETag', done);
};
/**
* @method module:azure-iothub.Registry#removeDevices
* @description Updates an array of devices.
*
* @param {Object} devices An array of objects which must include a `deviceId`
* property whose value is a valid device
* identifier.
* @param {boolean} forceRemove if `forceRemove` is true then the device will be
* removed regardless of an etag. Otherwise the etags
* must match.
* @param {Function} done The function to call when the operation is
* complete. `done` will be called with three
* arguments: an Error object (can be null), a
* BulkRegistryOperationResult
* and a transport-specific response object useful
* for logging or debugging.
*/
Registry.prototype.removeDevices = function (devices, forceRemove, done) {
this._processBulkDevices(devices, null, forceRemove, 'Delete', 'DeleteIfMatchETag', done);
};
/**
* @method module:azure-iothub.Registry#importDevicesFromBlob
* @description Imports devices from a blob in bulk job.
* @param {String} inputBlobContainerUri The URI to a container with a blob named 'devices.txt' containing a list of devices to import.
* @param {String} outputBlobContainerUri The URI to a container where a blob will be created with logs of the import process.
* @param {Function} done The function to call when the job has been created, with two arguments: an error object if an
* an error happened, (null otherwise) and the job status that can be used to track progress of the devices import.
*/
Registry.prototype.importDevicesFromBlob = function (inputBlobContainerUri, outputBlobContainerUri, done) {
/* Codes_SRS_NODE_IOTHUB_REGISTRY_16_001: [A ReferenceError shall be thrown if importBlobContainerUri is falsy] */
if (!inputBlobContainerUri)
throw new ReferenceError('inputBlobContainerUri cannot be falsy');
/* Codes_SRS_NODE_IOTHUB_REGISTRY_16_002: [A ReferenceError shall be thrown if exportBlobContainerUri is falsy] */
if (!outputBlobContainerUri)
throw new ReferenceError('outputBlobContainerUri cannot be falsy');
/*SRS_NODE_IOTHUB_REGISTRY_16_031: [The `importDeviceFromBlob` method shall construct an HTTP request using information supplied by the caller, as follows:
```
POST /jobs/create?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
{
'type': 'import',
'inputBlobContainerUri': '<input container Uri given as parameter>',
'outputBlobContainerUri': '<output container Uri given as parameter>'
}
```]*/
var path = '/jobs/create' + azure_iot_common_1.endpoint.versionQueryString();
var httpHeaders = {
'Content-Type': 'application/json; charset=utf-8'
};
var importRequest = {
'type': 'import',
'inputBlobContainerUri': inputBlobContainerUri,
'outputBlobContainerUri': outputBlobContainerUri
};
this._restApiClient.executeApiCall('POST', path, httpHeaders, importRequest, done);
};
/**
* @method module:azure-iothub.Registry#exportDevicesToBlob
* @description Export devices to a blob in a bulk job.
* @param {String} outputBlobContainerUri The URI to a container where a blob will be created with logs of the export process.
* @param {Boolean} excludeKeys Boolean indicating whether security keys should be excluded from the exported data.
* @param {Function} done The function to call when the job has been created, with two arguments: an error object if an
* an error happened, (null otherwise) and the job status that can be used to track progress of the devices export.
*/
Registry.prototype.exportDevicesToBlob = function (outputBlobContainerUri, excludeKeys, done) {
/* Codes_SRS_NODE_IOTHUB_REGISTRY_16_004: [A ReferenceError shall be thrown if outputBlobContainerUri is falsy] */
if (!outputBlobContainerUri)
throw new ReferenceError('outputBlobContainerUri cannot be falsy');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_032: [** The `exportDeviceToBlob` method shall construct an HTTP request using information supplied by the caller, as follows:
```
POST /jobs/create?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
{
'type': 'export',
'outputBlobContainerUri': '<output container Uri given as parameter>',
'excludeKeysInExport': '<excludeKeys Boolean given as parameter>'
}
```]*/
var path = '/jobs/create' + azure_iot_common_1.endpoint.versionQueryString();
var httpHeaders = {
'Content-Type': 'application/json; charset=utf-8'
};
var exportRequest = {
'type': 'export',
'outputBlobContainerUri': outputBlobContainerUri,
'excludeKeysInExport': excludeKeys
};
this._restApiClient.executeApiCall('POST', path, httpHeaders, exportRequest, done);
};
/**
* @method module:azure-iothub.Registry#listJobs
* @description List the last import/export jobs (including the active one, if any).
* @param {Function} done The function to call with two arguments: an error object if an error happened,
* (null otherwise) and the list of past jobs as an argument.
*/
Registry.prototype.listJobs = function (done) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_037: [The `listJobs` method shall construct an HTTP request using information supplied by the caller, as follows:
```
GET /jobs?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Request-Id: <guid>
```]*/
var path = '/jobs' + azure_iot_common_1.endpoint.versionQueryString();
this._restApiClient.executeApiCall('GET', path, null, null, done);
};
/**
* @method module:azure-iothub.Registry#getJob
* @description Get the status of a bulk import/export job.
* @param {String} jobId The identifier of the job for which the user wants to get status information.
* @param {Function} done The function to call with two arguments: an error object if an error happened,
* (null otherwise) and the status of the job whose identifier was passed as an argument.
*/
Registry.prototype.getJob = function (jobId, done) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_006: [A ReferenceError shall be thrown if jobId is falsy] */
if (!jobId)
throw new ReferenceError('jobId cannot be falsy');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_038: [The `getJob` method shall construct an HTTP request using information supplied by the caller, as follows:
```
GET /jobs/<jobId>?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Request-Id: <guid>
```]*/
var path = '/jobs/' + jobId + azure_iot_common_1.endpoint.versionQueryString();
this._restApiClient.executeApiCall('GET', path, null, null, done);
};
/**
* @method module:azure-iothub.Registry#cancelJob
* @description Cancel a bulk import/export job.
* @param {String} jobId The identifier of the job for which the user wants to get status information.
* @param {Function} done The function to call with two arguments: an error object if an error happened,
* (null otherwise) and the (cancelled) status of the job whose identifier was passed as an argument.
*/
Registry.prototype.cancelJob = function (jobId, done) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_012: [A ReferenceError shall be thrown if the jobId is falsy] */
if (!jobId)
throw new ReferenceError('jobId cannot be falsy');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_039: [The `cancelJob` method shall construct an HTTP request using information supplied by the caller as follows:
```
DELETE /jobs/<jobId>?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Request-Id: <guid>
```]*/
var path = '/jobs/' + jobId + azure_iot_common_1.endpoint.versionQueryString();
this._restApiClient.executeApiCall('DELETE', path, null, null, done);
};
/**
* @method module:azure-iothub.Registry#getTwin
* @description Gets the Device Twin of the device with the specified device identifier.
* @param {String} deviceId The device identifier.
* @param {Function} done The callback that will be called with either an Error object or
* the device twin instance.
*/
Registry.prototype.getTwin = function (deviceId, done) {
var _this = this;
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_019: [The `getTwin` method shall throw a `ReferenceError` if the `deviceId` parameter is falsy.]*/
if (!deviceId)
throw new ReferenceError('the \'deviceId\' cannot be falsy');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_020: [The `getTwin` method shall throw a `ReferenceError` if the `done` parameter is falsy.]*/
if (!done)
throw new ReferenceError('the \'done\' argument cannot be falsy');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_049: [The `getTwin` method shall construct an HTTP request using information supplied by the caller, as follows:
```
GET /twins/<encodeURIComponent(deviceId)>?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Request-Id: <guid>
```]*/
var path = '/twins/' + encodeURIComponent(deviceId) + azure_iot_common_1.endpoint.versionQueryString();
this._restApiClient.executeApiCall('GET', path, null, null, function (err, newTwin, response) {
if (err) {
done(err);
}
else {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_036: [The `getTwin` method shall call the `done` callback with a `Twin` object updated with the latest property values stored in the IoT Hub service.]*/
done(null, new twin_1.Twin(newTwin, _this), response);
}
});
};
/**
* @method module:azure-iothub.Registry#updateTwin
* @description Updates the Device Twin of a specific device with the given patch.
* @param {String} deviceId The device identifier.
* @param {Object} patch The desired properties and tags to patch the device twin with.
* @param {string} etag The latest etag for this device twin or '*' to force an update even if
* the device twin has been updated since the etag was obtained.
* @param {Function} done The callback that will be called with either an Error object or
* the device twin instance.
*/
Registry.prototype.updateTwin = function (deviceId, patch, etag, done) {
var _this = this;
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_044: [The `updateTwin` method shall throw a `ReferenceError` if the `deviceId` argument is `undefined`, `null` or an empty string.]*/
if (deviceId === null || deviceId === undefined || deviceId === '')
throw new ReferenceError('deviceId cannot be \'' + deviceId + '\'');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_045: [The `updateTwin` method shall throw a `ReferenceError` if the `patch` argument is falsy.]*/
if (!patch)
throw new ReferenceError('patch cannot be \'' + patch + '\'');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_046: [The `updateTwin` method shall throw a `ReferenceError` if the `etag` argument is falsy.]*/
if (!etag)
throw new ReferenceError('etag cannot be \'' + etag + '\'');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_048: [The `updateTwin` method shall construct an HTTP request using information supplied by the caller, as follows:
```
PATCH /twins/<encodeURIComponent(deviceId)>?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
If-Match: <etag>
<patch>
```]*/
var path = '/twins/' + encodeURIComponent(deviceId) + azure_iot_common_1.endpoint.versionQueryString();
var headers = {
'Content-Type': 'application/json; charset=utf-8',
'If-Match': etag
};
this._restApiClient.executeApiCall('PATCH', path, headers, patch, function (err, newTwin, response) {
if (err) {
done(err);
}
else {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_050: [The `updateTwin` method shall call the `done` callback with a `Twin` object updated with the latest property values stored in the IoT Hub service.]*/
done(null, new twin_1.Twin(newTwin, _this), response);
}
});
};
/**
* @method module:azure-iothub.Registry#createQuery
* @description Creates a query that can be run on the IoT Hub instance to find information about devices or jobs.
* @param {String} sqlQuery The query written as an SQL string.
* @param {Number} pageSize The desired number of results per page (optional. default: 1000, max: 10000).
*
* @throws {ReferenceError} If the sqlQuery argument is falsy.
* @throws {TypeError} If the sqlQuery argument is not a string or the pageSize argument not a number, null or undefined.
*/
Registry.prototype.createQuery = function (sqlQuery, pageSize) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_051: [The `createQuery` method shall throw a `ReferenceError` if the `sqlQuery` argument is falsy.]*/
if (!sqlQuery)
throw new ReferenceError('sqlQuery cannot be \'' + sqlQuery + '\'');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_052: [The `createQuery` method shall throw a `TypeError` if the `sqlQuery` argument is not a string.]*/
if (typeof sqlQuery !== 'string')
throw new TypeError('sqlQuery must be a string');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_053: [The `createQuery` method shall throw a `TypeError` if the `pageSize` argument is not `null`, `undefined` or a number.]*/
if (pageSize !== null && pageSize !== undefined && typeof pageSize !== 'number')
throw new TypeError('pageSize must be a number or be null or undefined');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_054: [The `createQuery` method shall return a new `Query` instance initialized with the `sqlQuery` and the `pageSize` argument if specified.]*/
return new query_1.Query(this._executeQueryFunc(sqlQuery, pageSize), this);
};
/**
* @method module:azure-iothub.Registry#getRegistryStatistics
* @description Gets statistics about the devices in the device identity registry.
* @param {Function} done The callback that will be called with either an Error object or
* the device registry statistics.
*/
Registry.prototype.getRegistryStatistics = function (done) {
var path = '/statistics/devices' + azure_iot_common_1.endpoint.versionQueryString();
this._restApiClient.executeApiCall('GET', path, {}, null, done);
};
Registry.prototype._bulkOperation = function (devices, done) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_011: [The `addDevices` method shall construct an HTTP request using information supplied by the caller, as follows:
```
POST /devices?api-version=<version> HTTP/1.1
Authorization: <sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
<stringified array supplied by the argument devices annotated with importMode property and deviceId property replaced by id>
```
]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_013: [The `updateDevices` method shall construct an HTTP request using information supplied by the caller, as follows:
```
POST /devices?api-version=<version> HTTP/1.1
Authorization: <sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
<list supplied by the argument devices annotated with importMode property and deviceId property replaced by id>
```
]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_018: [The `removeDevices` method shall construct an HTTP request using information supplied by the caller, as follows:
```
POST /devices?api-version=<version> HTTP/1.1
Authorization: <sharedAccessSignature>
Content-Type: application/json; charset=utf-8
Request-Id: <guid>
<stringified array supplied by the argument devices annotated with importMode property and deviceId property replaced by id>
```
]*/
var path = '/devices' + azure_iot_common_1.endpoint.versionQueryString();
var httpHeaders = {
'Content-Type': 'application/json; charset=utf-8'
};
this._restApiClient.executeApiCall('POST', path, httpHeaders, devices, done);
};
Registry.prototype._processBulkDevices = function (devices, operation, force, forceTrueAlternative, forceFalseAlternative, done) {
var _this = this;
if (!devices) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_004: [The `addDevices` method shall throw `ReferenceError` if the `devices` argument is falsy.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_025: [The `updateDevices` method shall throw `ReferenceError` if the `devices` argument is falsy.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_006: [The `removeDevices` method shall throw `ReferenceError` if the deviceInfo is falsy.]*/
throw new ReferenceError('devices cannot be \'' + devices + '\'');
}
else if (!Array.isArray(devices)) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_021: [The `addDevices` method shall throw `ArgumentError` if devices is NOT an array.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_020: [The `updateDevices` method shall throw `ArgumentError` if devices is NOT an array.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_019: [The `removeDevices` method shall throw `ArgumentError` if devices is NOT an array.]*/
throw new ArgumentError('devices must be an array');
}
else if ((devices.length === 0) || (devices.length > 100)) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_014: [The `addDevices` method shall throw `ArgumentError` if devices.length == 0 or is greater than 100.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_015: [The `updateDevices` method shall throw `ArgumentError` if devices.length == 0 or is greater than 100.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_016: [The `removeDevices` method shall throw `ArgumentError` if devices.length == 0 or is greater than 100.]*/
throw new ArgumentError('The device array has an invalid size of ' + devices.length);
}
else {
var importMode_1;
if (operation === null) {
//
// The api utilizes a force parameter. Check to insure it's present and a boolean.
//
if ((typeof force) !== 'boolean') {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_026: [The `updateDevices` method shall throw `ReferenceError` if the `forceUpdate` parameter is null or undefined.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_027: [The `removeDevices` method shall throw `ReferenceError` if the `forceRemove` parameter is null or undefined.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_024: [The `updateDevices` method shall throw `ReferenceError` if the `forceUpdate` parameter is NOT typeof boolean.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_023: [The `removeDevices` method shall throw `ReferenceError` if the `forceRemove` parameter is NOT typeof boolean.]*/
throw new ReferenceError('force parameter must be present and a boolean');
}
else {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_008: [If the `forceUpdate` parameter is true importMode will be set to `Update` otherwise it will be set to `UpdateIfMatchETag`.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_007: [If the `forceRemove` parameter is true then importMode will be set to `Delete` otherwise it will be set to `DeleteIfMatchETag`.]*/
importMode_1 = force ? forceTrueAlternative : forceFalseAlternative;
}
}
else {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_009: [The `addDevices` method shall utilize an importMode = `create`.]*/
importMode_1 = operation;
}
var bulkArray_1 = [];
devices.forEach(function (currentDevice) {
if (!currentDevice.deviceId) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_010: [The `addDevices` method shall throw `ArgumentError` if any elements of devices do NOT contain a `deviceId` property.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_012: [The `updateDevices` method shall throw `ArgumentError` if any elements of devices do NOT contain a `deviceId` property.]*/
/*Codes_SRS_NODE_IOTHUB_REGISTRY_06_017: [The `removeDevices` method shall throw `ArgumentError` if any elements of devices do NOT contain a `deviceId` property.]*/
throw new ArgumentError('The object is missing the property: deviceId');
}
else {
//
// And now remove the device id and put it back as id.
//
var actualDeviceId = currentDevice.deviceId;
var preparedDevice = JSON.parse(JSON.stringify(currentDevice));
delete preparedDevice.deviceId;
preparedDevice.id = actualDeviceId;
preparedDevice.importMode = importMode_1;
_this._normalizeAuthentication(preparedDevice);
bulkArray_1.push(preparedDevice);
}
});
this._bulkOperation(bulkArray_1, done);
}
};
Registry.prototype._executeQueryFunc = function (sqlQuery, pageSize) {
var _this = this;
return function (continuationToken, done) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_16_057: [The `_executeQueryFunc` method shall construct an HTTP request as follows:
```
POST /devices/query?api-version=<version> HTTP/1.1
Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8
x-ms-continuation: continuationToken
x-ms-max-item-count: pageSize
Request-Id: <guid>
{
query: <sqlQuery>
}
```]*/
var path = '/devices/query' + azure_iot_common_1.endpoint.versionQueryString();
var headers = {
'Content-Type': 'application/json; charset=utf-8'
};
if (continuationToken) {
headers['x-ms-continuation'] = continuationToken;
}
if (pageSize) {
headers['x-ms-max-item-count'] = pageSize;
}
var query = {
query: sqlQuery
};
_this._restApiClient.executeApiCall('POST', path, headers, query, done);
};
};
Registry.prototype._normalizeAuthentication = function (deviceInfo) {
if (!deviceInfo.hasOwnProperty('authentication')) {
/* Codes_SRS_NODE_IOTHUB_REGISTRY_06_028: [A device information with no authentication will be normalized with the following authentication:
authentication : {
type: 'sas',
symmetricKey: {
primaryKey: '',
secondaryKey: ''
}
}
] */
deviceInfo.authentication = {
type: 'sas',
symmetricKey: {
primaryKey: '',
secondaryKey: ''
}
};
/* Codes_SRS_NODE_IOTHUB_REGISTRY_06_029: [** A device information with an authentication object that contains a `type` property is considered normalized.] */
}
else if (!deviceInfo.authentication.hasOwnProperty('type')) {
if (deviceInfo.authentication.x509Thumbprint && (deviceInfo.authentication.x509Thumbprint.primaryThumbprint || deviceInfo.authentication.x509Thumbprint.secondaryThumbprint)) {
/* Codes_SRS_NODE_IOTHUB_REGISTRY_06_030: [A device information with an authentication object that contains the x509Thumbprint property with at least one of `primaryThumbprint` or `secondaryThumbprint` sub-properties will be normalized with a `type` property with value "selfSigned".] */
deviceInfo.authentication.type = 'selfSigned';
}
else {
/* Codes_SRS_NODE_IOTHUB_REGISTRY_06_031: [A device information with an authentication object that doesn't contain the x509Thumbprint property will be normalized with a `type` property with value "sas".] */
deviceInfo.authentication.type = 'sas';
}
}
};
/**
* @method module:azure-iothub.Registry.fromConnectionString
* @description Constructs a Registry object from the given connection string.
* @static
* @param {String} value A connection string which encapsulates the
* appropriate (read and/or write) Registry
* permissions.
* @returns {module:azure-iothub.Registry}
*/
Registry.fromConnectionString = function (value) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_05_008: [The `fromConnectionString` method shall throw `ReferenceError` if the value argument is falsy.]*/
if (!value)
throw new ReferenceError('value is \'' + value + '\'');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_05_009: [The `fromConnectionString` method shall derive and transform the needed parts from the connection string in order to create a `config` object for the constructor (see `SRS_NODE_IOTHUB_REGISTRY_05_001`).]*/
var cn = ConnectionString.parse(value);
var config = {
host: cn.HostName,
sharedAccessSignature: azure_iot_common_1.SharedAccessSignature.create(cn.HostName, cn.SharedAccessKeyName, cn.SharedAccessKey, Date.now())
};
/*Codes_SRS_NODE_IOTHUB_REGISTRY_05_010: [The `fromConnectionString` method shall return a new instance of the `Registry` object.]*/
return new Registry(config);
};
/**
* @method module:azure-iothub.Registry.fromSharedAccessSignature
* @description Constructs a Registry object from the given shared access signature.
* @static
*
* @param {String} value A shared access signature which encapsulates
* the appropriate (read and/or write) Registry
* permissions.
* @returns {module:azure-iothub.Registry}
*/
Registry.fromSharedAccessSignature = function (value) {
/*Codes_SRS_NODE_IOTHUB_REGISTRY_05_011: [The `fromSharedAccessSignature` method shall throw ReferenceError if the value argument is falsy.]*/
if (!value)
throw new ReferenceError('value is \'' + value + '\'');
/*Codes_SRS_NODE_IOTHUB_REGISTRY_05_012: [The `fromSharedAccessSignature` method shall derive and transform the needed parts from the shared access signature in order to create a `config` object for the constructor (see `SRS_NODE_IOTHUB_REGISTRY_05_001`).]*/
var sas = azure_iot_common_1.SharedAccessSignature.parse(value);
var config = {
host: sas.sr,
sharedAccessSignature: sas.toString()
};
/*Codes_SRS_NODE_IOTHUB_REGISTRY_05_013: [The fromSharedAccessSignature method shall return a new instance of the `Registry` object.]*/
return new Registry(config);
};
return Registry;
}());
exports.Registry = Registry;
//# sourceMappingURL=registry.js.map