Giter VIP home page Giter VIP logo

thesharpieone / batshit Goto Github PK

View Code? Open in Web Editor NEW

This project forked from yornaath/batshit

1.0 0.0 0.0 62.84 MB

A batch manager that will deduplicate and batch requests for a certain data type made within a window. Useful to batch requests made from multiple react components that uses react-query

Home Page: https://batshit-example.vercel.app/

License: MIT License

JavaScript 8.53% TypeScript 90.47% HTML 1.00%

batshit's Introduction

@yornaath/batshit CI

A batch manager that will deduplicate and batch requests for a given data type made within a window of time (or other custom scheduling). Useful to batch requests made from multiple react components that uses react-query or do batch processing of accumulated tasks.

Codesandbox example

Here is a codesanbox example using react, typescript, vite and the zeitgeist prediction-markets indexer api. It fetches markets up front and then batches all liquidity pool fetches made from the individual components into one request.

Codesandbox

Example with devtools

Example using zeitgeist market and pool data with included devtools to inspect the batching process. The working live code for the example linked below can be found in ./packages/example

Vercel Example app

Install

yarn add @yornaath/batshit

Quickstart

Here we are creating a simple batcher that will batch all fetches made within a window of 10 ms into one request.

import { create, keyResolver, windowScheduler } from "@yornaath/batshit";

type User = { id: number; name: string };

const users = create<User, number>({
  fetcher: async (ids) => {
    return client.users.where({
      id_in: ids,
    });
  },
  resolver: keyResolver("id"),
  scheduler: windowScheduler(10), // Default and can be omitted.
});

/**
 * Requests will be batched to one call since they are done within the same time window of 10 ms.
 */
const bob = users.fetch(1);
const alice = users.fetch(2);

const bobUndtAlice = await Promise.all([bob, alice]);

await delay(100);

/**
 * New Requests will be batched in a another call since not within the first timeframe.
 */
const joe = users.fetch(3);
const margareth = users.fetch(4);

const joeUndtMargareth = await Promise.all([joe, margareth]);

React(query) Example

Here we are also creating a simple batcher that will batch all fetches made within a window of 10 ms into one request. Since all items are rendered in one go their individual fetches will be batched into one request.

Note: a batcher for a group of items should only be created once. So creating them inside hooks wont work as intended.

import { useQuery } from "react-query";
import { create, windowScheduler } from "@yornaath/batshit";

const users = create<User, number>({
  fetcher: async (ids) => {
    return client.users.where({
      userId_in: ids,
    });
  },
  resolver: keyResolver("id"),
  scheduler: windowScheduler(10),
});

const useUser = (id: number) => {
  return useQuery(["users", id], async () => {
    return users.fetch(id);
  });
};

const UserDetails = (props: { userId: number }) => {
  const { isFetching, data } = useUser(props.userId);
  return (
    <>
      {isFetching ? (
        <div>Loading user {props.userId}</div>
      ) : (
        <div>User: {data.name}</div>
      )}
    </>
  );
};

/**
 * Since all user details items are rendered within the window there will only be one request made.
 */
const UserList = () => {
  const userIds = [1, 2, 3, 4];
  return (
    <>
      {userIds.map((id) => (
        <UserDetails userId={id} />
      ))}
    </>
  );
};

Fethcing with needed context

If the batch fetcher needs some context like an sdk or client to make its fetching you can use a memoizer to make sure that you reuse a batcher for the given context in the hook calls.

import { useQuery } from "@tanstack/react-query";
import { memoize } from "lodash-es";
import * as batshit from "@yornaath/batshit";

export const key = "markets";

const batcher = memoize((sdk: Sdk<IndexerContext>) => {
  return batshit.create<Market, number>({
    name: key,
    fetcher: async (ids) => {
      const { markets } = await sdk.markets({
        where: {
          marketId_in: ids,
        },
      });
      return markets;
    },
    scheduler: batshit.windowScheduler(10),
    resolver: batshit.keyResolver("marketId"),
  });
});

export const useMarket = (marketId: number) => {
  const [sdk, id] = useSdk();

  const query = useQuery(
    [id, key, marketId],
    async () => {
      if(sdk) {
        return batcher(sdk).fetch(marketId);
      }
    },
    {
      enabled: Boolean(sdk),
    },
  );

  return query;
};

Custom Batch Resolver

This batcher will fetch all posts for multiple users in one request and resolve the correct list of posts for the discrete queries.

const userposts = create<mock.Post, { authorId: number }, mock.Post[]>({
  fetcher: async (queries) => {
    return api.posts.where({
      authorId_in: queries.map((q) => q.authorId),
    });
  },
  scheduler: windowScheduler(10),
  resolver: (posts, query) =>
    posts.filter((post) => post.authorId === query.authorId),
});

const [alicesPosts, bobsPost] = await Promise.all([
  userposts.fetch({authorId: 1})
  userposts.fetch({authorId: 2})
]);

React Devtools

Tools to debug and inspect the batching process can be found in the @yornaath/batshit-devtools-react package.

yarn add @yornaath/batshit-devtools @yornaath/batshit-devtools-react
import { create, keyResolver, windowScheduler } from "@yornaath/batshit";
import BatshitDevtools from "@yornaath/batshit-devtools-react";

const batcher = create<Data, number>({
  fetcher: async (queries) => {...},
  scheduler: windowScheduler(10),
  resolver: keyResolver("id"),
  name: "batcher:data" // used in the devtools to identify a particular batcher.
});

const App = () => {
  <div>
    <Data batcher={batcher} />
    <BatshitDevtools />
  </div>
}

batshit's People

Contributors

yornaath avatar

Stargazers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.