Sapper isomorphic fetch library
In sapper, there are three different ways of fetching data:
- isomorphic (client + server)
- retries (on various network errors)
This library helps you abstract over where you are fetching data, meaning that your code maintains consistency without having to worry about where your data is being fetched.
The way it does this is by trying to use the first available fetch method, and failing over to alternatives if a method is not available. The methods it tries are, in the following order:
- Any fetch library you pass to
- window.fetch if the library detects it is running clientside
node-fetch, or whatever you want to pass in, if nothing else is available (pure server-side)
Generally this means that your usage is the same no matter where you call it, with one exception - using this library in the
preload method requires you to pass in Sapper's special
this.fetch method, as it is not available outside of the preload method. Examples of which are below.
To use within a Sapper application:
npm i -D @beyonk/sapper-httpclient
Configure it (both server-side and client-side as there are two bundles)
// src/client.js && src/server.jsApi
Use it on the client:
// src/routes/some-route.html// in a method (client-side)const api =const json = await apiconsole// in preload (Svelte v2) (isomorphic)const api =const json = await api// Use sapper's built in "fetch" methodconsole// in preload (Svelte v3) (isomorphic)const api =const json = await api// Use sapper's built in "fetch" methodconsole
Use it on the server:
// src/routes/some-route.jsconst api =const json = await api// pass node fetch in here.console
const api =const client = apiconsole // Get endpointconsole // Put with bodyconsole // Post with bodyconsole // Get with queryconsole // Deleteconsole // Put with headers
query method accepts an object of params as either a String or Array of Strings.
If any property passed into the query is
undefined it will be ignored.
const api =const client = apiconsole // will make a GET request to 'some/endpoint?foo=bar'console // will make a GET request to 'some/endpoint?foo=bar&baz=quxconsole // will make a GET request to 'some/endpoint?foo=bar&foo=quxconsole // will make a GET request to 'some/endpoint?baz=qux
Using built in response handling
const api =const profile = await apiconsole
As of v5.0.0, the http client can retry if a network error is encountered. The default is
retry: false, and requests won't be retried.
Configure it as follows:
errors is an array of any number of the nodejs network error codes
- Original code by Antony Jones