new HttpParser( req, res, mockDir )

Description

Create a parser class which defines methods to parse

  1. Request URL to get a matching directory
  2. From matched directory get .mock file content and generate a response
Parameters
Name Type Description
req express.Request

Express Request object for current instance of incoming request

res express.Response

Express response to be sent to client

mockDir string

location of http mocks

Methods


getMatchedDir() → {string}

Description

Finds a closest match dir for an incoming request

Returns

matchedDir for a given incoming request


getResponse( mockFile ) → {string}

Description

Defines a default response, if the closest matchedDir is present, parses and sends the response from mockfile, Looks for API Level, and Global level default response overrides if mockfile is not found. If no default response overrides are found, send the defined default response

Parameters
Name Type Description
mockFile string

location of of the closest mached mockfile for incoming request

Returns

matchedDir for a given incoming request


prepareResponse( mockFile )

Description
  • Since response file contains headers and body both, a PARSE_BODY flag is required to tell the logic if it's currently parsing headers or body
  • Set responseBody to an empty string and set a default response object
  • Set default response
  • Compile the handlebars used in the contents of mockFile
  • Generate actual response i.e. replace handlebars with their actual values and split the content into lines
  • If the mockfile contains the delimiter ====, split the content using the delimiter and pick one of the responses at random
  • Split file contents by os.EOL and read file line by line
  • Set PARSE_BODY flag to try when reader finds a blank line, since according to standard format of a raw HTTP Response, headers and body are separated by a blank line.
  • If line includes HTTP/HTTPS i.e. first line. Get the response status code
  • If following conditions are met:
    • Line is not blank; and
    • Parser is not currently parsing response body yet i.e. PARSE_BODY === false
  • Then:
    • Split line by :, of which first part will be header key and 2nd part will be header value
    • If headerKey is response delay, set variable DELAY to headerValue
  • If parsing response body, i.e. PARSE_BODY === true. Concatenate every line till last line to a responseBody variable
  • If on last line of response, do following:
    • Trim and remove whitespaces from the responseBody
    • Compile the Handlebars to generate a final response
    • Set PARSE_BODY flag back to false and responseBody to blank
    • Set express.Response Status code to response.status
    • Send the generated Response, from a timeout set to send the response after a DELAY value
Parameters
Name Type Description
mockFile string

location of of the closest mached mockfile for incoming request