Skip to content

Conversation

@billxinli
Copy link
Contributor

@billxinli billxinli commented Mar 17, 2022

Sometimes we may need to override the client function based on the spec, environment or special circumstances, such as test scenarios in test environment, where a mocked out fetch is required.

The constructor takes a fetch argument, however this can not be easily customized during run time, and the fetch function is called with the standard arguments, and it does not have any awareness to the spec that is associated to the call.

const api = new OASRequest({
  server: 'https://httpbin.org:443',

  clientFactory: function (url, options, spec) {
    const { operation: { operationId } } = spec

    if (process.env.NODE_ENV === 'test') {
      if (operationId === 'httpGet') {
        // Return a mocked out Response object, which the caller client can use with all standard fetch response interfaces
        return () => new Response(
           JSON.stringify(getExampleFromSpec(spec, process.env.TEST_SCENARIO)), 
           { 
              status: getStatusFromSpec(spec, process.env.TEST_SCENARIO) 
           }
        )
      }
    }

    return fetch
  }
})

@billxinli billxinli force-pushed the feat/client-factory branch from d4e1fc3 to d83fd6a Compare March 17, 2022 04:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant