elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

Difference between middleware / resolvers #22

Closed dredzone closed 6 years ago

dredzone commented 6 years ago

First, great little library thanks for the work.

Question, what is main diference between middleware / resolvers, when one should be used vs another?

Thanks.

elbywan commented 6 years ago

First, great little library thanks for the work.

Thanks ! đź‘Ť

Question, what is main diference between middleware / resolvers, when one should be used vs another?

Middleware are used to perform an action before the request is performed. Resolvers are used to program a chain of actions that are executed after the request completion.

Examples:

Before the request

/* A simple delay middleware. */
const delayMiddleware = delay => next => (url, opts) => {
  return new Promise(res => setTimeout(() => res(next(url, opts)), delay))
}

// The request will be delayed by 1 second.
wretch("...").middlewares([
  delayMiddleware(1000)
]).get().res(_ => /* ... */)

After, on the response

// Program "response" chain actions early on
const w = wretch()
  .resolve(resolver => resolver
    .perfs(_ =>  /* monitor every request */)
    .json(_ => _ /* automatically parse and return json */))

const myJson = await w.url("http://a.com").get()
// Equivalent to wretch()
//  .url("http://a.com")
//  .get()
//     <- the resolver chain is automatically injected here !
//  .perfs(_ =>  /* ... */)
//  .json(_ => _)
dredzone commented 6 years ago

Thanks for quick response,

But middleware also has access to response object, see below snippet, can resolver logic go in there?

basically the whole response-chain can be a set of middlewares, or do I missing something?

const middleware = () => next => (url, opts) => {
  return next(url, opts).then(response => {
   // perform resolve logic
  });
}
elbywan commented 6 years ago

basically the whole response-chain can be a set of middlewares, or do I missing something?

Except that middlewares have only access to the vanilla fetch response, not the wretch one. So yes, you can put some logic in the middlewares that will come just after the response is retrieved.

But be aware that :

Basically things happen in this order :

1) You define wretch request options (url / parameters / fetch options …), resolvers, catchers, middlewares first. 2) Calling .get/.post/.put… triggers a fetch call - but before that if middlewares were defined the middleware chain is executed here. 3) The request is on the fly now. 4) After the response is received, if you chained something using .then in the middlewares, then the action will be executed here. (This part has only access to the raw fetch response) 4) If you defined resolvers, they will be executed here. 5) Rest of the wretch specific function chain is executed here (error catchers / body parsing).

dredzone commented 6 years ago

Thanks for quick responses.