ReSift

ReSift

  • Docs
  • API
  • Help
  • GitHub

›Guides

Introduction

  • What is ReSift?
  • Installation

Tutorial

  • ReSift Rentals

Main Concepts

  • What's a fetch?
  • How to define a fetch
  • Making state consistent
  • Making sense of statuses
  • What are data services?
  • Error handling
  • Custom hooks

Examples

  • ReSift Notes (CRUD)
  • Infinite scroll
  • Custom hooks and React Router

Guides

  • ReSift vs Apollo and Relay
  • HTTP proxies
  • Usage with TypeScript
  • Usage with Redux
  • Usage with classes

API

  • About these docs
  • useStatus
  • useError
  • useDispatch
  • useData
  • useClearFetch
  • isUnknown
  • isNormal
  • isLoading
  • isError
  • defineFetch
  • dataServiceReducer
  • createStoreKey
  • createHttpService
  • createHttpProxy
  • createDataService
  • createActionType
  • combineStatuses
  • ResiftProvider
  • Guard
  • CanceledError
  • UNKNOWN
  • NORMAL
  • LOADING
  • ERROR
Edit

HTTP proxies

HTTP proxies is a feature of the HTTP data service.

HTTP proxies allow you to intercept http data service calls within fetches and potentially do something else.

You can define an HTTP proxy by calling createHttpProxy from ReSift.

A common use case of HTTP proxies is to use them for mocking an HTTP server. We use HTTP proxies to power the demos in these docs.

mockApi.js

import { createHttpProxy } from 'resift';

export const mockPeopleEndpoint = createHttpProxy(
  '/people/:personId',
  async ({ match, requestParams, http }) => {
    // ...
  },
);

After you create your proxy, add it to the proxies array when you create the HTTP service:

import { createDataService, createHttpService } from 'resift';
import { mockPeopleEndpoint } from './mockApi';

const http = createHttpService({
  proxies: [mockPeopleEndpoint],
});

const dataService = createDataService({
  services: { http },
  onError: (e) => {
    throw e;
  },
});

export default dataService;

createHttpProxy API

When you create an HTTP proxy, you provide a path (a string) or path options. This argument determines whether or not the proxy will run. The HTTP service will iterate through the proxies until it finds a match. The first match found will be the proxy it uses. If an http call matches this path, the second argument, the handler, will run.

The matching algorithm is a blatant copy/paste of react-router's matchPath

In the handler, you can destructure: requestParams, http, match, and more

  • The requestParams are the parameters the caller (in the data service) passes to the http call
  • http is the original http service. You can call it to make an actual HTTP request.
  • match is the result of react-router's matchPath function. It contains the match params in match.params

Here are some example mock endpoints from the ReSift Notes example.

import { createHttpProxy } from 'resift';
import shortId from 'shortid';
import delay from 'delay';
import moment from 'moment';
import { stripIndent } from 'common-tags';

const waitTime = 1000;

let noteData = [
  {
    id: 'sJxbrzBcn',
    content: stripIndent`
      # This is a note
    `,
    updatedAt: moment().toISOString(),
  },
];

export const notes = createHttpProxy({ path: '/notes', exact: true }, async ({ requestParams }) => {
  await delay(waitTime);

  const { method, data } = requestParams;

  if (method === 'GET') {
    // send a shallow copy just in case.
    // with a real API, the object returned would always be fresh references
    return [...noteData];
  }

  if (method === 'POST') {
    const newNote = {
      ...data,
      id: shortId(),
    };
    noteData.push(newNote);

    return newNote;
  }
});

export const note = createHttpProxy('/notes/:id', async ({ requestParams, match }) => {
  await delay(waitTime);

  const { method, data } = requestParams;
  const { id } = match.params;

  if (method === 'GET') {
    const note = noteData.find((note) => note.id === id);
    if (!note) throw new Error('Not Found');

    return note;
  }

  if (method === 'PUT') {
    const index = noteData.findIndex((note) => note.id === id);
    if (index === -1) throw new Error('Not Found');

    noteData[index] = data;
    return data;
  }

  if (method === 'DELETE') {
    const note = noteData.find((note) => note.id === id);
    if (!note) throw new Error('Not Found');

    noteData = noteData.filter((note) => note.id !== id);
    return undefined;
  }
});
Last updated on 4/1/2020
← ReSift vs Apollo and RelayUsage with TypeScript →
  • createHttpProxy API
ReSift
Docs
What is ReSift?What's a fetch?API
Community
Ask a questionOpen an issue@ meLeave feedback
More
StarBuild StatusCoverage Status
Copyright © 2021 Sift
www.justsift.com