Coder Social home page Coder Social logo

fetch-wrap's Issues

Using the Header object breaks header merging

Using the header object in a fetch call

    headers: new Headers(
        {
          "Content-Type": "application/json",
         }
      ),

instead of just

    headers: {
        "Content-Type": "application/json",
       }

will cause the merging of headers as show in the documentation to fail. Only the header(s) given in the fetch call will be used.

If a fix or warning for this is not desirable, could it be at least mentioned in the documentation? Depending on which solution you prefer I will gladly create a pull request.

es6 feature in middleware

Hi, I'm having a problem serving my webpack bundle to older browsers. I'm using your library but because of one little "const" in middleware.js it breaks.

const reviver = (receiveOptions && typeof receiveOptions.reviver !== undefined)

Would it be possible to replace "const" here with var?

Add TypeScript support

I wonder how one could make this a little bit more type-safe by having the middleware actually know the types of the arguments and the supposed return value (Promose<Response>).

I have started with this:

// This should be exported by "fetch-wrap" as a type
type FetchFunction = typeof fetch

export function logHeaders() {
  return function(url: string, options:RequestInit = {}, fetch: FetchFunction):Promise<Response> {
  }
}

Can merge be replaced by ES6 destructuring?

I wonder if the usage of lodash/merge is obsolete for the operations most middlewares do here?
They usually don't do deep merges so couldn't

return fetch(url, extendedFetch.merge({}, options, {
  headers: {
    "Authorization": "Bearer ...",
  }
}))

be replaced with:

return fetch(url, {
  ...options,
  headers: {
    ...options.headers,
    "Authorization": "Bearer ...",
  }
}))
it.only("should not matter", () => {
    const options = {
      body: "Test",
      headers: {
        "Accept": "text/plain",
      },
    }
    expect(extendFetch.merge({}, options, {
      headers: {
        "Content-Type": "text/plain",
      },
    })).toEqual({
      ...options,
      headers: {
        ...options.headers,
        "Content-Type": "text/plain",
      },
    })
  })

Ordering of Middleware

I was curious about the order in which middleware is being applied by fetch-wrap. This is an awesome library that we use heavily for our projects. We ran into a curious case where it seems that custom middleware would need to be applied in reverse-order, bottom-to-top, instead of top-to-bottom. For example:

const newFetch = fetchWrap(originalFetch, [
  doFirstThing(),
  doSecondThing(),
  doThirdThing()
]);

This would first call doThirdThing, then proceed backwards. Is this the intended behavior? I would hesitate to call it a "bug", since I see the test expectations in the repository that mimic these results. I have forked the repo and created a new test to better illustrate what I mean:

https://github.com/drewmoore/fetch-wrap/blob/1dfd6648d426d16a3981a18d058422118053dddc/test/middleware.js#L353

If this is something that you and the community would like to have adjusted, I would be happy to take a stab at it and submit a pull request.

Implementing a token refresh logic inside a middleware

I'd like to implement an OpenID-Connect refresh logic inside a middleware that adds an Access Token to a request and reacts on 401 responses by fetching a new access token and repeating the request with the new token.

However, inside the middleware I only have access to the "next" middleware in the chain and not the "start" of the middleware chain, so middleware that would transform bodies would not work.

function middleware() {
  return function(url:string, options: RequestInit, next: FetchFunction) {
    const fetch = next
    if (accessToken) {
      options = {
        ...options,
        headers: {
          ...options.headers,
          "Authorization": "Bearer " + accessToken,
        },
      }
    }
    return next(url, options).then(response => {
      if (response.status === 401 && refreshToken) {
        return fetch(tokenURI, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: {
            grant_type: "refresh_token",
            client_id: clientId,
            client_secret: clientSecret,
            refresh_token: refreshToken,
          },
        })
      } else {
        return response
      }
    })
  }
}

I have a sendFormEncoded middleware that should take care of converting an object body to urlencoded but its not triggered in my request to fetch a new access token. Any idea how to hand in the original start of the middle ware chain into each middleware?

Connecting with redux

Can you tell me how can I connect this wrapper with Redux. I want to have in separate file this wrapper and I need to dispatch some actions inside function for example for adding header.

File should looks like this but I'm getting dispatch is not defined error:

import { authGetToken } from "../store/actions/index";
const fetchWrap = require("fetch-wrap");

customFetch = fetchWrap(fetch, [
  function(url, options, fetch) {
    // add headers
    console.log("In fetch wrap!");
    dispatch(authGetToken())
      .then(token => {
        return fetch(
          url,
          fetchWrap.merge({}, options, {
            headers: {
              Authorization: "bearer " + token
            }
          })
        );
      })
      .catch(err => {
        console.log("Error while trying to get token with AuthGetToken");
      });
  },
]);
export default customFetch;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.