Skip to content

Convenience method to match all HTTP verbs #2486

Open
@hkovesdi

Description

@hkovesdi

Please avoid duplicates

Context

I came across a situation where I needed to validate a certain header before all requests and respond with a 400 if the validation failed.

nock('http://localhost')
  .matchHeader('X-Request-Id', (val) => String(val).match(/^[A-Fa-f0-9]{32}$/) === null)
  .get(/.*/)
  .replyWithError({
    message: 'Invalid request',
    code: 400,
  })
  .persist();

The validation is HTTP verb agnostic, so the above example would need to be repeated for all verbs.
It would be great to have a convenience method for such cases (e.g .any() or for the .intercept() method to accept an array of verbs as the second argument).

Alternatives

Yes, here is the implementation I'm currently using:

function nockAny(scope: nock.Scope, uri: string | RegExp, callback: (interceptor: nock.Interceptor) => nock.Scope) {
  const verbs = ['GET', 'PUT', 'HEAD', 'PATCH', 'POST', 'DELETE'];

  for (const verb of verbs) {
    callback(scope.intercept(uri, verb));
  }
}

  nockAny(
    nock('http://localhost').matchHeader('X-Request-Id', (val) => String(val).match(/^[A-Fa-f0-9]{32}$/) === null),
    /.*/,
    (interceptor) => {
      return interceptor
        .replyWithError({
          message: 'Invalid request',
          code: 400,
        })
        .persist();
    },
  );

It works just fine, but it would be great to have a convenience method for this. I'd be happy to submit a PR for it.

If the feature request is accepted, would you be willing to submit a PR?

  • yes

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions