@ventlio/tanstack-query 0.2.63-beta.7 → 0.2.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ventlio/tanstack-query",
3
- "version": "0.2.63-beta.7",
3
+ "version": "0.2.64",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "contributors": [
@@ -1,7 +1,10 @@
1
1
  export interface QueryModelBuilder<T> {
2
+ add: (data: T, position?: QueryModelAddPosition, path?: string) => T | undefined;
2
3
  findAll: (path?: string) => T[] | undefined;
3
4
  findMany: (selector: (record: T) => boolean, path?: string) => T[];
4
5
  find: (id: number | string, path?: string) => T | undefined;
5
6
  update: (id: number | string, data: Partial<T>, path?: string) => T | undefined;
6
7
  remove: (id: number, path?: string) => boolean;
7
8
  }
9
+
10
+ export type QueryModelAddPosition = 'start' | 'end';
@@ -2,7 +2,7 @@ import { useQueryClient } from '@tanstack/react-query';
2
2
  import result from 'lodash.result';
3
3
  import set from 'lodash.set';
4
4
  import type { TanstackQueryConfig } from '../types';
5
- import type { QueryModelBuilder } from './model.interface';
5
+ import type { QueryModelAddPosition, QueryModelBuilder } from './model.interface';
6
6
  import { useKeyTrackerModel } from './useKeyTrackerModel';
7
7
 
8
8
  export const useQueryModel = <T>(keyTracker: string, exact: boolean = true): QueryModelBuilder<T> => {
@@ -10,6 +10,26 @@ export const useQueryModel = <T>(keyTracker: string, exact: boolean = true): Que
10
10
  const { getQueryKey } = useKeyTrackerModel(keyTracker);
11
11
  const queryKey = getQueryKey() as any[];
12
12
 
13
+ const add = (data: T, position?: QueryModelAddPosition, path?: string): T | undefined => {
14
+ let records = findAll(path) ?? [];
15
+
16
+ if (!position || position === 'end') {
17
+ records = [...records, data];
18
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
19
+ } else if (position === 'start') {
20
+ records = [data, ...records];
21
+ }
22
+
23
+ if (!path) {
24
+ queryClient.setQueryData(queryKey, records);
25
+ } else {
26
+ const queryData = queryClient.getQueryData(queryKey, { exact }) ?? {};
27
+ queryClient.setQueryData(queryKey, set(queryData, path, records));
28
+ }
29
+
30
+ return data;
31
+ };
32
+
13
33
  const findAll = (path?: string): T[] | undefined => {
14
34
  const data = queryClient.getQueryData(queryKey, { exact });
15
35
 
@@ -104,5 +124,5 @@ export const useQueryModel = <T>(keyTracker: string, exact: boolean = true): Que
104
124
  return updated;
105
125
  };
106
126
 
107
- return { find, findAll, findMany, remove, update };
127
+ return { find, findAll, findMany, remove, update, add };
108
128
  };