Skip to content

🎣 Universal fetch api utility for Rill.

Notifications You must be signed in to change notification settings

rill-js/fetcher

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

49 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rill
@rill/fetcher
API stability Standard NPM version Downloads Gitter Chat

Fetch wrapper for Rill that allows intercepting requests and automatic FormData casting.

Installation

npm install @rill/fetcher

Example

const rill = require('rill')
const app = rill()
const fetcher = require('@rill/fetcher')

app.use(fetcher({
  name: 'api',
  base: '/api/'
}))

app.use(async ({ api }, next)=> {
  // Fetcher is an event emitter so you can intercept requests and responses.
  // Listeners are cleaned up on every request.

  // Example request intercept.
  api.on('request', (url, req)=> {
    // req is the options provided to the fetch request.
    req.headers.auth = '...'
  })

  // Example response intercept.
  api.on('response', (url, res)=> {
    // res is the response from a fetch request.
    console.log(res.headers.get('x-error-message'))
  })

  // Example fetch. (Options similar to natvie fetch).
  const response = await api('user', {
    method: 'GET', // Set method (GET is default).
    query: { a: 1 }, // Append a query string.
    body: { b: 2 }, // Set the request body.
    files: { c: ... }, // Set a FormData file (gets added to the formdata body).
    headers: { 'x-custom-header': 1 } // Set some headers.
  })

  // Parse api response as json (same as native fetch).
  const data = await response.json()
})

// Using https://github.com/DylanPiercey/isbrowser.
if (!process.browser) {
  // Handle the `user` api only in the server.
  app.get('/api/user', ({ req, res })=> {
    // Check out https://github.com/rill-js/forwarded-from to ensure consistent `ctx.req.ip` across api calls.
    res.body = { user: 'data' }
  })
}

Options (Defaults)

{
  name: 'fetch', // Optional path to set the fetcher on the context (default 'fetch').
  base: '/', // Sets the base path for the fetcher.
  forwardIP: true, // Set this to false to disable setting 'X-Forwarded-For' header
  forwardHost: true, // Set this to false to disable setting 'X-Forwarded-Host' header automatically.
  withCredentials: true, // Set this to false to disable sending cookies. (Uses same-origin).
  agent: {
    // Optionally specify a custom http(s) agent (nodejs only).
    // Both default to 'agentkeepalive' for optimum performance for local requests.
    // Set `agent: false` to disable the keepalive agent.
    http: ...,
    https: ...
  }
}

Contributions

  • Use npm test to run tests.

Please feel free to create a PR!

About

🎣 Universal fetch api utility for Rill.

Resources

Stars

Watchers

Forks

Packages

No packages published