helpers.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict'
  2. var extend = require('util')._extend
  3. , jsonSafeStringify = require('json-stringify-safe')
  4. , crypto = require('crypto')
  5. function deferMethod() {
  6. if(typeof setImmediate === 'undefined') {
  7. return process.nextTick
  8. }
  9. return setImmediate
  10. }
  11. function constructObject(initialObject) {
  12. initialObject = initialObject || {}
  13. return {
  14. extend: function (object) {
  15. return constructObject(extend(initialObject, object))
  16. },
  17. done: function () {
  18. return initialObject
  19. }
  20. }
  21. }
  22. function constructOptionsFrom(uri, options) {
  23. var params = constructObject()
  24. if (typeof options === 'object') {
  25. params.extend(options).extend({uri: uri})
  26. } else if (typeof uri === 'string') {
  27. params.extend({uri: uri})
  28. } else {
  29. params.extend(uri)
  30. }
  31. return params.done()
  32. }
  33. function isFunction(value) {
  34. return typeof value === 'function'
  35. }
  36. function filterForCallback(values) {
  37. var callbacks = values.filter(isFunction)
  38. return callbacks[0]
  39. }
  40. function paramsHaveRequestBody(params) {
  41. return (
  42. params.options.body ||
  43. params.options.requestBodyStream ||
  44. (params.options.json && typeof params.options.json !== 'boolean') ||
  45. params.options.multipart
  46. )
  47. }
  48. function safeStringify (obj) {
  49. var ret
  50. try {
  51. ret = JSON.stringify(obj)
  52. } catch (e) {
  53. ret = jsonSafeStringify(obj)
  54. }
  55. return ret
  56. }
  57. function md5 (str) {
  58. return crypto.createHash('md5').update(str).digest('hex')
  59. }
  60. function isReadStream (rs) {
  61. return rs.readable && rs.path && rs.mode
  62. }
  63. function toBase64 (str) {
  64. return (new Buffer(str || '', 'ascii')).toString('base64')
  65. }
  66. exports.isFunction = isFunction
  67. exports.constructObject = constructObject
  68. exports.constructOptionsFrom = constructOptionsFrom
  69. exports.filterForCallback = filterForCallback
  70. exports.paramsHaveRequestBody = paramsHaveRequestBody
  71. exports.safeStringify = safeStringify
  72. exports.md5 = md5
  73. exports.isReadStream = isReadStream
  74. exports.toBase64 = toBase64
  75. exports.defer = deferMethod()