apisauce

repository·master·Indexed 25 days ago

https://github.com/infinitered/apisauce

A low-fat wrapper around the Axios HTTP client library for Node, the browser, and React Native. It simplifies API interactions by providing a consistent response flow, standardized error handling via a 'problem' property, and support for request/response transforms and monitors.

Tokens
2.2K
Snippets
6
Records
17
Agent score
34%

What's inside apisauce

  1. Mocking Apisauce with axios-mock-adapter

    master

    When using axios-mock-adapter for testing, you must pass the api.axiosInstance to the adapter instead of the global axios instance to ensure the mocks are applied to your Apisauce instance.

    import apisauce from 'apisauce'
    import MockAdapter from 'axios-mock-adapter'
    
    test('mock adapter', async () => {
      const api = apisauce.create("https://api.github.com")
      const mock = new MockAdapter(api.axiosInstance)
      
      mock.onGet("/repos/skellock/apisauce/commits").reply(200, {
        commits: [{ id: 1, sha: "aef849923444" }],
      });
    
      const response = await api.get('/repos/skellock/apisauce/commits')
      expect(response.data[0].sha).toEqual("aef849923444")
    })
  2. Add Request and Response Transforms

    master

    Transforms allow you to globally mutate request or response data.

    Response Transforms: Can mutate the data property of the response. Use addResponseTransform for synchronous or addAsyncResponseTransform for asynchronous logic.

    Request Transforms: Can mutate data, method, url, headers, and params. Use addRequestTransform or addAsyncRequestTransform.

    Warning: Unlike monitors, exceptions in transforms are NOT swallowed and will interrupt the execution flow.

  3. Cancel an API request

    master

    Use CancelToken from apisauce to cancel ongoing requests.

    import { CancelToken } from 'apisauce'
    
    const source = CancelToken.source()
    const api = create({ baseURL: 'https://github.com' })
    
    api.get('/users', {}, { cancelToken: source.token })
    
    // To cancel the request
    source.cancel()
  4. Handle API responses

    master

    Apisauce promises always resolve with a response object, even if the request failed. This allows you to use a single .then() flow instead of separate .catch() blocks.

    Every response contains:

    • ok: Boolean (true if status is 200-299)
    • problem: String (error code)

    If the request reached the server, the response also includes:

    • data: The response body
    • status: HTTP status code
    • headers: Response headers
    • config: The axios config used
    • duration: Request duration in ms

    If an error occurred at the axios level, you can access originalError.

  5. Create an API instance with `create()`

    master
    Initialize an API instance by calling create() with a configuration object. The baseURL is the only required property. You can also provide default headers, a timeout in milliseconds, or a custom axiosInstance.
  6. Add Monitors to the API

    master
    Monitors are functions called before a promise resolves. They allow you to inspect requests and responses (e.g., for logging or performance monitoring) without modifying them. Monitors are wrapped in a try/catch block, so exceptions inside a monitor will not break the API request flow.
  7. Change Base URL and Headers

    master

    You can dynamically update the base URL or headers on an existing API instance using setBaseURL, setHeader, or setHeaders. These changes persist on the instance.

    // Change Base URL
    api.setBaseURL('https://some.other.place.com/api/v100')
    const currentUrl = api.getBaseURL()
    
    // Change Headers
    api.setHeader('Authorization', 'the new token goes here')
    api.setHeaders({
      Authorization: 'token',
      'X-Even-More': 'hawtness',
    })
  8. Reference: Problem Codes

    master

    The problem property on responses indicates the type of error. These values are available as constants on your API instance.

    Constant        VALUE               Status Code   Explanation
    ----------------------------------------------------------------------------------------
    NONE             null               200-299       No problems.
    CLIENT_ERROR     'CLIENT_ERROR'     400-499       Any non-specific 400 series error.
    SERVER_ERROR     'SERVER_ERROR'     500-599       Any 500 series error.
    TIMEOUT_ERROR    'TIMEOUT_ERROR'    ---           Server didn't respond in time.
    CONNECTION_ERROR 'CONNECTION_ERROR' ---           Server not available, bad dns.
    NETWORK_ERROR    'NETWORK_ERROR'    ---           Network not available.
    CANCEL_ERROR     'CANCEL_ERROR'     ---           Request has been cancelled.
  9. Initialize an API client with create()

    master
    Use create() to initialize a new Apisauce client. You can pass a configuration object that includes headers, timeout, or an existing axiosInstance. If an axiosInstance is provided, Apisauce will wrap it; otherwise, it creates a new one using the provided config and merges it with DEFAULT_HEADERS (application/json).
  10. Map HTTP status codes to error constants

    master

    Use getProblemFromStatus(status) to determine the nature of a response based on its HTTP status code.

    • 200-299: Returns NONE (null).
    • 400-499: Returns CLIENT_ERROR.
    • 500-599: Returns SERVER_ERROR.
    • Other/Undefined: Returns UNKNOWN_ERROR.