cujojs / rest

RESTful HTTP client for JavaScript
http://cujojs.com/
Other
1k stars 146 forks source link

Access methods of interceptor #183

Closed Doogiemuc closed 6 years ago

Doogiemuc commented 6 years ago

I have written a cachingInterceptor. Basically my interceptor is structured very similar to the pathPrefix.js example.

The pathPrefix example has two "private" methods startsWidth() and endsWith(). My cachingInterceptor als has methods like this, e.g. purgeCache() or setTTL()

=> How can I make these methods accessible from a module that only knonws the outer cujoJS rest "client". I mean, the client that might be wrapped in several interceptors.

var client = rest.wrap(mime, { mime: 'application/json'} )  // then convert entity according to mime type
                 .wrap(cachingInterceptor)      // caching interceptor must be BEFORE the mime interceptor!
                 .wrap(errorCode)               // Promise.reject() responses with http status code >= 400 
                 .wrap(logRequestsInterceptor, { logPayload: true })  // first of all log the request
                 .wrap(pathPrefix, { prefix: process.env.backendBaseURL })  // add path prefix to request

// <= how can I access the purgeCache() method inside my cachingInterceptor  from here, knowing only the client variable?
Doogiemuc commented 6 years ago

Still no idea. Please help. Anyone?

scothis commented 6 years ago

Interceptors can receive configuration when they wrap a client. That config is passed into each interceptor phase method.

const cachingInterceptor = interceptor({
  request(req, config) {
    ...
  },
  response(res, config) {
    ...
  }
});

rest.wrap(cachingInterceptor, { cache: cacheImpl })
Doogiemuc commented 6 years ago

Thank you for that tip. It worked fine.