BetterTyped / hyper-fetch

⚡ Fetching and realtime data exchange framework.
https://hyperfetch.bettertyped.com/
Apache License 2.0
1.02k stars 27 forks source link

Support for Hypertext Application Language (HAL) resource links #45

Closed stefanullinger closed 1 year ago

stefanullinger commented 1 year ago

Hi, in my current project, I am asked to use HAL resource links to load more items for a resource.

These resource links contain a full URL. The problem is, that the Hyper Fetch client already contains a baseURL for all request, which then ends up being prepended to the full URL of the resource links.

I would like to know, if there already is a way to request these resource URLs using the same client and without modifying the URL before the request is made by the HyperFetch client.

For example, imagine there is a books resource and I would like to show a paginated list of books. Requesting the books resource, the API would response with something like this:

{
  "_links":{
    "self":{
      "href":"https://my.api/books?page=1&size=10&sort=desc"
    },
    "next":{
      "href":"https://my.api/books?page=2&size=10&sort=desc"
    },
    "first":{
      "href":"https://my.api/books?page=1&size=10&sort=desc"
    },
    "last":{
      "href":"https://my.api/books?page=4&size=10&sort=desc"
    }
  },
  "_embedded":{
    "books":[
      {
        "id": 0,
        "_links":{
          "self":{
            "href":"https://my.api/books/0"
          }
        }
      },
      ...
    ]
  },
  "page":{
    "size":10,
    "totalElements":35,
    "totalPages":4,
    "number":1,
    "requestedPageSize":10
  }
}

After getting the response, I would like to grab the URL of _links.next.href and request the next books from the API.

Is there any way to do this with HyperFetch without replacing the base URL of this URL string?

prc5 commented 1 year ago

Hey! You can take the query part out of the link and pass it as queryParams.

I imagine it as something like that:

  1. Prepare query params
    const next = 'https://my.api/books?page=1&size=10&sort=desc'
    const queryParams = next.split("?")[1];  // No worries, HF will automatically add question mark in the final query
  2. Add them to your request
    
    const getBooks = client.createRequest()({ endpoint: '/books' })

getBooks.setQueryParams(queryParams); // Use prepared query params, everything will get cached and handled by HF



However, there is no direct method to take `_links.next.href` and put it directly into request, HF requires declarations first.

I hope this help! 👍🏻 
stefanullinger commented 1 year ago

Hey @prc5, thanks a lot - did not see this option, although it is so obvious!