helpers.js 1.4 KB

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