Skip to content

Commit

Permalink
style: Minor style improvements (#1693)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmelnikow committed Aug 23, 2019
1 parent 949d264 commit 8e78ffe
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 71 deletions.
24 changes: 12 additions & 12 deletions lib/common.js
Expand Up @@ -9,7 +9,7 @@ const url = require('url')
*
* @param {Object} options - a parsed options object of the request
*/
const normalizeRequestOptions = function(options) {
function normalizeRequestOptions(options) {
options.proto = options.proto || 'http'
options.port = options.port || (options.proto === 'http' ? 80 : 443)
if (options.host) {
Expand Down Expand Up @@ -46,7 +46,7 @@ const normalizeRequestOptions = function(options) {
* @param {Object} buffer - a Buffer object
* @returns {boolean}
*/
const isUtf8Representable = function(buffer) {
function isUtf8Representable(buffer) {
if (!Buffer.isBuffer(buffer)) {
return false
}
Expand All @@ -70,7 +70,7 @@ let requestOverrides = {}
* - options - the options of the issued request
* - callback - the callback of the issued request
*/
const overrideRequests = function(newRequest) {
function overrideRequests(newRequest) {
debug('overriding requests')
;['http', 'https'].forEach(function(proto) {
debug('- overriding request for', proto)
Expand Down Expand Up @@ -118,7 +118,7 @@ const overrideRequests = function(newRequest) {
* Restores `request` function of `http` and `https` modules to values they
* held before they were overridden by us.
*/
const restoreOverriddenRequests = function() {
function restoreOverriddenRequests() {
debug('restoring requests')
Object.entries(requestOverrides).forEach(
([proto, { module, request, get }]) => {
Expand All @@ -135,7 +135,7 @@ const restoreOverriddenRequests = function() {
* In WHATWG URL vernacular, this returns the origin portion of a URL.
* However, the port is not included if it's standard and not already present on the host.
*/
const normalizeOrigin = (proto, host, port) => {
function normalizeOrigin(proto, host, port) {
const hostHasPort = host.includes(':')
const portIsStandard =
(proto === 'http' && (port === 80 || port === '80')) ||
Expand Down Expand Up @@ -195,7 +195,7 @@ function isJSONContent(headers) {
*
* Duplicates throw an error.
*/
const headersFieldNamesToLowerCase = function(headers) {
function headersFieldNamesToLowerCase(headers) {
if (!_.isPlainObject(headers)) {
throw Error('Headers must be provided as an object')
}
Expand Down Expand Up @@ -228,7 +228,7 @@ const headersFieldsArrayToLowerCase = headers => [
*
* https://nodejs.org/api/http.html#http_message_rawheaders
*/
const headersInputToRawArray = function(headers) {
function headersInputToRawArray(headers) {
if (headers === undefined) {
return []
}
Expand Down Expand Up @@ -263,7 +263,7 @@ const headersInputToRawArray = function(headers) {
*
* Header names/keys are lower-cased.
*/
const headersArrayToObject = function(rawHeaders) {
function headersArrayToObject(rawHeaders) {
if (!Array.isArray(rawHeaders)) {
throw Error('Expected a header array')
}
Expand Down Expand Up @@ -318,7 +318,7 @@ const noDuplicatesHeaders = new Set([
*
* While Node has the luxury of knowing `value` is always a string, we do an extra step of coercion at the top.
*/
const addHeaderLine = function(headers, name, value) {
function addHeaderLine(headers, name, value) {
let values // code below expects `values` to be an array of strings
if (typeof value === 'function') {
// Function values are evaluated towards the end of the response, before that we use a placeholder
Expand Down Expand Up @@ -360,7 +360,7 @@ const addHeaderLine = function(headers, name, value) {
* @headers {Object} headers - object of header field names and values
* @fieldName {String} field name - string with the case-insensitive field name
*/
const deleteHeadersField = function(headers, fieldNameToDelete) {
function deleteHeadersField(headers, fieldNameToDelete) {
if (!_.isPlainObject(headers)) {
throw Error('headers must be an object')
}
Expand All @@ -385,7 +385,7 @@ const deleteHeadersField = function(headers, fieldNameToDelete) {
* - The header field name. string
* - Index of the header field in the raw header array.
*/
const forEachHeader = function(rawHeaders, callback) {
function forEachHeader(rawHeaders, callback) {
for (let i = 0; i < rawHeaders.length; i += 2) {
callback(rawHeaders[i + 1], rawHeaders[i], i)
}
Expand Down Expand Up @@ -571,7 +571,7 @@ const expand = input =>
*
* Expected values or leaf nodes of expected object values that are RegExp use test() for comparison.
*/
const deepEqual = (expected, actual) => {
function deepEqual(expected, actual) {
debug('deepEqual comparing', typeof expected, expected, typeof actual, actual)
if (expected instanceof RegExp) {
return expected.test(actual)
Expand Down
22 changes: 12 additions & 10 deletions lib/interceptor.js
Expand Up @@ -4,7 +4,7 @@ const debug = require('debug')('nock.interceptor')
const stringify = require('json-stringify-safe')
const _ = require('lodash')
const querystring = require('querystring')
const url = require('url')
const { URL, URLSearchParams } = require('url')

const common = require('./common')
const matchBody = require('./match_body')
Expand Down Expand Up @@ -74,7 +74,7 @@ module.exports = class Interceptor {
// strip off literal query parameters if they were provided as part of the URI
if (uriIsStr && uri.includes('?')) {
// localhost is a dummy value because the URL constructor errors for only relative inputs
const parsedURL = new url.URL(this.path, 'http://localhost')
const parsedURL = new URL(this.path, 'http://localhost')
this.path = parsedURL.pathname
this.query(parsedURL.searchParams)
this._key = `${this.method} ${scope.basePath}${this.path}`
Expand Down Expand Up @@ -298,10 +298,10 @@ module.exports = class Interceptor {
path = pathname
}

// If we have a filtered scope then we use it instead reconstructing
// the scope from the request options (proto, host and port) as these
// two won't necessarily match and we have to remove the scope that was
// matched (vs. that was defined).
// If we have a filtered scope then we use it instead reconstructing the
// scope from the request options (proto, host and port) as these two won't
// necessarily match and we have to remove the scope that was matched (vs.
// that was defined).
if (this.__nock_filteredScope) {
matchKey = this.__nock_filteredScope
} else {
Expand Down Expand Up @@ -400,7 +400,8 @@ module.exports = class Interceptor {
return this
}

// filtering by path is valid on the intercept level, but not filtering by request body?
// TODO filtering by path is valid on the intercept level, but not filtering
// by request body?

discard() {
if ((this.scope.shouldPersist() || this.counter > 0) && this.filePath) {
Expand Down Expand Up @@ -454,7 +455,7 @@ module.exports = class Interceptor {
strFormattingFn = common.percentDecode
}

if (queries instanceof url.URLSearchParams) {
if (queries instanceof URLSearchParams) {
// Normalize the data into the shape that is matched against.
// Duplicate keys are handled by combining the values into an array.
queries = querystring.parse(queries.toString())
Expand Down Expand Up @@ -536,10 +537,11 @@ module.exports = class Interceptor {
* @return {Interceptor} - the current interceptor for chaining
*/
delay(opts) {
let headDelay = 0
let bodyDelay = 0
let headDelay
let bodyDelay
if (_.isNumber(opts)) {
headDelay = opts
bodyDelay = 0
} else if (_.isObject(opts)) {
headDelay = opts.head || 0
bodyDelay = opts.body || 0
Expand Down
69 changes: 29 additions & 40 deletions lib/recorder.js
Expand Up @@ -20,7 +20,7 @@ function getMethod(options) {
return options.method || 'GET'
}

const getBodyFromChunks = function(chunks, headers) {
function getBodyFromChunks(chunks, headers) {
// If we have headers and there is content-encoding it means that
// the body shouldn't be merged but instead persisted as an array
// of hex strings so that the responses can be mocked one by one.
Expand Down Expand Up @@ -59,14 +59,14 @@ const getBodyFromChunks = function(chunks, headers) {
}
}

function generateRequestAndResponseObject(
function generateRequestAndResponseObject({
req,
bodyChunks,
options,
res,
dataChunks,
reqheaders
) {
reqheaders,
}) {
const response = getBodyFromChunks(dataChunks, res.headers)
options.path = req.path

Expand All @@ -91,14 +91,14 @@ function generateRequestAndResponseObject(
return nockDef
}

function generateRequestAndResponse(
function generateRequestAndResponse({
req,
bodyChunks,
options,
res,
dataChunks,
reqheaders
) {
reqheaders,
}) {
const requestBody = getBodyFromChunks(bodyChunks).body
const responseBody = getBodyFromChunks(dataChunks, res.headers).body

Expand All @@ -110,11 +110,10 @@ function generateRequestAndResponse(
// Remove the query from the path
path = path.substring(0, queryIndex)

// Create the query() object
const queryStr = req.path.slice(queryIndex + 1)
queryObj = querystring.parse(queryStr)
}
// Always encoding the query parameters when recording.
// Always encode the query parameters when recording.
const encodedQueryObj = {}
for (const key in queryObj) {
const formattedPair = common.formatQueryValue(
Expand Down Expand Up @@ -242,9 +241,7 @@ function record(recOptions) {
res.once('end', function() {
debug(thisRecordingId, proto, 'intercepted request ended')

let out
let reqheaders

// Ignore request headers completely unless it was explicitly enabled by the user (see README)
if (enableReqHeadersRecording) {
// We never record user-agent headers as they are worse than useless -
Expand All @@ -253,25 +250,17 @@ function record(recOptions) {
common.deleteHeadersField(reqheaders, 'user-agent')
}

if (outputObjects) {
out = generateRequestAndResponseObject(
req,
bodyChunks,
options,
res,
dataChunks,
reqheaders
)
} else {
out = generateRequestAndResponse(
req,
bodyChunks,
options,
res,
dataChunks,
reqheaders
)
}
const generateFn = outputObjects
? generateRequestAndResponseObject
: generateRequestAndResponse
let out = generateFn({
req,
bodyChunks,
options,
res,
dataChunks,
reqheaders,
})

debug('out:', out)

Expand Down Expand Up @@ -302,9 +291,7 @@ function record(recOptions) {
}
})

const dataChunks = []
let encoding

// We need to be aware of changes to the stream's encoding so that we
// don't accidentally mangle the data.
const { setEncoding } = res
Expand All @@ -313,6 +300,7 @@ function record(recOptions) {
return setEncoding.apply(this, arguments)
}

const dataChunks = []
// Replace res.push with our own implementation that stores chunks
const origResPush = res.push
res.push = function(data) {
Expand Down Expand Up @@ -361,8 +349,9 @@ function record(recOptions) {
}
}

// Starting in Node 8, `OutgoingMessage.end()` directly calls an internal `write_` function instead
// of proxying to the public `OutgoingMessage.write()` method, so we have to wrap `end` too.
// Starting in Node 8, `OutgoingMessage.end()` directly calls an internal
// `write_` function instead of proxying to the public
// `OutgoingMessage.write()` method, so we have to wrap `end` too.
const oldEnd = req.end
req.end = function(chunk, encoding, callback) {
debug('req.end')
Expand All @@ -384,7 +373,7 @@ function record(recOptions) {
})
}

// Restores *all* the overridden http/https modules' properties.
// Restore *all* the overridden http/https modules' properties.
function restore() {
debug(
currentRecordingId,
Expand All @@ -400,9 +389,9 @@ function clear() {
outputs = []
}

exports.record = record
exports.outputs = function() {
return outputs
module.exports = {
record,
outputs: () => outputs,
restore,
clear,
}
exports.restore = restore
exports.clear = clear
1 change: 0 additions & 1 deletion lib/scope.js
Expand Up @@ -158,7 +158,6 @@ class Scope extends EventEmitter {
}

isDone() {
// if nock is turned off, it always says it's done
if (!globalIntercept.isOn()) {
return true
}
Expand Down
12 changes: 5 additions & 7 deletions lib/socket.js
Expand Up @@ -3,8 +3,6 @@
const { EventEmitter } = require('events')
const debug = require('debug')('nock.socket')

function noop() {}

module.exports = class Socket extends EventEmitter {
constructor(options) {
super()
Expand All @@ -19,11 +17,6 @@ module.exports = class Socket extends EventEmitter {
this.destroyed = false
this.connecting = false

this.setNoDelay = noop
this.setKeepAlive = noop
this.resume = noop
this.unref = noop

// totalDelay that has already been applied to the current
// request/connection, timeout error will be generated if
// it is timed-out.
Expand All @@ -32,6 +25,11 @@ module.exports = class Socket extends EventEmitter {
this.timeoutMs = null
}

setNoDelay() {}
setKeepAlive() {}
resume() {}
unref() {}

setTimeout(timeoutMs, fn) {
this.timeoutMs = timeoutMs
if (fn) {
Expand Down

0 comments on commit 8e78ffe

Please sign in to comment.