parse-client-options.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. module.exports = parseOptions
  2. const defaults = require('lodash/defaults')
  3. const pick = require('lodash/pick')
  4. const deprecate = require('./deprecate')
  5. const getRequestAgent = require('./get-request-agent')
  6. const DEFAULTS = require('./defaults')
  7. const OPTION_NAMES = [
  8. 'timeout',
  9. 'baseUrl',
  10. 'agent',
  11. 'headers'
  12. ]
  13. function parseOptions (userOptions) {
  14. if (!userOptions) {
  15. userOptions = {}
  16. }
  17. if ('followRedirects' in userOptions) {
  18. deprecate('followRedirects option is no longer supported. All redirects are followed correctly')
  19. }
  20. if ('protocol' in userOptions) {
  21. deprecate('protocol option is no longer supported')
  22. }
  23. if ('host' in userOptions) {
  24. deprecate('host option is no longer supported')
  25. }
  26. if ('port' in userOptions) {
  27. deprecate('port option is no longer supported')
  28. }
  29. if ('pathPrefix' in userOptions) {
  30. deprecate('pathPrefix option is no longer supported')
  31. }
  32. if ('Promise' in userOptions) {
  33. deprecate('Promise option is no longer supported. The native Promise API is used')
  34. }
  35. const options = defaults(pick(userOptions, OPTION_NAMES), DEFAULTS)
  36. const clientDefaults = {
  37. baseUrl: options.baseUrl,
  38. headers: options.headers,
  39. request: {
  40. timeout: options.timeout
  41. }
  42. }
  43. if (userOptions.protocol) {
  44. clientDefaults.baseUrl = `${userOptions.protocol}://${userOptions.host}`
  45. /* istanbul ignore else */
  46. if (userOptions.port) {
  47. clientDefaults.baseUrl += `:${userOptions.port}`
  48. }
  49. // Check if a prefix is passed in the options and strip any leading or trailing slashes from it.
  50. /* istanbul ignore else */
  51. if (userOptions.pathPrefix) {
  52. clientDefaults.baseUrl += '/' + userOptions.pathPrefix.replace(/(^[/]+|[/]+$)/g, '')
  53. }
  54. }
  55. /* istanbul ignore else */
  56. if (!process.browser) {
  57. clientDefaults.request.agent = getRequestAgent(clientDefaults.baseUrl, userOptions)
  58. }
  59. return clientDefaults
  60. }