utils.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // Licensed under the MIT License. See License.txt in the project root for license information.
  3. import uuidv4 from "uuid/v4";
  4. import { Constants } from "./constants";
  5. /**
  6. * A constant that indicates whether the environment is node.js or browser based.
  7. */
  8. export var isNode = (typeof process !== "undefined") && !!process.version && !!process.versions && !!process.versions.node;
  9. /**
  10. * Checks if a parsed URL is HTTPS
  11. *
  12. * @param {object} urlToCheck The url to check
  13. * @return {boolean} True if the URL is HTTPS; false otherwise.
  14. */
  15. export function urlIsHTTPS(urlToCheck) {
  16. return urlToCheck.protocol.toLowerCase() === Constants.HTTPS;
  17. }
  18. /**
  19. * Encodes an URI.
  20. *
  21. * @param {string} uri The URI to be encoded.
  22. * @return {string} The encoded URI.
  23. */
  24. export function encodeUri(uri) {
  25. return encodeURIComponent(uri)
  26. .replace(/!/g, "%21")
  27. .replace(/"/g, "%27")
  28. .replace(/\(/g, "%28")
  29. .replace(/\)/g, "%29")
  30. .replace(/\*/g, "%2A");
  31. }
  32. /**
  33. * Returns a stripped version of the Http Response which only contains body,
  34. * headers and the status.
  35. *
  36. * @param {HttpOperationResponse} response The Http Response
  37. *
  38. * @return {object} The stripped version of Http Response.
  39. */
  40. export function stripResponse(response) {
  41. var strippedResponse = {};
  42. strippedResponse.body = response.bodyAsText;
  43. strippedResponse.headers = response.headers;
  44. strippedResponse.status = response.status;
  45. return strippedResponse;
  46. }
  47. /**
  48. * Returns a stripped version of the Http Request that does not contain the
  49. * Authorization header.
  50. *
  51. * @param {WebResource} request The Http Request object
  52. *
  53. * @return {WebResource} The stripped version of Http Request.
  54. */
  55. export function stripRequest(request) {
  56. var strippedRequest = request.clone();
  57. if (strippedRequest.headers) {
  58. strippedRequest.headers.remove("authorization");
  59. }
  60. return strippedRequest;
  61. }
  62. /**
  63. * Validates the given uuid as a string
  64. *
  65. * @param {string} uuid The uuid as a string that needs to be validated
  66. *
  67. * @return {boolean} True if the uuid is valid; false otherwise.
  68. */
  69. export function isValidUuid(uuid) {
  70. var validUuidRegex = new RegExp("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", "ig");
  71. return validUuidRegex.test(uuid);
  72. }
  73. /**
  74. * Provides an array of values of an object. For example
  75. * for a given object { "a": "foo", "b": "bar" }, the method returns ["foo", "bar"].
  76. *
  77. * @param {object} obj An object whose properties need to be enumerated so that it"s values can be provided as an array
  78. *
  79. * @return {any[]} An array of values of the given object.
  80. */
  81. export function objectValues(obj) {
  82. var result = [];
  83. if (obj && obj instanceof Object) {
  84. for (var key in obj) {
  85. if (obj.hasOwnProperty(key)) {
  86. result.push(obj[key]);
  87. }
  88. }
  89. }
  90. else {
  91. throw new Error("The provided object " + JSON.stringify(obj, undefined, 2) + " is not a valid object that can be " +
  92. "enumerated to provide its values as an array.");
  93. }
  94. return result;
  95. }
  96. /**
  97. * Generated UUID
  98. *
  99. * @return {string} RFC4122 v4 UUID.
  100. */
  101. export function generateUuid() {
  102. return uuidv4();
  103. }
  104. /**
  105. * Executes an array of promises sequentially. Inspiration of this method is here:
  106. * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!
  107. *
  108. * @param {Array} promiseFactories An array of promise factories(A function that return a promise)
  109. *
  110. * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain.
  111. * If not provided then the promise chain starts with undefined.
  112. *
  113. * @return A chain of resolved or rejected promises
  114. */
  115. export function executePromisesSequentially(promiseFactories, kickstart) {
  116. var result = Promise.resolve(kickstart);
  117. promiseFactories.forEach(function (promiseFactory) {
  118. result = result.then(promiseFactory);
  119. });
  120. return result;
  121. }
  122. /**
  123. * Merges source object into the target object
  124. * @param {object} source The object that needs to be merged
  125. *
  126. * @param {object} target The object to be merged into
  127. *
  128. * @returns {object} Returns the merged target object.
  129. */
  130. export function mergeObjects(source, target) {
  131. Object.keys(source).forEach(function (key) {
  132. target[key] = source[key];
  133. });
  134. return target;
  135. }
  136. /**
  137. * A wrapper for setTimeout that resolves a promise after t milliseconds.
  138. * @param {number} t The number of milliseconds to be delayed.
  139. * @param {T} value The value to be resolved with after a timeout of t milliseconds.
  140. * @returns {Promise<T>} Resolved promise
  141. */
  142. export function delay(t, value) {
  143. return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });
  144. }
  145. /**
  146. * Converts a Promise to a callback.
  147. * @param {Promise<any>} promise The Promise to be converted to a callback
  148. * @returns {Function} A function that takes the callback (cb: Function): void
  149. * @deprecated generated code should instead depend on responseToBody
  150. */
  151. export function promiseToCallback(promise) {
  152. if (typeof promise.then !== "function") {
  153. throw new Error("The provided input is not a Promise.");
  154. }
  155. return function (cb) {
  156. promise.then(function (data) {
  157. cb(undefined, data);
  158. }, function (err) {
  159. cb(err);
  160. });
  161. };
  162. }
  163. /**
  164. * Converts a Promise to a service callback.
  165. * @param {Promise<HttpOperationResponse>} promise - The Promise of HttpOperationResponse to be converted to a service callback
  166. * @returns {Function} A function that takes the service callback (cb: ServiceCallback<T>): void
  167. */
  168. export function promiseToServiceCallback(promise) {
  169. if (typeof promise.then !== "function") {
  170. throw new Error("The provided input is not a Promise.");
  171. }
  172. return function (cb) {
  173. promise.then(function (data) {
  174. process.nextTick(cb, undefined, data.parsedBody, data.request, data);
  175. }, function (err) {
  176. process.nextTick(cb, err);
  177. });
  178. };
  179. }
  180. export function prepareXMLRootList(obj, elementName) {
  181. var _a;
  182. if (!Array.isArray(obj)) {
  183. obj = [obj];
  184. }
  185. return _a = {}, _a[elementName] = obj, _a;
  186. }
  187. /**
  188. * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor
  189. * @param {object} targetCtor The target object on which the properties need to be applied.
  190. * @param {Array<object>} sourceCtors An array of source objects from which the properties need to be taken.
  191. */
  192. export function applyMixins(targetCtor, sourceCtors) {
  193. sourceCtors.forEach(function (sourceCtors) {
  194. Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) {
  195. targetCtor.prototype[name] = sourceCtors.prototype[name];
  196. });
  197. });
  198. }
  199. var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  200. /**
  201. * Indicates whether the given string is in ISO 8601 format.
  202. * @param {string} value The value to be validated for ISO 8601 duration format.
  203. * @return {boolean} `true` if valid, `false` otherwise.
  204. */
  205. export function isDuration(value) {
  206. return validateISODuration.test(value);
  207. }
  208. /**
  209. * Replace all of the instances of searchValue in value with the provided replaceValue.
  210. * @param {string | undefined} value The value to search and replace in.
  211. * @param {string} searchValue The value to search for in the value argument.
  212. * @param {string} replaceValue The value to replace searchValue with in the value argument.
  213. * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue.
  214. */
  215. export function replaceAll(value, searchValue, replaceValue) {
  216. return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || "");
  217. }
  218. //# sourceMappingURL=utils.js.map