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

100% Statements 32/32
100% Branches 18/18
100% Functions 16/16
100% Lines 32/32
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            49× 49× 49× 49× 49× 49×                         27×     27×                       12×       57×       93×                         18×                          
'use strict';
 
var _ = require('underscore'),
    Class = require('class.extend');
 
module.exports = Class.extend({
 
   init: function(evt, context) {
      this._started = new Date().getTime();
      this._event = evt;
      this._context = context;
      this._query = this._event.queryStringParameters || {};
      this._pathParams = this._event.pathParameters || {};
      this._headers = this._event.headers || {};
   },
 
   getEvent: function() {
      return this._event;
   },
 
   getContext: function() {
      return this._context;
   },
 
   validateQueryParams: function(rules) {
      var invalidRequiredFields = [],
          isValid = true,
          msg;
 
      _.each(rules, function(rule, name) {
         if (this.hasQueryParam(name) && rule.pattern && !rule.pattern.test(this.query(name))) {
            this._query[name] = undefined;
            isValid = false;
         }
 
         if (rule.required && (!this.hasQueryParam(name) || _.isEmpty(this.query(name)))) {
            isValid = false;
            invalidRequiredFields.push(name);
         }
      }.bind(this));
 
      if (!_.isEmpty(invalidRequiredFields)) {
         msg = 'Invalid required fields: ' + invalidRequiredFields.join(', ');
      }
 
      return { isValid: isValid, msg: msg };
   },
 
   hasPathParam: function(k) {
      return !_.isUndefined(this.pathParam(k));
   },
 
   pathParam: function(k) {
      return this._pathParams[k];
   },
 
   hasQueryParam: function(k) {
      return !_.isUndefined(this.query(k));
   },
 
   query: function(k) {
      return this._query[k];
   },
 
   context: function(k) {
      return this._context[k];
   },
 
   body: function() {
      return this._event.body;
   },
 
   isBase64Encoded: function() {
      return !!this._event.isBase64Encoded;
   },
 
   header: function(k) {
      return this._headers[k];
   },
 
   path: function() {
      return this._event.path;
   },
 
   method: function() {
      return this._event.httpMethod;
   },
 
   started: function() {
      return this._started;
   },
 
});