@hypequery/react 0.0.0-canary-20260611154523
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/LICENSE +201 -0
- package/README.md +259 -0
- package/dist/analyticsHooks.d.ts +31 -0
- package/dist/analyticsHooks.d.ts.map +1 -0
- package/dist/analyticsHooks.js +18 -0
- package/dist/analyticsHooks.test.d.ts +2 -0
- package/dist/analyticsHooks.test.d.ts.map +1 -0
- package/dist/analyticsHooks.test.js +98 -0
- package/dist/createHooks.d.ts +49 -0
- package/dist/createHooks.d.ts.map +1 -0
- package/dist/createHooks.js +177 -0
- package/dist/createHooks.test.d.ts +2 -0
- package/dist/createHooks.test.d.ts.map +1 -0
- package/dist/createHooks.test.js +686 -0
- package/dist/errors.d.ts +9 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +13 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/types.d.ts +9 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/package.json +43 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are advised to review the applicable
|
|
150
|
+
documentation for the specific language governing permissions and
|
|
151
|
+
limitations under each license.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2024 hypequery
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
# @hypequery/react
|
|
2
|
+
|
|
3
|
+
React hooks for typed Hypequery HTTP endpoints, built on TanStack Query.
|
|
4
|
+
|
|
5
|
+
Use `@hypequery/react` with APIs created by `@hypequery/serve`. The hooks call generated routes and infer input/output types from the API type you pass in.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @hypequery/react @tanstack/react-query
|
|
11
|
+
# or
|
|
12
|
+
pnpm add @hypequery/react @tanstack/react-query
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quick Start
|
|
16
|
+
|
|
17
|
+
Given a serve API:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
// server/api.ts
|
|
21
|
+
import { initServe } from '@hypequery/serve';
|
|
22
|
+
import { z } from 'zod';
|
|
23
|
+
import { db } from './db.js';
|
|
24
|
+
|
|
25
|
+
const { query, serve } = initServe({
|
|
26
|
+
context: () => ({ db }),
|
|
27
|
+
basePath: '/api/analytics',
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const weeklyRevenue = query({
|
|
31
|
+
description: 'Weekly revenue',
|
|
32
|
+
input: z.object({ startDate: z.string() }),
|
|
33
|
+
query: ({ ctx, input }) =>
|
|
34
|
+
ctx.db
|
|
35
|
+
.table('orders')
|
|
36
|
+
.where('created_at', 'gte', input.startDate)
|
|
37
|
+
.sum('total', 'revenue')
|
|
38
|
+
.execute(),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
export const api = serve({
|
|
42
|
+
queries: { weeklyRevenue },
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
api.route('/weeklyRevenue', api.queries.weeklyRevenue);
|
|
46
|
+
|
|
47
|
+
export type AnalyticsApi = typeof api;
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Create hooks on the client:
|
|
51
|
+
|
|
52
|
+
```tsx
|
|
53
|
+
// client/analytics-hooks.ts
|
|
54
|
+
import { createHooks } from '@hypequery/react';
|
|
55
|
+
import type { AnalyticsApi } from '../server/api.js';
|
|
56
|
+
|
|
57
|
+
export const { useQuery, useMutation } = createHooks<AnalyticsApi>({
|
|
58
|
+
baseUrl: '/api/analytics',
|
|
59
|
+
api: {} as AnalyticsApi,
|
|
60
|
+
});
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Use them inside a component:
|
|
64
|
+
|
|
65
|
+
```tsx
|
|
66
|
+
function RevenuePanel() {
|
|
67
|
+
const revenue = useQuery('weeklyRevenue', {
|
|
68
|
+
startDate: '2026-01-01',
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
if (revenue.isLoading) return <p>Loading...</p>;
|
|
72
|
+
if (revenue.error) return <p>{revenue.error.message}</p>;
|
|
73
|
+
|
|
74
|
+
return <pre>{JSON.stringify(revenue.data, null, 2)}</pre>;
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Dataset And Metric Hooks
|
|
79
|
+
|
|
80
|
+
`createAnalyticsHooks` adds convenience wrappers for semantic endpoint names. Metrics use their endpoint name directly. Dataset endpoints are addressed as `dataset:<name>` in the API type and exposed through `useDataset(name, ...)`.
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
import { createAnalyticsHooks } from '@hypequery/react';
|
|
84
|
+
import type { AnalyticsApi } from '../server/api.js';
|
|
85
|
+
|
|
86
|
+
import { manifest } from '../server/api.js'; // serve api.manifest(), serialized
|
|
87
|
+
|
|
88
|
+
export const { useMetric, useDataset } = createAnalyticsHooks<AnalyticsApi>({
|
|
89
|
+
baseUrl: '/api/analytics',
|
|
90
|
+
manifest,
|
|
91
|
+
metrics: ['revenue', 'averageOrderValue'] as const,
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
function Dashboard() {
|
|
95
|
+
const revenue = useMetric('revenue', {
|
|
96
|
+
dimensions: ['country'],
|
|
97
|
+
filters: [{ field: 'status', operator: 'eq', value: 'completed' }],
|
|
98
|
+
orderBy: [{ field: 'revenue', direction: 'desc' }],
|
|
99
|
+
limit: 10,
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const orders = useDataset('orders', {
|
|
103
|
+
dimensions: ['status'],
|
|
104
|
+
measures: ['revenue', 'orderCount'],
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
return (
|
|
108
|
+
<pre>
|
|
109
|
+
{JSON.stringify({ revenue: revenue.data, orders: orders.data }, null, 2)}
|
|
110
|
+
</pre>
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Route Configuration
|
|
116
|
+
|
|
117
|
+
Hooks need to know each endpoint's HTTP method and path. There are three ways to
|
|
118
|
+
supply that, in increasing precedence: a route manifest, a runtime `api` object,
|
|
119
|
+
or explicit `config`.
|
|
120
|
+
|
|
121
|
+
### Route manifest (recommended)
|
|
122
|
+
|
|
123
|
+
`@hypequery/serve`'s `api.manifest()` returns a serializable map of every
|
|
124
|
+
query/metric/dataset key to its `{ method, path }`. Export it from a server-only
|
|
125
|
+
module and pass it to the hooks — this avoids importing server code into the
|
|
126
|
+
browser bundle while keeping client routes in sync with the server.
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
// server side (server-only module)
|
|
130
|
+
export const manifest = api.manifest();
|
|
131
|
+
|
|
132
|
+
// client side
|
|
133
|
+
const { useQuery } = createHooks<AnalyticsApi>({
|
|
134
|
+
baseUrl: '/api/analytics',
|
|
135
|
+
manifest,
|
|
136
|
+
});
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
> Metric and dataset endpoints are POST routes whose paths differ from their map
|
|
140
|
+
> keys (e.g. `dataset:orders` → `POST /api/analytics/datasets/orders/query`). They
|
|
141
|
+
> require a `manifest` (or explicit `config`); calling them without one throws a
|
|
142
|
+
> clear error rather than hitting the wrong URL.
|
|
143
|
+
|
|
144
|
+
#### Generating the manifest at build time
|
|
145
|
+
|
|
146
|
+
The cleanest way to keep server code out of the browser bundle is to generate a
|
|
147
|
+
JSON file at build time and import that on the client. `api.manifest()` is pure —
|
|
148
|
+
it reads the configured routes and never touches your database — so this step is
|
|
149
|
+
cheap and safe to run in CI.
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
// scripts/gen-manifest.ts — run before your client build
|
|
153
|
+
import { writeFileSync } from 'node:fs';
|
|
154
|
+
import { api } from '../server/api.js';
|
|
155
|
+
|
|
156
|
+
writeFileSync('src/generated/manifest.json', JSON.stringify(api.manifest(), null, 2));
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
```jsonc
|
|
160
|
+
// package.json
|
|
161
|
+
{
|
|
162
|
+
"scripts": {
|
|
163
|
+
"gen:manifest": "tsx scripts/gen-manifest.ts",
|
|
164
|
+
"build": "npm run gen:manifest && <your client build>"
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
// client side — imports plain JSON, no server code in the bundle
|
|
171
|
+
import manifest from './generated/manifest.json';
|
|
172
|
+
|
|
173
|
+
const { useQuery } = createHooks<AnalyticsApi>({
|
|
174
|
+
baseUrl: '/api/analytics',
|
|
175
|
+
manifest,
|
|
176
|
+
});
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
The manifest is derived entirely from your serve config (`basePath`, route keys,
|
|
180
|
+
and `semanticPaths`), so the generated file is deterministic and only changes when
|
|
181
|
+
your API shape does — commit it or regenerate it on every build.
|
|
182
|
+
|
|
183
|
+
> `baseUrl` supplies the origin/host; the per-endpoint path comes from the
|
|
184
|
+
> manifest (it already includes the server's `basePath`), so there's no
|
|
185
|
+
> double-prefixing. Keep `baseUrl` aligned with where the API is mounted.
|
|
186
|
+
|
|
187
|
+
### Explicit config
|
|
188
|
+
|
|
189
|
+
If a manifest is not available at runtime, pass route config explicitly. This
|
|
190
|
+
overrides any manifest entry.
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
const { useQuery } = createHooks<AnalyticsApi>({
|
|
194
|
+
baseUrl: '/api/analytics',
|
|
195
|
+
config: {
|
|
196
|
+
weeklyRevenue: { method: 'POST', path: '/weeklyRevenue' },
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`path` may be relative to `baseUrl`, absolute within the same origin, or an absolute HTTP URL.
|
|
202
|
+
|
|
203
|
+
## Headers
|
|
204
|
+
|
|
205
|
+
Pass static headers or a function that returns headers.
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
const hooks = createHooks<AnalyticsApi>({
|
|
209
|
+
baseUrl: '/api/analytics',
|
|
210
|
+
headers: () => ({
|
|
211
|
+
authorization: `Bearer ${localStorage.getItem('token')}`,
|
|
212
|
+
}),
|
|
213
|
+
});
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
## Query Options
|
|
217
|
+
|
|
218
|
+
TanStack Query options can be passed as the final argument.
|
|
219
|
+
|
|
220
|
+
```tsx
|
|
221
|
+
const result = useQuery(
|
|
222
|
+
'weeklyRevenue',
|
|
223
|
+
{ startDate: '2026-01-01' },
|
|
224
|
+
{
|
|
225
|
+
staleTime: 60_000,
|
|
226
|
+
refetchOnWindowFocus: false,
|
|
227
|
+
},
|
|
228
|
+
);
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
For no-input queries, use `queryOptions()` when an options object might look like input.
|
|
232
|
+
|
|
233
|
+
```tsx
|
|
234
|
+
import { queryOptions } from '@hypequery/react';
|
|
235
|
+
|
|
236
|
+
const result = useQuery('health', queryOptions({
|
|
237
|
+
staleTime: 30_000,
|
|
238
|
+
}));
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
## Mutations
|
|
242
|
+
|
|
243
|
+
`useMutation(name)` uses the same endpoint typing and sends requests as `POST` by default unless route config overrides it.
|
|
244
|
+
|
|
245
|
+
```tsx
|
|
246
|
+
const refresh = useMutation('refreshReport');
|
|
247
|
+
|
|
248
|
+
refresh.mutate({ reportId: 'revenue' });
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Notes
|
|
252
|
+
|
|
253
|
+
- This package does not define datasets. Use `@hypequery/datasets` for semantic definitions.
|
|
254
|
+
- This package does not generate SQL. It calls HTTP routes exposed by `@hypequery/serve`.
|
|
255
|
+
- Dataset relationship JOIN execution is not implied by the React hooks; hooks consume whatever endpoint behavior the server exposes.
|
|
256
|
+
|
|
257
|
+
## License
|
|
258
|
+
|
|
259
|
+
Apache-2.0.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { UseQueryOptions as TanstackUseQueryOptions, UseQueryResult } from '@tanstack/react-query';
|
|
2
|
+
import { type CreateHooksConfig } from './createHooks.js';
|
|
3
|
+
import { HttpError } from './errors.js';
|
|
4
|
+
import type { ExtractNames, QueryInput, QueryOutput } from './types.js';
|
|
5
|
+
type DatasetKey<Name extends string> = `dataset:${Name}`;
|
|
6
|
+
type DatasetNamesFromApi<Api> = ExtractNames<Api> extends infer Key ? Key extends `dataset:${infer Name}` ? Name : never : never;
|
|
7
|
+
type QueryKey<Name extends string, Input> = Input extends never ? ['hypequery', Name] : ['hypequery', Name, Input];
|
|
8
|
+
type QueryOptions<Api, Key extends ExtractNames<Api>> = Omit<TanstackUseQueryOptions<QueryOutput<Api, Key>, HttpError, QueryOutput<Api, Key>, QueryKey<Key, QueryInput<Api, Key>>>, 'queryKey' | 'queryFn'>;
|
|
9
|
+
type MetricQueryParams<Api, Key extends ExtractNames<Api>> = QueryInput<Api, Key> extends never ? [name: Key, options?: QueryOptions<Api, Key>] : [name: Key, input: QueryInput<Api, Key>, options?: QueryOptions<Api, Key>];
|
|
10
|
+
type DatasetQueryParams<Api, Name extends DatasetNamesFromApi<Api>> = QueryInput<Api, Extract<ExtractNames<Api>, DatasetKey<Name>>> extends never ? [name: Name, options?: QueryOptions<Api, Extract<ExtractNames<Api>, DatasetKey<Name>>>] : [
|
|
11
|
+
name: Name,
|
|
12
|
+
input: QueryInput<Api, Extract<ExtractNames<Api>, DatasetKey<Name>>>,
|
|
13
|
+
options?: QueryOptions<Api, Extract<ExtractNames<Api>, DatasetKey<Name>>>
|
|
14
|
+
];
|
|
15
|
+
export interface CreateAnalyticsHooksConfig<Api extends Record<string, {
|
|
16
|
+
input: any;
|
|
17
|
+
output: any;
|
|
18
|
+
}>, TMetrics extends readonly Exclude<ExtractNames<Api>, `dataset:${string}`>[] = readonly Exclude<ExtractNames<Api>, `dataset:${string}`>[]> extends CreateHooksConfig<Api> {
|
|
19
|
+
metrics?: TMetrics;
|
|
20
|
+
}
|
|
21
|
+
export declare function createAnalyticsHooks<Api extends Record<string, {
|
|
22
|
+
input: any;
|
|
23
|
+
output: any;
|
|
24
|
+
}>, const TMetrics extends readonly Exclude<ExtractNames<Api>, `dataset:${string}`>[] = readonly Exclude<ExtractNames<Api>, `dataset:${string}`>[]>(config: CreateAnalyticsHooksConfig<Api, TMetrics>): {
|
|
25
|
+
readonly useMetric: <Name extends TMetrics extends readonly (infer U)[] ? U extends string ? U : never : Exclude<ExtractNames<Api>, `dataset:${string}`>>(...args: MetricQueryParams<Api, Name>) => UseQueryResult<QueryOutput<Api, Name>, HttpError>;
|
|
26
|
+
readonly useDataset: <Name extends DatasetNamesFromApi<Api>>(...args: DatasetQueryParams<Api, Name>) => UseQueryResult<QueryOutput<Api, Extract<ExtractNames<Api>, DatasetKey<Name>>>, HttpError>;
|
|
27
|
+
readonly useQuery: <Name extends Extract<keyof Api, string>>(...args: QueryInput<Api, Name> extends never ? [name: Name, options?: Omit<TanstackUseQueryOptions<QueryOutput<Api, Name>, HttpError, QueryOutput<Api, Name>, QueryInput<Api, Name> extends never ? ["hypequery", Name] : ["hypequery", Name, QueryInput<Api, Name>]>, "queryKey" | "queryFn"> | undefined] : [name: Name, input: QueryInput<Api, Name>, options?: Omit<TanstackUseQueryOptions<QueryOutput<Api, Name>, HttpError, QueryOutput<Api, Name>, QueryInput<Api, Name> extends never ? ["hypequery", Name] : ["hypequery", Name, QueryInput<Api, Name>]>, "queryKey" | "queryFn"> | undefined]) => UseQueryResult<QueryOutput<Api, Name>, HttpError>;
|
|
28
|
+
readonly useMutation: <Name extends Extract<keyof Api, string>>(name: Name, options?: Omit<import("@tanstack/react-query").UseMutationOptions<QueryOutput<Api, Name>, HttpError, QueryInput<Api, Name>, unknown>, "mutationFn"> | undefined) => import("@tanstack/react-query").UseMutationResult<QueryOutput<Api, Name>, HttpError, QueryInput<Api, Name>>;
|
|
29
|
+
};
|
|
30
|
+
export {};
|
|
31
|
+
//# sourceMappingURL=analyticsHooks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"analyticsHooks.d.ts","sourceRoot":"","sources":["../src/analyticsHooks.tsx"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { createHooks } from './createHooks.js';
|
|
2
|
+
export function createAnalyticsHooks(config) {
|
|
3
|
+
const hooks = createHooks(config);
|
|
4
|
+
function useMetric(...args) {
|
|
5
|
+
const [name, ...rest] = args;
|
|
6
|
+
return hooks.useQuery(name, ...rest);
|
|
7
|
+
}
|
|
8
|
+
function useDataset(...args) {
|
|
9
|
+
const [name, ...rest] = args;
|
|
10
|
+
const key = `dataset:${String(name)}`;
|
|
11
|
+
return hooks.useQuery(key, ...rest);
|
|
12
|
+
}
|
|
13
|
+
return {
|
|
14
|
+
...hooks,
|
|
15
|
+
useMetric,
|
|
16
|
+
useDataset,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"analyticsHooks.test.d.ts","sourceRoot":"","sources":["../src/analyticsHooks.test.tsx"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
3
|
+
import { renderHook, waitFor } from '@testing-library/react';
|
|
4
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
5
|
+
import { createAnalyticsHooks } from './analyticsHooks.js';
|
|
6
|
+
function createWrapper() {
|
|
7
|
+
const queryClient = new QueryClient({
|
|
8
|
+
defaultOptions: {
|
|
9
|
+
queries: { retry: false },
|
|
10
|
+
},
|
|
11
|
+
});
|
|
12
|
+
return ({ children }) => (_jsx(QueryClientProvider, { client: queryClient, children: children }));
|
|
13
|
+
}
|
|
14
|
+
function mockSuccessResponse(data) {
|
|
15
|
+
return {
|
|
16
|
+
ok: true,
|
|
17
|
+
status: 200,
|
|
18
|
+
json: () => Promise.resolve(data),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
describe('createAnalyticsHooks', () => {
|
|
22
|
+
const fetchMock = vi.fn();
|
|
23
|
+
beforeEach(() => {
|
|
24
|
+
fetchMock.mockReset();
|
|
25
|
+
});
|
|
26
|
+
it('queries metrics through useMetric with metric names only', async () => {
|
|
27
|
+
fetchMock.mockResolvedValue(mockSuccessResponse({ data: [{ totalRevenue: 42 }] }));
|
|
28
|
+
const { useMetric } = createAnalyticsHooks({
|
|
29
|
+
baseUrl: '/api/analytics',
|
|
30
|
+
fetchFn: fetchMock,
|
|
31
|
+
metrics: ['totalRevenue', 'monthlyRevenue'],
|
|
32
|
+
config: {
|
|
33
|
+
totalRevenue: { method: 'POST', path: '/api/analytics/metrics/totalRevenue' },
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
const { result } = renderHook(() => useMetric('totalRevenue', { dimensions: ['country'] }), { wrapper: createWrapper() });
|
|
37
|
+
await waitFor(() => {
|
|
38
|
+
expect(result.current.data).toEqual({ data: [{ totalRevenue: 42 }] });
|
|
39
|
+
});
|
|
40
|
+
expect(fetchMock).toHaveBeenCalledWith('/api/analytics/metrics/totalRevenue', expect.objectContaining({
|
|
41
|
+
method: 'POST',
|
|
42
|
+
body: JSON.stringify({ dimensions: ['country'] }),
|
|
43
|
+
}));
|
|
44
|
+
});
|
|
45
|
+
it('queries datasets through useDataset without exposing dataset: keys', async () => {
|
|
46
|
+
fetchMock.mockResolvedValue(mockSuccessResponse({ data: [{ country: 'US', revenue: 120 }] }));
|
|
47
|
+
const { useDataset } = createAnalyticsHooks({
|
|
48
|
+
baseUrl: '/api/analytics',
|
|
49
|
+
fetchFn: fetchMock,
|
|
50
|
+
metrics: [],
|
|
51
|
+
config: {
|
|
52
|
+
'dataset:orders': { method: 'POST', path: '/api/analytics/datasets/orders/query' },
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
const { result } = renderHook(() => useDataset('orders', { dimensions: ['country'], measures: ['revenue'] }), { wrapper: createWrapper() });
|
|
56
|
+
await waitFor(() => {
|
|
57
|
+
expect(result.current.data).toEqual({ data: [{ country: 'US', revenue: 120 }] });
|
|
58
|
+
});
|
|
59
|
+
expect(fetchMock).toHaveBeenCalledWith('/api/analytics/datasets/orders/query', expect.objectContaining({
|
|
60
|
+
method: 'POST',
|
|
61
|
+
body: JSON.stringify({ dimensions: ['country'], measures: ['revenue'] }),
|
|
62
|
+
}));
|
|
63
|
+
});
|
|
64
|
+
it('supports metric names from the declared semantic metric list', async () => {
|
|
65
|
+
fetchMock.mockResolvedValue(mockSuccessResponse({ data: [{ period: '2025-01-01', monthlyRevenue: 90 }] }));
|
|
66
|
+
const { useMetric } = createAnalyticsHooks({
|
|
67
|
+
baseUrl: '/api/analytics',
|
|
68
|
+
fetchFn: fetchMock,
|
|
69
|
+
metrics: ['totalRevenue', 'monthlyRevenue'],
|
|
70
|
+
config: {
|
|
71
|
+
monthlyRevenue: { method: 'POST', path: '/api/analytics/metrics/monthlyRevenue' },
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
const { result } = renderHook(() => useMetric('monthlyRevenue', { by: 'month' }), { wrapper: createWrapper() });
|
|
75
|
+
await waitFor(() => {
|
|
76
|
+
expect(result.current.data).toEqual({ data: [{ period: '2025-01-01', monthlyRevenue: 90 }] });
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
it('resolves semantic config paths against an absolute baseUrl host', async () => {
|
|
80
|
+
fetchMock.mockResolvedValue(mockSuccessResponse({ data: [{ totalRevenue: 42 }] }));
|
|
81
|
+
const { useMetric } = createAnalyticsHooks({
|
|
82
|
+
baseUrl: 'https://api.example.com/hypequery',
|
|
83
|
+
fetchFn: fetchMock,
|
|
84
|
+
metrics: ['totalRevenue', 'monthlyRevenue'],
|
|
85
|
+
config: {
|
|
86
|
+
totalRevenue: { method: 'POST', path: '/api/analytics/metrics/totalRevenue' },
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
const { result } = renderHook(() => useMetric('totalRevenue', { dimensions: ['country'] }), { wrapper: createWrapper() });
|
|
90
|
+
await waitFor(() => {
|
|
91
|
+
expect(result.current.data).toEqual({ data: [{ totalRevenue: 42 }] });
|
|
92
|
+
});
|
|
93
|
+
expect(fetchMock).toHaveBeenCalledWith('https://api.example.com/api/analytics/metrics/totalRevenue', expect.objectContaining({
|
|
94
|
+
method: 'POST',
|
|
95
|
+
body: JSON.stringify({ dimensions: ['country'] }),
|
|
96
|
+
}));
|
|
97
|
+
});
|
|
98
|
+
});
|