all files / apigateway-utils/src/ ResponseBuilder.js

100% Statements 61/61
100% Branches 28/28
100% Functions 21/21
100% Lines 61/61
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150                    32× 32× 32× 32× 32× 32×       14× 14×       50× 50×       23× 23×       39×                                                                               68× 68×   68×               68×     68×   61× 61× 61×         68×   68× 62×               11×          
'use strict';
 
var _ = require('underscore'),
    Class = require('class.extend'),
    CONTENT_TYPE_JSON = 'application/json;charset=UTF-8',
    CONTENT_TYPE_JSONP = 'text/javascript;charset=UTF-8',
    CONTENT_TYPE_RSS = 'application/rss+xml',
    CONTENT_TYPE_HTML = 'text/html;charset=UTF-8';
 
module.exports = Class.extend({
 
   init: function() {
      this._headers = {};
      this._status = 200;
      this._body = {};
      this._isJSONPSupported = false;
      this._cacheDurationSeconds = 0;
      this.contentType(CONTENT_TYPE_JSON);
   },
 
   status: function(status) {
      this._status = status;
      return this;
   },
 
   header: function(key, value) {
      this._headers[key] = value;
      return this;
   },
 
   body: function(o) {
      this._body = o;
      return this;
   },
 
   contentType: function(type) {
      return this.header('Content-Type', type);
   },
 
   allowCORS: function(origin) {
      return this.header('Access-Control-Allow-Origin', origin || '*');
   },
 
   supportJSONP: function(jsonpCallbackQueryParamName) {
      this._isJSONPSupported = true;
      this._jsonpQueryParamName = jsonpCallbackQueryParamName;
      return this;
   },
 
   cacheForSeconds: function(s) {
      this._cacheDurationSeconds = Math.max(0, s);
      return this;
   },
 
   cacheForMinutes: function(m) {
      return this.cacheForSeconds(m * 60);
   },
 
   cacheForHours: function(h) {
      return this.cacheForMinutes(h * 60);
   },
 
   redirect: function(url, isPermanent) {
      this.status(isPermanent ? 301 : 302);
      this.header('Location', url);
      return this.body('Found. Redirecting to ' + url);
   },
 
   invalidRequest: function(body) {
      this.status(400);
      return this.body(body || { message: 'Invalid request', status: 400 });
   },
 
   error: function(body) {
      this.status(500);
      return this.body(body || { message: 'Error processing request', status: 500 });
   },
 
   serviceUnavailable: function(body) {
      this.status(503);
      return this.body(body || { message: 'Service unavailable', status: 503 });
   },
 
   notFound: function(body) {
      this.status(404);
      return this.body(body || { message: 'Not Found', status: 404 });
   },
 
   rss: function(body) {
      this.contentType(CONTENT_TYPE_RSS);
      return this.body(body);
   },
 
   html: function(body) {
      this.contentType(CONTENT_TYPE_HTML);
      return this.body(body);
   },
 
   toResponse: function(req) {
      this._updateForJSONP(req);
      this._addCacheHeaders();
 
      return {
         statusCode: this._status,
         headers: this._headers,
         body: _.isObject(this._body) ? JSON.stringify(this._body) : this._body,
      };
   },
 
   _addCacheHeaders: function() {
      var now = new Date(),
          expiry = new Date(now.getTime() + (this._cacheDurationSeconds * 1000));
 
      if (this._cacheDurationSeconds) {
         delete this._headers.Pragma;
         this._headers.Expires = expiry.toUTCString();
         this._headers['Cache-Control'] = ('must-revalidate, max-age=' + this._cacheDurationSeconds);
      } else {
         this._headers.Expires = 'Thu, 19 Nov 1981 08:52:00 GMT';
         this._headers['Cache-Control'] = 'no-cache, max-age=0, must-revalidate';
         this._headers.Pragma = 'no-cache';
      }
   },
 
   _updateForJSONP: function(req) {
      var callback;
 
      if (!this._isJSONPSupported || !(_.isObject(this._body) || _.isArray(this._body))) {
         return;
      }
 
      if (req.hasQueryParam(this._jsonpQueryParamName) && this._isValidJSONPCallback(req.query(this._jsonpQueryParamName))) {
         callback = req.query(this._jsonpQueryParamName);
 
         this.contentType(CONTENT_TYPE_JSONP);
         this._body = 'typeof ' + callback + ' === \'function\' && ' + callback + '(' + JSON.stringify(this._body) + ');';
      }
   },
 
   _isValidJSONPCallback: function(name) {
      return _.isEmpty(name) ? false : /^[A-Za-z0-9_\\$]+$/.test(name);
   },
 
});
 
module.exports.CONTENT_TYPE_JSON = CONTENT_TYPE_JSON;
module.exports.CONTENT_TYPE_JSONP = CONTENT_TYPE_JSONP;
module.exports.CONTENT_TYPE_RSS = CONTENT_TYPE_RSS;
module.exports.CONTENT_TYPE_HTML = CONTENT_TYPE_HTML;