codesignd Patterns

(function(app) {
	'use strict';
	
	// Store for the event handlers
	var handlers = {};
	var hasOwnProperty = handlers.hasOwnProperty;
	
	/**
	 * Registers an event handler for a specified event
	 *
	 * @param  {string}   event    Event name
	 * @param  {Function} callback
	 * @return {object}            Object with a remove() method to unsubscribe from events
	 */
	app.on = function(event, callback) {
		// Create event array if not already existing
		if(!hasOwnProperty.call(handlers, event)) handlers[event] = [];
		
		// Add the callback to the array
		var index = handlers[event].push(callback) - 1;
		
		// Return function to delete handler again
		return {
			remove: function() {
				delete handlers[event][index];
			}
		};
	};
	
	/**
	 * Triggers an event with a given event argument
	 *
	 * @param {string} event Event name
	 * @param {mixed}  ...   Arbitrary arguments to pass to every callback
	 */
	app.emit = function(event) {
		if(!hasOwnProperty.call(handlers, event)) return;
		
		var args = Array.prototype.slice.call(arguments, 1);
		handlers[event].forEach(function(handler) {
			handler.apply(undefined, args);
		});
	};
	
	/**
	 * Returns a promise that resolves after the specified time
	 *
	 * @param  {integer} time Time in milliseconds
	 * @return {Promise}
	 */
	app.timerPromise = function(time) {
		return new Promise(function(resolve, reject) {
			setTimeout(resolve, time);
		});
	};
	
	/**
	 * Validates that a fetch() request has a HTTP status code in the 200 range
	 *
	 * @param  {Response} response fetch() response
	 * @return {Response}          Same response object to allow for chaining
	 */
	app.validateHttpStatus = function(response) {
		if(response.status >= 200 && response.status < 300) {
			return response;
		} else {
			var error = new Error('HTTP response with status: ' + response.status + ' ' + response.statusText);
			error.response = response;
			throw error;
		}
	};
	
	/**
	 * Converts a fetch() response to JSON
	 *
	 * @param  {Response} response fetch() response
	 * @return {Promise}
	 */
	app.parseJsonResponse = function(response) {
		// Validate that the response is JSON
		var contentType = response.headers.get('Content-Type');
		if(contentType.indexOf('application/json') !== 0) {
			throw new Error('Got content type "' + contentType + '", expected JSON.');
		}
		
		// Convert response to JSON
		return response.json();
	};
})(window.app = window.app || {});