redux-saga / saga-query

Data synchronization using a middleware system for front-end apps
64 stars 4 forks source link

custom key and hash key #24

Closed VldMrgnn closed 1 year ago

VldMrgnn commented 1 year ago

This PR adresses two distinct issues

1. The user will have the ability to define a custom key

There are cases when the saga-query key is needed in dev functions, in order to distinguish between similar requests and differentiate the datasets. In other cases is useful when operating directly with cached datasets and there is a need for customize the cache store selectors. Also in some custom caching middleware or used as a marker in the request to the backend. Overall it is important to give the developer the freedom to operate.

If the custom key is provided then it will be used. Otherwise the default one will be applied. The usage of the custom key:

const query = createApi();
  query.use(requestMonitor());
  query.use(query.routes());
  query.use(customKey);
 //...

const createUserCustomKey = query.post<{ email: string }>(
    `/users`,
    function* processUsers(ctx: ApiCtx<any, any>, next) {
      ctx.cache = true;
      ctx.key = 'MY_CUSTOM_KEY'; 
      yield next();
     //...
    },
  );

Alternatively the customKey middleware can be set as default inside the requestMonitor middleware, similar with the simpleCache middleware. In such case the developer should not care to include the middleware in the api definition. The simple definition of the key being enough to override the default key.

2. In the absence of a custom defined key, saga-query will create default hash key.

This feature replaces the existing base64 key with a hashed one. The main reason for this feature is the case of large fetch query parameters. When base64 encoded this will generate a large key in the store.

Having both features available, the developer can choose between implementing its 'own keys, when more fine tuning in needed, or letting the saga-query to create the key.