create.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. const errors = require('./errors');
  3. const asStream = require('./as-stream');
  4. const asPromise = require('./as-promise');
  5. const normalizeArguments = require('./normalize-arguments');
  6. const merge = require('./merge');
  7. const deepFreeze = require('./utils/deep-freeze');
  8. const getPromiseOrStream = options => options.stream ? asStream(options) : asPromise(options);
  9. const aliases = [
  10. 'get',
  11. 'post',
  12. 'put',
  13. 'patch',
  14. 'head',
  15. 'delete'
  16. ];
  17. const create = defaults => {
  18. defaults = merge({}, defaults);
  19. normalizeArguments.preNormalize(defaults.options);
  20. if (!defaults.handler) {
  21. // This can't be getPromiseOrStream, because when merging
  22. // the chain would stop at this point and no further handlers would be called.
  23. defaults.handler = (options, next) => next(options);
  24. }
  25. function got(url, options) {
  26. try {
  27. return defaults.handler(normalizeArguments(url, options, defaults), getPromiseOrStream);
  28. } catch (error) {
  29. if (options && options.stream) {
  30. throw error;
  31. } else {
  32. return Promise.reject(error);
  33. }
  34. }
  35. }
  36. got.create = create;
  37. got.extend = options => {
  38. let mutableDefaults;
  39. if (options && Reflect.has(options, 'mutableDefaults')) {
  40. mutableDefaults = options.mutableDefaults;
  41. delete options.mutableDefaults;
  42. } else {
  43. mutableDefaults = defaults.mutableDefaults;
  44. }
  45. return create({
  46. options: merge.options(defaults.options, options),
  47. handler: defaults.handler,
  48. mutableDefaults
  49. });
  50. };
  51. got.mergeInstances = (...args) => create(merge.instances(args));
  52. got.stream = (url, options) => got(url, {...options, stream: true});
  53. for (const method of aliases) {
  54. got[method] = (url, options) => got(url, {...options, method});
  55. got.stream[method] = (url, options) => got.stream(url, {...options, method});
  56. }
  57. Object.assign(got, {...errors, mergeOptions: merge.options});
  58. Object.defineProperty(got, 'defaults', {
  59. value: defaults.mutableDefaults ? defaults : deepFreeze(defaults),
  60. writable: defaults.mutableDefaults,
  61. configurable: defaults.mutableDefaults,
  62. enumerable: true
  63. });
  64. return got;
  65. };
  66. module.exports = create;