@mobx-query/core 0.2.0

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.
Files changed (58) hide show
  1. package/.gitattributes +2 -0
  2. package/README.md +98 -0
  3. package/eslint.config.js +29 -0
  4. package/index.html +13 -0
  5. package/package.json +60 -0
  6. package/public/vite.svg +1 -0
  7. package/src/App.css +0 -0
  8. package/src/App.tsx +5 -0
  9. package/src/api/constants.ts +1 -0
  10. package/src/api/fetch.ts +29 -0
  11. package/src/api/todos.ts +14 -0
  12. package/src/api/types.ts +30 -0
  13. package/src/api/users.ts +19 -0
  14. package/src/assets/react.svg +1 -0
  15. package/src/index.css +60 -0
  16. package/src/libs/mobx-query/client/MQClient.ts +75 -0
  17. package/src/libs/mobx-query/client/MQClientAccessor.ts +74 -0
  18. package/src/libs/mobx-query/client/index.ts +8 -0
  19. package/src/libs/mobx-query/client/types.ts +37 -0
  20. package/src/libs/mobx-query/entity/Entity.ts +232 -0
  21. package/src/libs/mobx-query/entity/EntityCollection.ts +285 -0
  22. package/src/libs/mobx-query/entity/constants.ts +7 -0
  23. package/src/libs/mobx-query/entity/index.ts +15 -0
  24. package/src/libs/mobx-query/entity/types.ts +11 -0
  25. package/src/libs/mobx-query/mutations/BatchMutationBase.ts +105 -0
  26. package/src/libs/mobx-query/mutations/BatchUpdateMutation.ts +48 -0
  27. package/src/libs/mobx-query/mutations/CreateMutation.ts +172 -0
  28. package/src/libs/mobx-query/mutations/DeleteMutation.ts +94 -0
  29. package/src/libs/mobx-query/mutations/EntityMutationBase.ts +110 -0
  30. package/src/libs/mobx-query/mutations/MutationBase.ts +40 -0
  31. package/src/libs/mobx-query/mutations/OptimisticMutationStrategy.ts +122 -0
  32. package/src/libs/mobx-query/mutations/UpdateMutation.ts +76 -0
  33. package/src/libs/mobx-query/mutations/constants.ts +16 -0
  34. package/src/libs/mobx-query/mutations/index.ts +44 -0
  35. package/src/libs/mobx-query/mutations/types.ts +205 -0
  36. package/src/libs/mobx-query/queries/QueryBase.ts +65 -0
  37. package/src/libs/mobx-query/queries/QueryFragmentMany.ts +31 -0
  38. package/src/libs/mobx-query/queries/QueryFragmentOne.ts +35 -0
  39. package/src/libs/mobx-query/queries/QueryMany.ts +80 -0
  40. package/src/libs/mobx-query/queries/QueryManyBase.ts +135 -0
  41. package/src/libs/mobx-query/queries/QueryOne.ts +84 -0
  42. package/src/libs/mobx-query/queries/QueryOneBase.ts +93 -0
  43. package/src/libs/mobx-query/queries/index.ts +33 -0
  44. package/src/libs/mobx-query/queries/types.ts +60 -0
  45. package/src/libs/mobx-query/react/createReactContext.tsx +23 -0
  46. package/src/libs/mobx-query/react/index.ts +3 -0
  47. package/src/libs/mobx-query/utils/generateEntityId.ts +12 -0
  48. package/src/libs/mobx-query/utils/index.ts +8 -0
  49. package/src/libs/mobx-query/utils/invalidateQueryByHash.ts +18 -0
  50. package/src/libs/mobx-query/utils/types.ts +18 -0
  51. package/src/libs/react-query.ts +11 -0
  52. package/src/main.tsx +16 -0
  53. package/src/utils.ts +3 -0
  54. package/src/vite-env.d.ts +1 -0
  55. package/tsconfig.app.json +27 -0
  56. package/tsconfig.json +7 -0
  57. package/tsconfig.node.json +25 -0
  58. package/vite.config.ts +52 -0
package/.gitattributes ADDED
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
package/README.md ADDED
@@ -0,0 +1,98 @@
1
+ # DISCLAIMER: This project is still in development and I don't know when I'm going to finish it, but still feel free to check it out.
2
+
3
+ # mobx-query
4
+
5
+ **Combine the best of react-query and mobx** — mobx-query provides a thin integration layer that uses React Query for fetching/invalidations and MobX for storing and mutating observable entities. It supports optimistic mutations with automatic rollbacks on error and automatic invalidation of dependent queries on success.
6
+
7
+ # Features
8
+
9
+ - Normalize query responses into a single observable Map per collection.
10
+
11
+ - Hooks make it easy to work with data. Use [useSuspenseQueryEntitiesList](#sample-section) and [useSuspenseQueryEntity](#sample-section) to fetch and hydrate entities. For mutations, [useCreateMutation](#sample-section) and [useDeleteMutation](#sample-section) handle collection-level changes with optimistic updates and invalidations, while [useUpdateMutation](#sample-section) lets you update a single entity directly.
12
+
13
+ - Optimistic updates with automatic query invalidation on successful mutations and rollbacks on error.
14
+
15
+ - Fine-grained, mutable entities powered by MobX (observable fields & actions).
16
+
17
+ # Quick example
18
+
19
+ Create the observable entity and wire it into a collection.
20
+
21
+ ```ts
22
+ // Your observable entity
23
+ class Todo {
24
+ id: number;
25
+ userId: number;
26
+ @observable accessor title: string;
27
+ @observable accessor isCompleted: boolean;
28
+
29
+ constructor(data: TodoDTO) {
30
+ this.id = data.id;
31
+ this.userId = data.userId;
32
+ this.title = data.title;
33
+ this.isCompleted = data.completed;
34
+ }
35
+ }
36
+
37
+ // Collection for a Todo entity
38
+ class TodosCollection extends EntityCollection<TodoDTO, Todo> {
39
+ constructor() {
40
+ super("todos", queryClient, {
41
+ getEntityId: (todo) => todo.id,
42
+ hydrate: (todo) => new Todo(todo), // wrap data from queries into observable states
43
+ });
44
+ }
45
+
46
+ useTodosByUserIdQuery(userId: number) {
47
+ return this.useSuspenseQueryEntitiesList(getTodosByUserId, userId);
48
+ }
49
+
50
+ useDeleteTodoMutation(entity: TodoHydrated) {
51
+ return this.useDeleteMutation(entity, (entity) => deleteTodo(entity.id));
52
+ }
53
+ }
54
+
55
+ type TodoHydrated = EntityHydrated<Todo>;
56
+
57
+ const todosCollection = new TodosCollection();
58
+ ```
59
+
60
+ Use hook from a collection to fetch and retrieve obserbable data
61
+
62
+ ```ts
63
+ const TodosList: React.FC<{ userId: number }> = () => {
64
+ const todos = todosCollection.useTodosByUserIdQuery(userId);
65
+
66
+ return <List items={todos} />;
67
+ };
68
+ ```
69
+
70
+ Mutate entity with automatic queries invalidation on mutation success and rollback on error
71
+
72
+ ```ts
73
+ const TodoListItem: React.FC<{ todo: TodoHydrated }> = ({ todo }) => {
74
+ const deleteTodo = todosCollection.useDeleteTodoMutation(todo);
75
+
76
+ const update = todo.useUpdateMutation(entity => updateTodo(entity));
77
+
78
+ const handleEditTitle = () => {
79
+ const value = prompt("Update title", todo.title);
80
+
81
+ if (value) {
82
+ todo.title = value;
83
+ update();
84
+ }
85
+ };
86
+
87
+ return (
88
+ <div>
89
+ {todo.title}
90
+ <button onClick={handleEditTitle}>
91
+ Edit
92
+ </button>
93
+ <button onClick={deleteTodo}>
94
+ Delete
95
+ </button>
96
+ </div>
97
+ );
98
+ };
@@ -0,0 +1,29 @@
1
+ import js from "@eslint/js";
2
+ import globals from "globals";
3
+ import reactHooks from "eslint-plugin-react-hooks";
4
+ import reactRefresh from "eslint-plugin-react-refresh";
5
+ import tseslint from "typescript-eslint";
6
+ import { globalIgnores } from "eslint/config";
7
+
8
+ export default tseslint.config([
9
+ globalIgnores(["dist"]),
10
+ {
11
+ files: ["**/*.{ts,tsx}"],
12
+ extends: [
13
+ js.configs.recommended,
14
+ tseslint.configs.recommended,
15
+ reactHooks.configs["recommended-latest"],
16
+ reactRefresh.configs.vite,
17
+ ],
18
+ languageOptions: {
19
+ ecmaVersion: 2020,
20
+ globals: globals.browser,
21
+ },
22
+ rules: {
23
+ "@typescript-eslint/no-explicit-any": "off",
24
+ "@typescript-eslint/no-unsafe-function-type": "off",
25
+ "react-hooks/rules-of-hooks": "off",
26
+ "@typescript-eslint/no-empty-object-type": "off",
27
+ },
28
+ },
29
+ ]);
package/index.html ADDED
@@ -0,0 +1,13 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>Vite + React + TS</title>
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script type="module" src="/src/main.tsx"></script>
12
+ </body>
13
+ </html>
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@mobx-query/core",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "author": "smashboy",
6
+ "private": false,
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "scripts": {
11
+ "dev": "vite",
12
+ "build": "tsc -b && vite build",
13
+ "lint": "eslint .",
14
+ "preview": "vite preview"
15
+ },
16
+ "exports": {
17
+ "./client": {
18
+ "import": "./dist/client.js"
19
+ },
20
+ "./entity": {
21
+ "import": "./dist/entity.js"
22
+ },
23
+ "./mutations": {
24
+ "import": "./dist/mutations.js"
25
+ },
26
+ "./queries": {
27
+ "import": "./dist/queries.js"
28
+ },
29
+ "./react": {
30
+ "import": "./dist/react.js"
31
+ },
32
+ "./utils": {
33
+ "import": "./dist/utils.js"
34
+ }
35
+ },
36
+ "dependencies": {
37
+ "@babel/plugin-proposal-decorators": "^7.28.0",
38
+ "@tanstack/react-query": "^5.90.21",
39
+ "@tanstack/react-query-devtools": "^5.91.3",
40
+ "mobx": "^6.13.7",
41
+ "mobx-react-lite": "^4.1.0",
42
+ "mobx-react-observer": "^1.1.0",
43
+ "react": "^19.1.1",
44
+ "react-dom": "^19.1.1"
45
+ },
46
+ "devDependencies": {
47
+ "@eslint/js": "^9.33.0",
48
+ "@types/node": "^25.3.0",
49
+ "@types/react": "^19.1.10",
50
+ "@types/react-dom": "^19.1.7",
51
+ "@vitejs/plugin-react": "^5.0.0",
52
+ "eslint": "^9.33.0",
53
+ "eslint-plugin-react-hooks": "^5.2.0",
54
+ "eslint-plugin-react-refresh": "^0.4.20",
55
+ "globals": "^16.3.0",
56
+ "typescript": "~5.8.3",
57
+ "typescript-eslint": "^8.39.1",
58
+ "vite": "^7.1.2"
59
+ }
60
+ }
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
package/src/App.css ADDED
File without changes
package/src/App.tsx ADDED
@@ -0,0 +1,5 @@
1
+ const App = () => {
2
+ return <div />;
3
+ };
4
+
5
+ export default App;
@@ -0,0 +1 @@
1
+ export const API_URL = "https://jsonplaceholder.typicode.com";
@@ -0,0 +1,29 @@
1
+ import { API_URL } from "./constants";
2
+
3
+ export interface ApiFetchOptions {
4
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
5
+ params?: Map<string, string>;
6
+ }
7
+
8
+ export async function apiFetch<R = unknown>(
9
+ path: string,
10
+ options?: ApiFetchOptions
11
+ ) {
12
+ const url = new URL(API_URL);
13
+
14
+ url.pathname = path;
15
+
16
+ if (options?.params && options.params.size > 0) {
17
+ for (const [key, value] of options.params.entries()) {
18
+ url.searchParams.append(key, value);
19
+ }
20
+ }
21
+
22
+ const res = await fetch(url.toString(), {
23
+ method: options?.method || "GET",
24
+ });
25
+
26
+ const json = await res.json();
27
+
28
+ return json as R;
29
+ }
@@ -0,0 +1,14 @@
1
+ import { apiFetch } from "./fetch";
2
+ import type { TodoDTO } from "./types";
3
+
4
+ export function getTodosByUserId(userId: number) {
5
+ return apiFetch<TodoDTO[]>("/todos", {
6
+ params: new Map([["userId", userId.toString()]]),
7
+ });
8
+ }
9
+
10
+ export async function deleteTodo(todoId: number) {
11
+ return apiFetch<void>(`/todos/${todoId}`, {
12
+ method: "DELETE",
13
+ });
14
+ }
@@ -0,0 +1,30 @@
1
+ export interface UserDTO {
2
+ id: number;
3
+ name: string;
4
+ username: string;
5
+ email: string;
6
+ address: {
7
+ street: string;
8
+ suite: string;
9
+ city: string;
10
+ zipcode: string;
11
+ geo: {
12
+ lat: string;
13
+ lng: string;
14
+ };
15
+ };
16
+ phone: string;
17
+ website: string;
18
+ company: {
19
+ name: string;
20
+ catchPhrase: string;
21
+ bs: string;
22
+ };
23
+ }
24
+
25
+ export interface TodoDTO {
26
+ id: number;
27
+ title: string;
28
+ completed: boolean;
29
+ userId: number;
30
+ }
@@ -0,0 +1,19 @@
1
+ import { wait } from "../utils";
2
+ import { apiFetch } from "./fetch";
3
+ import type { UserDTO } from "./types";
4
+
5
+ export function getAllUsers() {
6
+ return apiFetch<UserDTO[]>("/users");
7
+ }
8
+
9
+ export function getUserById(userId: number) {
10
+ return apiFetch<UserDTO>(`/users/${userId}`);
11
+ }
12
+
13
+ export async function deleteUser(userId: number) {
14
+ await wait(1500);
15
+
16
+ return apiFetch<void>(`/users/${userId}`, {
17
+ method: "DELETE",
18
+ });
19
+ }
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
package/src/index.css ADDED
@@ -0,0 +1,60 @@
1
+ :root {
2
+ font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
3
+ line-height: 1.5;
4
+ font-weight: 400;
5
+
6
+ color-scheme: light dark;
7
+ color: rgba(255, 255, 255, 0.87);
8
+ background-color: #242424;
9
+
10
+ font-synthesis: none;
11
+ text-rendering: optimizeLegibility;
12
+ -webkit-font-smoothing: antialiased;
13
+ -moz-osx-font-smoothing: grayscale;
14
+ }
15
+
16
+ a {
17
+ font-weight: 500;
18
+ color: #646cff;
19
+ text-decoration: inherit;
20
+ }
21
+ a:hover {
22
+ color: #535bf2;
23
+ }
24
+
25
+ h1 {
26
+ font-size: 3.2em;
27
+ line-height: 1.1;
28
+ }
29
+
30
+ button {
31
+ border-radius: 8px;
32
+ border: 1px solid transparent;
33
+ padding: 0.6em 1.2em;
34
+ font-size: 1em;
35
+ font-weight: 500;
36
+ font-family: inherit;
37
+ background-color: #1a1a1a;
38
+ cursor: pointer;
39
+ transition: border-color 0.25s;
40
+ }
41
+ button:hover {
42
+ border-color: #646cff;
43
+ }
44
+ button:focus,
45
+ button:focus-visible {
46
+ outline: 4px auto -webkit-focus-ring-color;
47
+ }
48
+
49
+ @media (prefers-color-scheme: light) {
50
+ :root {
51
+ color: #213547;
52
+ background-color: #ffffff;
53
+ }
54
+ a:hover {
55
+ color: #747bff;
56
+ }
57
+ button {
58
+ background-color: #f9f9f9;
59
+ }
60
+ }
@@ -0,0 +1,75 @@
1
+ import { type EntityConstructorAny, EntityCollection } from "../entity";
2
+ import type { MQClientContextRegistered } from "./types";
3
+ import {
4
+ OptimisticMutationErrorStrategy,
5
+ OptimisticMutationInvalidationStrategy,
6
+ } from "../mutations";
7
+
8
+ export interface MQClientOptions {
9
+ invalidationStrategy?: OptimisticMutationInvalidationStrategy;
10
+ errorStrategy?: OptimisticMutationErrorStrategy;
11
+ invalidateOnError?: boolean;
12
+ }
13
+
14
+ export interface MQClientProps<T> extends MQClientOptions {
15
+ context: MQClientContextRegistered;
16
+ entities: EntityConstructorAny[];
17
+ rootStore: () => T;
18
+ }
19
+
20
+ export const __MOBX_QUERY__: {
21
+ state: Map<string, EntityCollection>;
22
+ context: MQClientContextRegistered | null;
23
+ options: Required<MQClientOptions>;
24
+ } = {
25
+ state: new Map(),
26
+ context: null,
27
+ options: {
28
+ invalidationStrategy:
29
+ OptimisticMutationInvalidationStrategy.REFERENCED_QUERIES,
30
+ errorStrategy: OptimisticMutationErrorStrategy.ROLLBACK,
31
+ invalidateOnError: true,
32
+ },
33
+ };
34
+
35
+ export class MQClient<T> {
36
+ readonly rootStore: T;
37
+
38
+ constructor(props: MQClientProps<T>) {
39
+ __MOBX_QUERY__.context = props.context;
40
+
41
+ for (const entity of props.entities) {
42
+ __MOBX_QUERY__.state.set(
43
+ entity.name,
44
+ new EntityCollection(entity, props.context.queryClient),
45
+ );
46
+ }
47
+
48
+ // if (process.env.NODE_ENV === 'development') {
49
+ // setupMobxDevtoolsV2()
50
+ // }
51
+
52
+ __MOBX_QUERY__.options.invalidationStrategy =
53
+ props.invalidationStrategy ??
54
+ OptimisticMutationInvalidationStrategy.REFERENCED_QUERIES;
55
+ __MOBX_QUERY__.options.errorStrategy =
56
+ props.errorStrategy ?? OptimisticMutationErrorStrategy.ROLLBACK;
57
+ __MOBX_QUERY__.options.invalidateOnError = props.invalidateOnError ?? true;
58
+
59
+ this.rootStore = props.rootStore();
60
+ }
61
+
62
+ getEntityCollection<TEntityConstructor extends EntityConstructorAny>(
63
+ entity: TEntityConstructor,
64
+ ) {
65
+ const collection = __MOBX_QUERY__.state.get(
66
+ entity.name,
67
+ ) as EntityCollection<TEntityConstructor>;
68
+
69
+ if (!collection) {
70
+ throw new Error(`Entity collection not found for entity ${entity.name}`);
71
+ }
72
+
73
+ return collection;
74
+ }
75
+ }
@@ -0,0 +1,74 @@
1
+ import { __MOBX_QUERY__ } from "./MQClient";
2
+ import type {
3
+ DefaultError,
4
+ MutationOptions,
5
+ QueryClient,
6
+ } from "@tanstack/react-query";
7
+ import type { MQClientContextRegistered } from "./types";
8
+ import type { EntityCollection, EntityConstructorAny } from "../entity";
9
+ import type { MutationFn } from "../mutations";
10
+
11
+ export abstract class MQClientAccessor {
12
+ protected readonly queryClient: QueryClient;
13
+ protected readonly context: MQClientContextRegistered;
14
+ private readonly globalState: Map<string, EntityCollection>;
15
+
16
+ constructor() {
17
+ if (!__MOBX_QUERY__) {
18
+ throw new Error("Client not found");
19
+ }
20
+
21
+ if (!__MOBX_QUERY__.context) {
22
+ throw new Error("MQClientContext is required");
23
+ }
24
+
25
+ this.queryClient = __MOBX_QUERY__.context.queryClient;
26
+ this.globalState = __MOBX_QUERY__.state;
27
+ this.context = __MOBX_QUERY__.context;
28
+ }
29
+
30
+ protected getEntityCollection<
31
+ TEntityConstructor extends EntityConstructorAny = EntityConstructorAny,
32
+ >(
33
+ entityConstructor: TEntityConstructor,
34
+ ): EntityCollection<TEntityConstructor> {
35
+ const collection = this.globalState.get(entityConstructor.name);
36
+
37
+ if (!collection) {
38
+ throw new Error(
39
+ `Entity collection not found for entity ${entityConstructor.name}`,
40
+ );
41
+ }
42
+
43
+ return collection as unknown as EntityCollection<TEntityConstructor>;
44
+ }
45
+
46
+ protected runSyncMutation<
47
+ TInput,
48
+ TError = DefaultError,
49
+ TMutateResult = unknown,
50
+ >(
51
+ input: TInput,
52
+ mutationFn: MutationFn<TInput>,
53
+ options?: MutationOptions<void, TError, TInput, TMutateResult>,
54
+ ) {
55
+ this.queryClient
56
+ .getMutationCache()
57
+ .build<void, TError, TInput, TMutateResult>(this.queryClient, {
58
+ mutationFn: (input) => mutationFn(input, this.context),
59
+ onError: options?.onError,
60
+ onMutate: options?.onMutate,
61
+ onSuccess: options?.onSuccess,
62
+ onSettled: options?.onSettled,
63
+ gcTime: options?.gcTime,
64
+ meta: options?.meta,
65
+ networkMode: options?.networkMode,
66
+ retry: options?.retry,
67
+ retryDelay: options?.retryDelay,
68
+ scope: options?.scope,
69
+ mutationKey: options?.mutationKey,
70
+ })
71
+ .execute(input)
72
+ .catch((error) => console.log("runSyncMutation error", error));
73
+ }
74
+ }
@@ -0,0 +1,8 @@
1
+ import { MQClient } from "./MQClient";
2
+ import { MQClientAccessor } from "./MQClientAccessor";
3
+
4
+ import type { MQClientContext, MQClientContextRegistered } from "./types";
5
+
6
+ export { MQClient, MQClientAccessor };
7
+
8
+ export type { MQClientContext, MQClientContextRegistered };
@@ -0,0 +1,37 @@
1
+ import { QueryClient } from '@tanstack/react-query'
2
+
3
+ export interface MQClientContext {
4
+ queryClient: QueryClient
5
+ }
6
+
7
+ /**
8
+ * Global namespace that users can augment to register their custom context type.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * declare global {
13
+ * namespace MobXQuery {
14
+ * interface RegisteredContext {
15
+ * context: MyCustomContext
16
+ * }
17
+ * }
18
+ * }
19
+ * ```
20
+ */
21
+ declare global {
22
+ // eslint-disable-next-line @typescript-eslint/no-namespace
23
+ namespace MobXQuery {
24
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
25
+ interface RegisteredContext {}
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Extracts the user's registered context type or falls back to base MQClientContext.
31
+ * This allows users to define their context type once via global namespace augmentation.
32
+ */
33
+ export type MQClientContextRegistered = MobXQuery.RegisteredContext extends {
34
+ context: infer TContext extends MQClientContext
35
+ }
36
+ ? TContext
37
+ : MQClientContext