Skip to content

Latest commit

History

History
113 lines (86 loc) 路 2.55 KB

advanced-creation.md

File metadata and controls

113 lines (86 loc) 路 2.55 KB

Advanced creation

Make calling REST APIs easier by creating niche-specific got instances.

got.create(settings)

Example: gh-got

Configure a new got instance with the provided settings.
Note: In contrast to got.extend(), this method has no defaults.

To inherit from parent, set it as got.defaults.options or use got.mergeOptions(defaults.options, options).
Note: Avoid using object spread as it doesn't work recursively.

methods

Type: Object

Array of supported request methods.

To inherit from parent, set it as got.defaults.methods.

handler

Type: Function
Default: undefined

Function making additional changes to the request.

To inherit from parent, set it as got.defaults.handler.
To use the default handler, just omit specifying this.

Note: These options are normalized.

next()

Normalizes arguments and returns a Promise or a Stream depending on options.stream.

const settings = {
	handler: (options, next) => {
		if (options.stream) {
			// It's a Stream
			// We can perform stream-specific actions on it
			return next(options)
				.on('request', request => setTimeout(() => request.abort(), 50));
		}

		// It's a Promise
		return next(options);
	},
	methods: got.defaults.methods,
	options: got.mergeOptions(got.defaults.options, {
		json: true
	})
};

const jsonGot = got.create(settings);
const defaults = {
	handler: (options, next) => next(options),
	methods: [
		'get',
		'post',
		'put',
		'patch',
		'head',
		'delete'
	],
	options: {
		retries: 2,
		cache: false,
		decompress: true,
		useElectronNet: false,
		throwHttpErrors: true,
		headers: {
			'user-agent': `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)`
		}
	}
};

// Same as:
const defaults = {
	handler: got.defaults.handler,
	methods: got.defaults.methods,
	options: got.defaults.options
};

const unchangedGot = got.create(defaults);
const settings = {
	handler: got.defaults.handler,
	methods: got.defaults.methods,
	options: got.mergeOptions(got.defaults.options, {
		headers: {
			unicorn: 'rainbow'
		}
	})
};

const unicorn = got.create(settings);

// Same as:
const unicorn = got.extend({headers: {unicorn: 'rainbow'}});