utils.js 1.4 KB

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