UNPKG

2.33 kBJavaScriptView Raw
1/*
2 * Copyright 2014 the original author or authors
3 * @license MIT, see LICENSE.txt for details
4 *
5 * @author Scott Andrews
6 */
7
8(function (define) {
9 'use strict';
10
11 define(function (require) {
12
13 var Promise = require('when/lib/Promise'),
14 when = require('when'),
15 normalizeHeaderName = require('./normalizeHeaderName');
16
17 // extend ResponsePromise from Promise
18 function ResponsePromise() {
19 return Promise.apply(this, arguments);
20 }
21 ResponsePromise.prototype = Object.create(Promise.prototype);
22
23 // augment ResponsePromise with HTTP Response specific methods
24
25 function property(promise, name) {
26 return promise.then(
27 function (value) {
28 return value && value[name];
29 },
30 function (value) {
31 return when.reject(value && value[name]);
32 }
33 );
34 }
35
36 /**
37 * Obtain the response entity
38 *
39 * @returns {Promise} for the response entity
40 */
41 ResponsePromise.prototype.entity = function entity() {
42 return property(this, 'entity');
43 };
44
45 /**
46 * Obtain the response status
47 *
48 * @returns {Promise} for the response status
49 */
50 ResponsePromise.prototype.status = function status() {
51 return property(property(this, 'status'), 'code');
52 };
53
54 /**
55 * Obtain the response headers map
56 *
57 * @returns {Promise} for the response headers map
58 */
59 ResponsePromise.prototype.headers = function headers() {
60 return property(this, 'headers');
61 };
62
63 /**
64 * Obtain a specific response header
65 *
66 * @param {String} headerName the header to retrieve
67 * @returns {Promise} for the response header's value
68 */
69 ResponsePromise.prototype.header = function header(headerName) {
70 headerName = normalizeHeaderName(headerName);
71 return property(this.headers(), headerName);
72 };
73
74 /**
75 * Wrap a Promise as an ResponsePromise
76 *
77 * @param {Promise<Response>} promise the promise for an HTTP Response
78 * @returns {ResponsePromise<Response>} wrapped promise for Response with additional helper methods
79 */
80 function makeResponsePromise(promise) {
81 return new ResponsePromise(promise.then.bind(promise));
82 }
83
84 makeResponsePromise.ResponsePromise = ResponsePromise;
85
86 return makeResponsePromise;
87
88 });
89
90}(
91 typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }
92 // Boilerplate for AMD and Node
93));