helpers.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict'
  2. var jsonSafeStringify = require('json-stringify-safe')
  3. , crypto = require('crypto')
  4. , Buffer = require('safe-buffer').Buffer
  5. var defer = typeof setImmediate === 'undefined'
  6. ? process.nextTick
  7. : setImmediate
  8. function paramsHaveRequestBody(params) {
  9. return (
  10. params.body ||
  11. params.requestBodyStream ||
  12. (params.json && typeof params.json !== 'boolean') ||
  13. params.multipart
  14. )
  15. }
  16. function safeStringify (obj, replacer) {
  17. var ret
  18. try {
  19. ret = JSON.stringify(obj, replacer)
  20. } catch (e) {
  21. ret = jsonSafeStringify(obj, replacer)
  22. }
  23. return ret
  24. }
  25. function md5 (str) {
  26. return crypto.createHash('md5').update(str).digest('hex')
  27. }
  28. function isReadStream (rs) {
  29. return rs.readable && rs.path && rs.mode
  30. }
  31. function toBase64 (str) {
  32. return Buffer.from(str || '', 'utf8').toString('base64')
  33. }
  34. function copy (obj) {
  35. var o = {}
  36. Object.keys(obj).forEach(function (i) {
  37. o[i] = obj[i]
  38. })
  39. return o
  40. }
  41. function version () {
  42. var numbers = process.version.replace('v', '').split('.')
  43. return {
  44. major: parseInt(numbers[0], 10),
  45. minor: parseInt(numbers[1], 10),
  46. patch: parseInt(numbers[2], 10)
  47. }
  48. }
  49. exports.paramsHaveRequestBody = paramsHaveRequestBody
  50. exports.safeStringify = safeStringify
  51. exports.md5 = md5
  52. exports.isReadStream = isReadStream
  53. exports.toBase64 = toBase64
  54. exports.copy = copy
  55. exports.version = version
  56. exports.defer = defer