Getting response with NodeJS request module

The request module is really powerful. Here’s an example of a function:

const request = require('request');

// Get config

const krakenDefaults = {
		baseUrl: 'https://api.twitch.tv/kraken/',
		headers: {
			Accept: 'application/vnd.twitchtv.v5+json',
			'Client-ID': config.twitch.api.clientID
		},
		json: true
	};

const kraken = request.defaults(krakenDefaults);

function usernameToUser(username, callback) {
	// Caching here

	return kraken({
		url: 'users',
		qs: { login: username },
		callback: (err, { statusCode }, { _total, users }) => {
			if(err || statusCode !== 200 || _total === 0) {
				callback(err, null);
			}
			else {
				callback(null, users[0]);
			}
		}
	});
}

You can find all of the request library options here.

let input = 'alca';
usernameToUser(input, (err, data) => {
	if(err) {
		console.log('ERR', err);
	}
	else {
		console.log(input, 'is ID', data._id); // 'alca is ID 7676884'
	}
});

With request-promise this would look like:

const rp = require('request-promise');

// Get config

const krakenDefaults = {
		baseUrl: 'https://api.twitch.tv/kraken/',
		headers: {
			Accept: 'application/vnd.twitchtv.v5+json',
			'Client-ID': config.twitch.api.clientID
		},
		json: true
	};

const kraken = rp.defaults(krakenDefaults);

function usernameToUser(username) {
	// Caching here

	return kraken({
		url: 'users',
		qs: { login: username }
	})
	.then(({ _total, users }) => {
		if(_total === 0) {
			return null;
		}
		return users[0];
	});
}
let input = 'alca';
usernameToUser(input)
	.then(data => {
		console.log(input, 'is ID', data._id); // 'alca is ID 7676884'
	});

And then there’s options like “simple” and “resolveWithFullResponse” that you might want.