Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convenience method to match all HTTP verbs #2486

Open
2 tasks done
hkovesdi opened this issue Jun 3, 2023 · 0 comments
Open
2 tasks done

Convenience method to match all HTTP verbs #2486

hkovesdi opened this issue Jun 3, 2023 · 0 comments
Labels

Comments

@hkovesdi
Copy link

hkovesdi commented Jun 3, 2023

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant