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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293 |
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
14
14
14
14
14
14
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
4
1
3
1
1
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
1
1
1
1
3
1
115
115
115
115
113
108
108
108
108
108
108
112
112
112
112
106
112
108
112
108
1
1
1
1
1
1
1
1
1
1
1
1
1
1
163
163
163
163
163
163
163
163
163
163
169
163
169
163
1
83
83
83
83
83
83
83
83
83
83
83
16
16
67
67
67
67
67
1
52
52
52
52
52
52
52
52
52
52
33
33
31
52
2
2
52
52
52
52
52
52
52
52
3
52
52
52
52
1
47
47
47
47
47
1
102
1
2
1
2
1
3
1
6
1
2
1
22
22
22
22
22
22
22
22
1
21
21
21
21
21
21
21
21
21
3
18
21
21
21
21
1
87
87
87
87
87
87
87
87
3
87
87
87
87
70
17
17
17
17
87
87
87
87
1
164
164
164
164
164
164
164
164
164
164
164
164
164
164
164
164
164
2
2
162
162
160
162
162
164
164
1 | //
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Module dependencies.
var util = require('util');
var extend = require('extend');
var _ = require('underscore');
var azureCommon = require('./../../common/common');
var azureutil = azureCommon.util;
var validate = azureCommon.validate;
var SR = azureCommon.SR;
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKeyTable = require('./internal/sharedkeytable');
var RequestHandler = require('./internal/requesthandler');
var TableQuery = require('./tablequery');
var WebResource = azureCommon.WebResource;
var Constants = azureCommon.Constants;
var QueryStringConstants = Constants.QueryStringConstants;
var HeaderConstants = Constants.HeaderConstants;
var TableConstants = Constants.TableConstants;
var RequestLocationMode = Constants.RequestLocationMode;
// Models requires
var tableResult = require('./models/tableresult');
var entityResult = require('./models/entityresult');
var BatchResult = require('./models/batchresult');
var ServiceStatsParser = azureCommon.ServiceStatsParser;
var AclResult = azureCommon.AclResult;
var TableUtilities = require('./tableutilities');
/**
* Creates a new TableService object.
* If no connection string or storageaccount and storageaccesskey are provided,
* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used.
* @class
* The TableService object allows you to peform management operations with the Microsoft Azure Table Service.
* The Table Service stores data in rows of key-value pairs. A table is composed of multiple rows, and each row
* contains key-value pairs. There is no schema, so each row in a table may store a different set of keys.
*
* For more information on the Table Service, as well as task focused information on using it from a Node.js application, see
* [How to Use the Table Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-table-storage/).
* The following defaults can be set on the Table service.
* defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Table service.
* defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Table service.
* defaultLocationMode The default location mode for requests made via the Table service.
* defaultPayloadFormat The default payload format for requests made via the Table service.
* useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Table service.; true to use the
* Nagle algorithm; otherwise, false. The default value is false.
* @constructor
* @extends {StorageServiceClient}
*
* @param {string} [storageAccountOrConnectionString] The storage account or the connection string.
* @param {string} [storageAccessKey] The storage access key.
* @param {string|object} [host] The host address. To define primary only, pass a string.
* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} [sasToken] The Shared Access Signature token.
*/
function TableService(storageAccountOrConnectionString, storageAccessKey, host, sasToken) {
var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken);
TableService['super_'].call(this,
storageServiceSettings._name,
storageServiceSettings._key,
storageServiceSettings._tableEndpoint,
storageServiceSettings._usePathStyleUri,
storageServiceSettings._sasToken);
Iif (this.anonymous) {
throw new Error(SR.ANONYMOUS_ACCESS_BLOBSERVICE_ONLY);
}
Eif(this.storageAccount && this.storageAccessKey) {
this.storageCredentials = new SharedKeyTable(this.storageAccount, this.storageAccessKey, this.usePathStyleUri);
}
this.defaultPayloadFormat = TableUtilities.PayloadFormat.MINIMAL_METADATA;
}
util.inherits(TableService, StorageServiceClient);
// Table service methods
/**
* Gets the service stats for a storage account’s Table service.
*
* @this {TableService}
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the properties.
* `response` will contain information related to this operation.
*/
TableService.prototype.getServiceStats = function (optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getServiceStats', function (v) {
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var webResource = WebResource.get()
.withQueryOption(QueryStringConstants.COMP, 'stats')
.withQueryOption(QueryStringConstants.RESTYPE, 'service');
var processResponseCallback = function (responseObject, next) {
responseObject.serviceStatsResult = null;
Eif (!responseObject.error) {
responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats);
}
// function to be called after all filters
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response);
};
// call the first filter
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Gets the properties of a storage account’s Table service, including Azure Storage Analytics.
*
* @this {TableService}
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the properties.
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.getServiceProperties = function (optionsOrCallback, callback) {
return this.getAccountServiceProperties(optionsOrCallback, callback);
};
/**
* Sets the properties of a storage account’s Table service, including Azure Storage Analytics.
* You can also use this operation to set the default request version for all incoming requests that do not have a version specified.
*
* @this {TableService}
* @param {object} serviceProperties The service properties.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information if an error occurs;
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) {
return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback);
};
/**
* Lists a segment containing a collection of table items under the specified account.
*
* @this {TableService}
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The create options or callback function.
* @param {int} [options.maxResults] Specifies the maximum number of tables to return per call to Azure ServiceClient.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of tables and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.listTablesSegmented = function (currentToken, optionsOrCallback, callback) {
this.listTablesSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback);
};
/**
* Lists a segment containing a collection of table items under the specified account.
*
* @this {TableService}
* @param {string} prefix The prefix of the table name.
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The create options or callback function.
* @param {int} [options.maxResults] Specifies the maximum number of tables to return per call to Azure ServiceClient.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of tables and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.listTablesSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('listTables', function (v) {
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat;
var webResource = WebResource.get(TableConstants.TABLE_SERVICE_TABLE_NAME);
RequestHandler.setTableRequestHeadersAndBody(webResource, null, options.payloadFormat);
Iif(!azureutil.objectIsNull(currentToken)) {
webResource.withQueryOption(TableConstants.NEXT_TABLE_NAME, currentToken.nextTableName);
}
Eif(!azureutil.objectIsNull(prefix)) {
var query = new TableQuery()
.where(TableConstants.TABLE_NAME + ' >= ?', prefix)
.and(TableConstants.TABLE_NAME + ' < ?', prefix + '{');
webResource.withQueryOption(QueryStringConstants.FILTER, query.toQueryObject().$filter);
}
Iif(!azureutil.objectIsNull(options.maxResults)) {
var query = TableQuery.top(options.maxResults);
webResource.withQueryOption(QueryStringConstants.TOP, query.toQueryObject().$top);
}
options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
var processResponseCallback = function (responseObject, next) {
responseObject.listTablesResult = null;
Eif (!responseObject.error) {
responseObject.listTablesResult = {
entries: null,
continuationToken: null
};
responseObject.listTablesResult.entries = tableResult.parse(responseObject.response);
Iif (responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME] &&
!azureutil.objectIsEmpty(responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME])) {
responseObject.listTablesResult.continuationToken = {
nextTableName: null,
targetLocation: null
};
responseObject.listTablesResult.continuationToken.nextTableName = responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME];
responseObject.listTablesResult.continuationToken.targetLocation = responseObject.targetLocation;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.listTablesResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
// Table Methods
/**
* Gets the table's ACL.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the ACL information for the table.
* `response` will contain information related to this operation.
*/
TableService.prototype.getTableAcl = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getTableAcl', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var webResource = WebResource.get(table)
.withQueryOption(QueryStringConstants.COMP, 'acl');
var processResponseCallback = function (responseObject, next) {
responseObject.tableResult = null;
if (!responseObject.error) {
responseObject.tableResult = tableResult.parse(responseObject.response, true);
responseObject.tableResult.signedIdentifiers = AclResult.parse(responseObject.response.body);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.tableResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Updates the table's ACL.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} signedIdentifiers The signed identifiers. Signed identifiers must be in an array.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain information for the table.
* `response` will contain information related to this operation.
*/
TableService.prototype.setTableAcl = function (table, signedIdentifiers, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('setTableAcl', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var policies = null;
if (signedIdentifiers) {
if (!_.isArray(signedIdentifiers)) {
throw new Error(SR.INVALID_SIGNED_IDENTIFIERS);
}
policies = AclResult.serialize(signedIdentifiers);
}
var webResource = WebResource.put(table)
.withQueryOption(QueryStringConstants.COMP, 'acl')
.withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0)
.withBody(policies);
var processResponseCallback = function (responseObject, next) {
responseObject.tableResult = null;
if (!responseObject.error) {
// SetTableAcl doesn't actually return anything in the response
responseObject.tableResult = {TableName : table};
if (signedIdentifiers) {
responseObject.tableResult.signedIdentifiers = signedIdentifiers;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.tableResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
/**
* Retrieves a shared access signature token.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} sharedAccessPolicy The shared access policy.
* @param {string} [sharedAccessPolicy.Id] The signed identifier.
* @param {object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type.
* @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used).
* @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used).
* @param {string} [sharedAccessPolicy.AccessPolicy.StartPk] The starting Partition Key for which the SAS will be valid.
* @param {string} [sharedAccessPolicy.AccessPolicy.EndPk] The ending Partition Key for which the SAS will be valid.
* @param {string} [sharedAccessPolicy.AccessPolicy.StartRk] The starting Row Key for which the SAS will be valid.
* @param {string} [sharedAccessPolicy.AccessPolicy.EndRk] The ending Row Key for which the SAS will be valid.
* @return {object} An object with the shared access signature.
*/
TableService.prototype.generateSharedAccessSignature = function (table, sharedAccessPolicy) {
// check if the TableService is able to generate a shared access signature
if (!this.storageCredentials || !this.storageCredentials.generateSignedQueryString) {
throw new Error(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY);
}
validate.validateArgs('generateSharedAccessSignature', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.object(sharedAccessPolicy, 'sharedAccessPolicy');
});
return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.Table, table , sharedAccessPolicy, null, {tableName: table });
};
/**
* Checks whether or not a table exists on the service.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain be true if the table exists, or false if the table does not exist.
* `response` will contain information related to this operation.
*/
TableService.prototype.doesTableExist = function (table, optionsOrCallback, callback) {
this._doesTableExist(table, false, optionsOrCallback, callback);
};
/**
* Creates a new table within a storage account.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the new table information.
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.createTable = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createTable', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var tableDescriptor = tableResult.serialize(table);
var webResource = WebResource.post('Tables')
.withHeader(HeaderConstants.PREFER, HeaderConstants.PREFER_NO_CONTENT);
RequestHandler.setTableRequestHeadersAndBody(webResource, tableDescriptor);
var processResponseCallback = function (responseObject, next) {
responseObject.tableResponse = {};
responseObject.tableResponse.isSuccessful = responseObject.error ? false : true;
responseObject.tableResponse.statusCode = responseObject.response.statusCode;
if (!responseObject.error) {
responseObject.tableResponse.TableName = table;
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.tableResponse, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
/**
* Creates a new table within a storage account if it does not exists.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* `result` will be `true` if table was created, false otherwise
* `response` will contain information related to this operation.
* @return {undefined}
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* tableService.createTableIfNotExists('tasktable', function(error) {
* if(!error) {
* // Table created or exists
* }
* });
*/
TableService.prototype.createTableIfNotExists = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createTableIfNotExists', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
self._doesTableExist(table, true, options, function(error, exists, response) {
Iif (error) {
callback(error, exists, response);
} else Eif (exists) {
callback(error, false, response);
} else {
self.createTable(table, options, function(createError, createResponse) {
var created;
if (!createError) {
created = true;
}
else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.TableErrorCodeStrings.TABLE_ALREADY_EXISTS) {
createError = null;
created = false;
createResponse.isSuccessful = true;
}
callback(createError, created, createResponse);
});
}
});
};
/**
* Deletes a table from a storage account.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information if an error occurs;
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.deleteTable = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('deleteTable', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.del('Tables(\'' + table + '\')');
RequestHandler.setTableRequestHeadersAndBody(webResource);
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Deletes a table from a storage account, if it exists.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* `result` will be `true` if table was deleted, false otherwise
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.deleteTableIfExists = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('deleteTableIfExists', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
self._doesTableExist(table, true, options, function(error, exists, response) {
Iif (error) {
callback(error, exists, response);
} else if (!exists) {
response.isSuccessful = true;
callback(error, false, response);
} else {
self.deleteTable(table, options, function(deleteError, deleteResponse) {
var deleted;
Eif (!deleteError) {
deleted = true;
} else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.StorageErrorCodeStrings.RESOURCE_NOT_FOUND) {
deleted = false;
deleteError = null;
deleteResponse.isSuccessful = true;
}
callback(deleteError, deleted, deleteResponse);
});
}
});
};
// Table Entity Methods
/**
* Queries data in a table. To retrieve a single entity by partition key and row key, use retrieve entity.
*
* @this {TableService}
* @param {string} table The table name.
* @param {TableQuery} tableQuery The query to perform. Use null, undefined, or new TableQuery() to get all of the entities in the table.
* @param {object} currentToken A continuation token returned by a previous listing operation.
* Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {bool} [options.autoResolveProperties] If true, guess at all property types.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {Function(entity)} [options.entityResolver] The entity resolver. Given a single entity returned by the query, returns a modified object which is added to
* the entities array.
* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value,
* and the property Edm type if given by the service, returns the Edm type of the property.
* @param {TableService~queryResponse} callback `error` will contain information if an error occurs;
* otherwise `entities` will contain the entities returned by the query.
* If more matching entities exist, and could not be returned,
* `queryResultContinuation` will contain a continuation token that can be used
* to retrieve the next set of results.
* `response` will contain information related to this operation.
* @return {undefined}
*
* The logic for returning entity types can get complicated. Here is the algorithm used:
* ```
* var propertyType;
*
* if (propertyResovler) { // If the caller provides a propertyResolver in the options, use it
* propertyType = propertyResolver(partitionKey, rowKey, propertyName, propertyValue, propertyTypeFromService);
* } else if (propertyTypeFromService) { // If the service provides us a property type, use it. See below for an explanation of when this will and won't occur.
* propertyType = propertyTypeFromService;
* } else if (autoResolveProperties) { // If options.autoResolveProperties is set to true
* if (javascript type is string) { // See below for an explanation of how and why autoResolveProperties works as it does.
* propertyType = 'Edm.String';
* } else if (javascript type is boolean) {
* propertyType = 'Edm.Boolean';
* }
* }
*
* if (propertyType) {
* // Set the property type on the property.
* } else {
* // Property gets no EdmType.
* }
* ```
* Notes:
*
* * The service only provides a type if JsonFullMetadata or JsonMinimalMetadata is used, and if the type is Int64, Guid, Binary, or DateTime.
* * Explanation of autoResolveProperties:
* * String gets correctly resolved to 'Edm.String'.
* * Int64, Guid, Binary, and DateTime all get resolved to 'Edm.String.' This only happens if JsonNoMetadata is used (otherwise the service will provide the propertyType in a prior step).
* * Boolean gets correctly resolved to 'Edm.Boolean'.
* * For both Int32 and Double, no type information is returned, even in the case of autoResolveProperties = true. This is due to an
* inability to distinguish between the two in certain cases.
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* // tasktable should already exist and have entities
*
* // returns all entities in tasktable, and a continuation token for the next page of results if necessary
* tableService.queryEntities('tasktable', null, null \/*currentToken*\/, function(error, result) {
* if(!error) {
* var entities = result.entities;
* // do stuff with the returned entities if there are any
* }
* });
*
* // returns field1 and field2 of the entities in tasktable, and a continuation token for the next page of results if necessary
* var tableQuery = new TableQuery().select('field1', 'field2');
* tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result) {
* if(!error) {
* var entities = result.entities;
* // do stuff with the returned entities if there are any
* }
* });
*/
TableService.prototype.queryEntities = function (table, tableQuery, currentToken, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('queryEntities', function (v) {
v.string(table, 'table');
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat;
var webResource = WebResource.get(table);
RequestHandler.setTableRequestHeadersAndBody(webResource, null, options.payloadFormat);
if (tableQuery) {
var queryString = tableQuery.toQueryObject();
Object.keys(queryString).forEach(function (queryStringName) {
webResource.withQueryOption(queryStringName, queryString[queryStringName]);
});
}
if(!azureutil.objectIsNull(currentToken)) {
webResource.withQueryOption(TableConstants.NEXT_PARTITION_KEY, currentToken.nextPartitionKey);
webResource.withQueryOption(TableConstants.NEXT_ROW_KEY, currentToken.nextRowKey);
}
options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
var processResponseCallback = function (responseObject, next) {
responseObject.queryEntitiesResult = null;
Eif (!responseObject.error) {
responseObject.queryEntitiesResult = {
entries: null,
continuationToken: null
};
// entries
responseObject.queryEntitiesResult.entries = entityResult.parseQuery(responseObject.response, options.autoResolveProperties, options.propertyResolver, options.entityResolver);
// continuation token
var continuationToken = {
nextPartitionKey: responseObject.response.headers[TableConstants.CONTINUATION_NEXT_PARTITION_KEY],
nextRowKey: responseObject.response.headers[TableConstants.CONTINUATION_NEXT_ROW_KEY],
targetLocation: responseObject.targetLocation
};
if (!azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(continuationToken.nextPartitionKey)) {
responseObject.queryEntitiesResult.continuationToken = continuationToken;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.queryEntitiesResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Retrieves an entity from a table.
*
* @this {TableService}
* @param {string} table The table name.
* @param {string} partitionKey The partition key.
* @param {string} rowKey The row key.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value,
* and the property Edm type if given by the service, returns the Edm type of the property.
* @param {Function(entity)} [options.entityResolver] The entity resolver. Given the single entity returned by the query, returns a modified object.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will be the matching entity.
* `response` will contain information related to this operation.
* @return {undefined}
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* tableService.retrieveEntity('tasktable', 'tasksSeattle', '1', function(error, serverEntity) {
* if(!error) {
* // Entity available in serverEntity variable
* }
* });
*/
TableService.prototype.retrieveEntity = function (table, partitionKey, rowKey, optionsOrCallback, callback) {
var entityDescriptor = { PartitionKey: {_: partitionKey, $: 'Edm.String'},
RowKey: {_: rowKey, $: 'Edm.String'},
};
validate.validateArgs('retrieveEntity', function (v) {
v.stringAllowEmpty(partitionKey, 'partitionKey');
v.stringAllowEmpty(rowKey, 'rowKey');
});
this._performEntityOperation(TableConstants.Operations.RETRIEVE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Inserts a new entity into a table.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {string} [options.echoContent] Whether or not to return the entity upon a successful insert. Default to false.
* @param {string} [options.payloadFormat] The payload format to use in the response, if options.echoContent is true.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Only applied if echoContent is true. Given the partition key, row key, property name,
* property value, and the property Edm type if given by the service, returns the Edm type of the property.
* @param {Function(entity)} [options.entityResolver] The entity resolver. Only applied if echoContent is true. Given the single entity returned by the insert, returns
* a modified object.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* `response` will contain information related to this operation.
* @return {undefined}
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* var task1 = {
* PartitionKey : {'_': 'tasksSeattle', '$':'Edm.String'},
* RowKey: {'_': '1', '$':'Edm.String'},
* Description: {'_': 'Take out the trash', '$':'Edm.String'},
* DueDate: {'_': new Date(2011, 12, 14, 12), '$':'Edm.DateTime'}
* };
* tableService.insertEntity('tasktable', task1, function(error) {
* if(!error) {
* // Entity inserted
* }
* });
*/
TableService.prototype.insertEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.INSERT, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Inserts or updates a new entity into a table.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.insertOrReplaceEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.INSERT_OR_REPLACE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Updates an existing entity within a table by replacing it. To update conditionally based on etag, set entity['.metadata']['etag'].
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.updateEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.UPDATE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Updates an existing entity within a table by merging new property values into the entity. To merge conditionally based on etag, set entity['.metadata']['etag'].
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.mergeEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.MERGE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Inserts or updates an existing entity within a table by merging new property values into the entity.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.insertOrMergeEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.INSERT_OR_MERGE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Deletes an entity within a table. To delete conditionally based on etag, set entity['.metadata']['etag'].
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information if an error occurs;
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.deleteEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.DELETE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Executes the operations in the batch.
*
* @this {TableService}
* @param {string} table The table name.
* @param {TableBatch} batch The table batch to execute.
* @param {object} [options] The create options or callback function.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain responses for each operation executed in the batch;
* `result.entity` will contain the entity information for each operation executed.
* `result.response` will contain the response for each operations executed.
* `response` will contain information related to this operation.
* @return {undefined}
*/
TableService.prototype.executeBatch = function (table, batch, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('executeBatch', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.object(batch, 'batch');
v.callback(callback);
});
if(!batch.hasOperations()) {
throw new Error(SR.EMPTY_BATCH);
}
var options = extend(true, {}, userOptions);
var batchResult = new BatchResult(this, table, batch.operations);
var webResource = batchResult.constructWebResource();
var body = batchResult.serialize();
webResource.withBody(body);
webResource.withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(body, 'utf8'));
var processResponseCallback = function (responseObject, next) {
var responseObjects = batchResult.parse(responseObject);
// if the batch was unsuccesful, there will be a single response indicating the error
if (responseObjects && responseObjects.length > 0 && !responseObjects[0].response.isSuccessful) {
responseObject = responseObjects[0];
} else {
responseObject.operationResponses = responseObjects;
}
var finalCallback = function (returnObject) {
// perform final callback
callback(returnObject.error, returnObject.operationResponses, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
// Private methods
/**
* Checks whether or not a table exists on the service.
* @ignore
*
* @this {TableService}
* @param {string} table The table name.
* @param {string} primaryOnly If true, the request will be executed against the primary storage location.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain be true if the table exists, or false if the table does not exist.
* `response` will contain information related to this operation.
*/
TableService.prototype._doesTableExist = function (table, primaryOnly, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('doesTableExist', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
if(primaryOnly === false) {
options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
}
var webResource = WebResource.get('Tables(\'' + table + '\')');
RequestHandler.setTableRequestHeadersAndBody(webResource);
var processResponseCallback = function (responseObject, next) {
if(!responseObject.error){
responseObject.exists = true;
} else Eif (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
responseObject.error = null;
responseObject.exists = false;
responseObject.response.isSuccessful = true;
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.exists, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Peforms a table operation.
*
* @this {TableService}
* @param {string} operation The operation to perform.
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The create options or callback function.
* @param {string} [options.echoContent] Whether or not to return the entity upon a successful insert. Default to false.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `entity` will contain the entity information.
* `response` will contain information related to this operation.
* @return {undefined}
* @ignore
*/
TableService.prototype._performEntityOperation = function (operation, table, entityDescriptor, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('entityOperation', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.object(entityDescriptor, 'entityDescriptor');
v.object(entityDescriptor.PartitionKey, 'entityDescriptor.PartitionKey');
v.object(entityDescriptor.RowKey, 'entityDescriptor.RowKey');
v.stringAllowEmpty(entityDescriptor.PartitionKey._, 'entityDescriptor.PartitionKey._');
v.stringAllowEmpty(entityDescriptor.RowKey._, 'entityDescriptor.RowKey._');
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat;
var webResource = RequestHandler.constructEntityWebResource(operation, table, entityDescriptor, options);
var processResponseCallback = function (responseObject, next) {
var finalCallback;
if (operation === TableConstants.Operations.DELETE) {
finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
} else {
responseObject.entityResponse = null;
if (!responseObject.error) {
responseObject.entityResponse = entityResult.parseEntity(responseObject.response, options.autoResolveProperties, options.propertyResolver, options.entityResolver);
}
finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.entityResponse, returnObject.response);
};
}
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
/**
* Given the partition key, row key, property name, property value,
* and the property Edm type if given by the service, returns the Edm type of the property.
* @typedef {function} TableService~propertyResolver
* @param {object} pk The partition key.
* @param {object} rk The row key.
* @param {string} name The property name.
* @param {object} value The property value.
* @param {string} type The EDM type.
*/
/**
* Returns entities matched by a query.
* @callback TableService~queryResponse
* @param {object} error If an error occurs, the error information.
* @param {object} entities The entities returned by the query.
* @param {object} queryResultContinuation If more matching entities exist, and could not be returned,
* a continuation token that can be used to retrieve more results.
* @param {object} response Information related to this operation.
*/
module.exports = TableService; |