3.1.5 • Published 9 years ago

@rill/fetcher v3.1.5

Weekly downloads
6
License
MIT
Repository
github
Last release
9 years ago

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!

4.1.0

8 years ago

4.0.2

9 years ago

4.0.1

9 years ago

4.0.0

9 years ago

3.1.8

9 years ago

3.1.7

9 years ago

3.1.6

9 years ago

3.1.5

9 years ago

3.1.4

9 years ago

3.1.3

9 years ago

3.1.2

9 years ago

3.1.1

9 years ago

3.1.0

9 years ago

3.0.6

9 years ago

3.0.5

9 years ago

3.0.4

9 years ago

3.0.3

9 years ago

3.0.2

9 years ago

3.0.1

9 years ago

3.0.0

9 years ago

2.0.0

10 years ago

1.0.3

10 years ago

1.0.2

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago

0.2.0

10 years ago

0.1.3

10 years ago

0.1.2

10 years ago

0.1.1

10 years ago

0.1.0

10 years ago