utils.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const bson_1 = require("bson");
  4. const type_1 = require("./type");
  5. exports.sleep = (ms = 0) => new Promise(r => setTimeout(r, ms));
  6. const counters = {};
  7. exports.autoCount = (domain = 'any') => {
  8. if (!counters[domain]) {
  9. counters[domain] = 0;
  10. }
  11. return counters[domain]++;
  12. };
  13. exports.getReqOpts = (apiOptions) => {
  14. if (apiOptions.timeout !== undefined) {
  15. return {
  16. timeout: apiOptions.timeout
  17. };
  18. }
  19. return {};
  20. };
  21. exports.filterUndefined = o => {
  22. if (!type_1.isObject(o)) {
  23. return o;
  24. }
  25. for (let key in o) {
  26. if (o[key] === undefined) {
  27. delete o[key];
  28. }
  29. else if (type_1.isObject(o[key])) {
  30. o[key] = exports.filterUndefined(o[key]);
  31. }
  32. }
  33. return o;
  34. };
  35. exports.stringifyByEJSON = params => {
  36. params = exports.filterUndefined(params);
  37. return bson_1.EJSON.stringify(params, { relaxed: false });
  38. };
  39. exports.parseByEJSON = params => {
  40. return bson_1.EJSON.parse(params);
  41. };
  42. class TcbError extends Error {
  43. constructor(error) {
  44. super(error.message);
  45. this.code = error.code;
  46. this.message = error.message;
  47. }
  48. }
  49. exports.TcbError = TcbError;
  50. exports.E = (errObj) => {
  51. return new TcbError(errObj);
  52. };
  53. function processReturn(throwOnCode, res) {
  54. if (throwOnCode === false) {
  55. return res;
  56. }
  57. throw exports.E(Object.assign({}, res));
  58. }
  59. exports.processReturn = processReturn;