hydrousdb 1.1.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.
- package/LICENSE +21 -0
- package/README.md +686 -0
- package/dist/analytics/index.d.mts +178 -0
- package/dist/analytics/index.d.ts +178 -0
- package/dist/analytics/index.js +221 -0
- package/dist/analytics/index.js.map +1 -0
- package/dist/analytics/index.mjs +219 -0
- package/dist/analytics/index.mjs.map +1 -0
- package/dist/auth/index.d.mts +180 -0
- package/dist/auth/index.d.ts +180 -0
- package/dist/auth/index.js +220 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/auth/index.mjs +218 -0
- package/dist/auth/index.mjs.map +1 -0
- package/dist/http-CIXLF5GV.d.mts +466 -0
- package/dist/http-CIXLF5GV.d.ts +466 -0
- package/dist/index.d.mts +73 -0
- package/dist/index.d.ts +73 -0
- package/dist/index.js +810 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +801 -0
- package/dist/index.mjs.map +1 -0
- package/dist/records/index.d.mts +124 -0
- package/dist/records/index.d.ts +124 -0
- package/dist/records/index.js +226 -0
- package/dist/records/index.js.map +1 -0
- package/dist/records/index.mjs +224 -0
- package/dist/records/index.mjs.map +1 -0
- package/package.json +67 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 HydrousDB
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,686 @@
|
|
|
1
|
+
# hydrousdb
|
|
2
|
+
|
|
3
|
+
> **Official TypeScript SDK for [HydrousDB](https://db-api-82687684612.us-central1.run.app)**
|
|
4
|
+
> — a cloud-native record store with built-in authentication, batch operations, analytics, and cursor-based pagination.
|
|
5
|
+
|
|
6
|
+
[](https://npmjs.com/package/hydrousdb)
|
|
7
|
+
[](https://www.typescriptlang.org/)
|
|
8
|
+
[](./LICENSE)
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Table of Contents
|
|
13
|
+
|
|
14
|
+
- [Features](#features)
|
|
15
|
+
- [Installation](#installation)
|
|
16
|
+
- [Quick Start](#quick-start)
|
|
17
|
+
- [Framework Guides](#framework-guides)
|
|
18
|
+
- [Next.js (App Router)](#nextjs-app-router)
|
|
19
|
+
- [Next.js (Pages Router)](#nextjs-pages-router)
|
|
20
|
+
- [Vue 3 / Nuxt 3](#vue-3--nuxt-3)
|
|
21
|
+
- [React (Vite / CRA)](#react-vite--cra)
|
|
22
|
+
- [Node.js / Express](#nodejs--express)
|
|
23
|
+
- [API Reference](#api-reference)
|
|
24
|
+
- [createClient](#createclient)
|
|
25
|
+
- [Records](#records)
|
|
26
|
+
- [Auth](#auth)
|
|
27
|
+
- [Analytics](#analytics)
|
|
28
|
+
- [Error Handling](#error-handling)
|
|
29
|
+
- [Pagination](#pagination)
|
|
30
|
+
- [TypeScript](#typescript)
|
|
31
|
+
- [Contributing](#contributing)
|
|
32
|
+
- [License](#license)
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## Features
|
|
37
|
+
|
|
38
|
+
- ✅ **Full TypeScript** — every method and response is fully typed
|
|
39
|
+
- ✅ **Modular** — import only what you need (`hydrousdb/records`, `hydrousdb/auth`, `hydrousdb/analytics`)
|
|
40
|
+
- ✅ **Tree-shakeable** — ships ESM + CJS with dual exports
|
|
41
|
+
- ✅ **Auto-retry** — retries on transient 5xx / network errors with linear back-off
|
|
42
|
+
- ✅ **Timeout control** — configurable per-client request timeout
|
|
43
|
+
- ✅ **Cursor pagination helpers** — `queryAll()` / `listAllUsers()` handle cursor following for you
|
|
44
|
+
- ✅ **Zero dependencies** — uses the native `fetch` API (Node 18+, all modern browsers)
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Installation
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
npm install hydrousdb
|
|
52
|
+
# or
|
|
53
|
+
pnpm add hydrousdb
|
|
54
|
+
# or
|
|
55
|
+
yarn add hydrousdb
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
> **Node.js ≥ 18** is required (uses native `fetch`). For Node 16/17, polyfill `fetch` with `node-fetch` or `undici`.
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Quick Start
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { createClient } from 'hydrousdb';
|
|
66
|
+
|
|
67
|
+
const db = createClient({
|
|
68
|
+
apiKey: 'your-api-key',
|
|
69
|
+
bucketKey: 'your-bucket-key',
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// Insert a record
|
|
73
|
+
const { data, meta } = await db.records.insert({
|
|
74
|
+
values: { name: 'Alice', score: 99 },
|
|
75
|
+
queryableFields: ['name'],
|
|
76
|
+
});
|
|
77
|
+
console.log('Created record:', meta.id);
|
|
78
|
+
|
|
79
|
+
// Query records
|
|
80
|
+
const { data: records } = await db.records.query({
|
|
81
|
+
filters: [{ field: 'score', op: '>=', value: 90 }],
|
|
82
|
+
limit: 20,
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// Auth — sign a user in
|
|
86
|
+
const { data: user, session } = await db.auth.signIn({
|
|
87
|
+
email: 'alice@example.com',
|
|
88
|
+
password: 'Str0ng@Pass!',
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Framework Guides
|
|
95
|
+
|
|
96
|
+
### Next.js (App Router)
|
|
97
|
+
|
|
98
|
+
**1. Create a shared client singleton**
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
// lib/db.ts
|
|
102
|
+
import { createClient } from 'hydrousdb';
|
|
103
|
+
|
|
104
|
+
// The client is re-used across all server components in the same process
|
|
105
|
+
export const db = createClient({
|
|
106
|
+
apiKey: process.env.HYDROUS_API_KEY!,
|
|
107
|
+
bucketKey: process.env.HYDROUS_BUCKET_KEY!,
|
|
108
|
+
});
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
**2. Use in a Server Component**
|
|
112
|
+
|
|
113
|
+
```tsx
|
|
114
|
+
// app/products/page.tsx
|
|
115
|
+
import { db } from '@/lib/db';
|
|
116
|
+
|
|
117
|
+
export default async function ProductsPage() {
|
|
118
|
+
const { data: products } = await db.records.query({
|
|
119
|
+
filters: [{ field: 'category', op: '==', value: 'shoes' }],
|
|
120
|
+
limit: 24,
|
|
121
|
+
sortOrder: 'desc',
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
return (
|
|
125
|
+
<ul>
|
|
126
|
+
{products.map(p => (
|
|
127
|
+
<li key={p.id}>{String(p.name)}</li>
|
|
128
|
+
))}
|
|
129
|
+
</ul>
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
**3. Use in a Route Handler**
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
// app/api/records/route.ts
|
|
138
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
139
|
+
import { db } from '@/lib/db';
|
|
140
|
+
import { HydrousError } from 'hydrousdb';
|
|
141
|
+
|
|
142
|
+
export async function POST(req: NextRequest) {
|
|
143
|
+
try {
|
|
144
|
+
const body = await req.json();
|
|
145
|
+
const result = await db.records.insert({
|
|
146
|
+
values: body,
|
|
147
|
+
queryableFields: ['email', 'name'],
|
|
148
|
+
});
|
|
149
|
+
return NextResponse.json(result, { status: 201 });
|
|
150
|
+
} catch (err) {
|
|
151
|
+
if (err instanceof HydrousError) {
|
|
152
|
+
return NextResponse.json({ error: err.message }, { status: err.status });
|
|
153
|
+
}
|
|
154
|
+
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
**4. Auth middleware example**
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
// middleware.ts
|
|
163
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
164
|
+
import { db } from '@/lib/db';
|
|
165
|
+
|
|
166
|
+
export async function middleware(req: NextRequest) {
|
|
167
|
+
const sessionId = req.cookies.get('sessionId')?.value;
|
|
168
|
+
if (!sessionId) return NextResponse.redirect(new URL('/login', req.url));
|
|
169
|
+
|
|
170
|
+
try {
|
|
171
|
+
await db.auth.validateSession(sessionId);
|
|
172
|
+
return NextResponse.next();
|
|
173
|
+
} catch {
|
|
174
|
+
return NextResponse.redirect(new URL('/login', req.url));
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export const config = { matcher: ['/dashboard/:path*'] };
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
**5. Environment variables**
|
|
182
|
+
|
|
183
|
+
```env
|
|
184
|
+
# .env.local
|
|
185
|
+
HYDROUS_API_KEY=your-api-key
|
|
186
|
+
HYDROUS_BUCKET_KEY=your-bucket-key
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
---
|
|
190
|
+
|
|
191
|
+
### Next.js (Pages Router)
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
// pages/api/records.ts
|
|
195
|
+
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
196
|
+
import { createClient, HydrousError } from 'hydrousdb';
|
|
197
|
+
|
|
198
|
+
const db = createClient({
|
|
199
|
+
apiKey: process.env.HYDROUS_API_KEY!,
|
|
200
|
+
bucketKey: process.env.HYDROUS_BUCKET_KEY!,
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
204
|
+
if (req.method === 'GET') {
|
|
205
|
+
try {
|
|
206
|
+
const result = await db.records.query({ limit: 50 });
|
|
207
|
+
return res.status(200).json(result);
|
|
208
|
+
} catch (err) {
|
|
209
|
+
if (err instanceof HydrousError) return res.status(err.status).json({ error: err.message });
|
|
210
|
+
return res.status(500).json({ error: 'Internal Server Error' });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
res.setHeader('Allow', ['GET']);
|
|
214
|
+
res.status(405).end();
|
|
215
|
+
}
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
---
|
|
219
|
+
|
|
220
|
+
### Vue 3 / Nuxt 3
|
|
221
|
+
|
|
222
|
+
**Nuxt 3 — plugin**
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
// plugins/hydrousdb.ts
|
|
226
|
+
import { createClient } from 'hydrousdb';
|
|
227
|
+
|
|
228
|
+
export default defineNuxtPlugin(() => {
|
|
229
|
+
const config = useRuntimeConfig();
|
|
230
|
+
|
|
231
|
+
const db = createClient({
|
|
232
|
+
apiKey: config.hydrousApiKey as string,
|
|
233
|
+
bucketKey: config.hydrousBucketKey as string,
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
return { provide: { db } };
|
|
237
|
+
});
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
// nuxt.config.ts
|
|
242
|
+
export default defineNuxtConfig({
|
|
243
|
+
runtimeConfig: {
|
|
244
|
+
hydrousApiKey: '', // Set via NUXT_HYDROUS_API_KEY env var
|
|
245
|
+
hydrousBucketKey: '', // Set via NUXT_HYDROUS_BUCKET_KEY env var
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
**Usage in a component**
|
|
251
|
+
|
|
252
|
+
```vue
|
|
253
|
+
<script setup lang="ts">
|
|
254
|
+
const { $db } = useNuxtApp();
|
|
255
|
+
|
|
256
|
+
const { data: records, pending } = await useAsyncData('records', () =>
|
|
257
|
+
$db.records.query({ limit: 20 })
|
|
258
|
+
);
|
|
259
|
+
</script>
|
|
260
|
+
|
|
261
|
+
<template>
|
|
262
|
+
<div v-if="pending">Loading…</div>
|
|
263
|
+
<ul v-else>
|
|
264
|
+
<li v-for="r in records?.data" :key="r.id">{{ r.name }}</li>
|
|
265
|
+
</ul>
|
|
266
|
+
</template>
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
**Vue 3 standalone — composable**
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
// composables/useHydrous.ts
|
|
273
|
+
import { createClient } from 'hydrousdb';
|
|
274
|
+
|
|
275
|
+
const db = createClient({
|
|
276
|
+
apiKey: import.meta.env.VITE_HYDROUS_API_KEY,
|
|
277
|
+
bucketKey: import.meta.env.VITE_HYDROUS_BUCKET_KEY,
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
export function useHydrous() {
|
|
281
|
+
return db;
|
|
282
|
+
}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
---
|
|
286
|
+
|
|
287
|
+
### React (Vite / CRA)
|
|
288
|
+
|
|
289
|
+
```tsx
|
|
290
|
+
// src/hooks/useRecords.ts
|
|
291
|
+
import { useEffect, useState } from 'react';
|
|
292
|
+
import { createClient, HydrousRecord, HydrousError } from 'hydrousdb';
|
|
293
|
+
|
|
294
|
+
const db = createClient({
|
|
295
|
+
apiKey: import.meta.env.VITE_HYDROUS_API_KEY,
|
|
296
|
+
bucketKey: import.meta.env.VITE_HYDROUS_BUCKET_KEY,
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
export function useRecords(limit = 20) {
|
|
300
|
+
const [records, setRecords] = useState<HydrousRecord[]>([]);
|
|
301
|
+
const [loading, setLoading] = useState(true);
|
|
302
|
+
const [error, setError] = useState<string | null>(null);
|
|
303
|
+
|
|
304
|
+
useEffect(() => {
|
|
305
|
+
const controller = new AbortController();
|
|
306
|
+
|
|
307
|
+
db.records.query({ limit }, { signal: controller.signal })
|
|
308
|
+
.then(r => setRecords(r.data))
|
|
309
|
+
.catch(e => { if (!(e instanceof DOMException)) setError(String(e)); })
|
|
310
|
+
.finally(() => setLoading(false));
|
|
311
|
+
|
|
312
|
+
return () => controller.abort();
|
|
313
|
+
}, [limit]);
|
|
314
|
+
|
|
315
|
+
return { records, loading, error };
|
|
316
|
+
}
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
### Node.js / Express
|
|
322
|
+
|
|
323
|
+
```ts
|
|
324
|
+
// server.ts
|
|
325
|
+
import express from 'express';
|
|
326
|
+
import { createClient, HydrousError } from 'hydrousdb';
|
|
327
|
+
|
|
328
|
+
const db = createClient({
|
|
329
|
+
apiKey: process.env.HYDROUS_API_KEY!,
|
|
330
|
+
bucketKey: process.env.HYDROUS_BUCKET_KEY!,
|
|
331
|
+
});
|
|
332
|
+
const app = express();
|
|
333
|
+
app.use(express.json());
|
|
334
|
+
|
|
335
|
+
app.get('/records', async (req, res) => {
|
|
336
|
+
try {
|
|
337
|
+
const result = await db.records.query({ limit: 50 });
|
|
338
|
+
res.json(result);
|
|
339
|
+
} catch (err) {
|
|
340
|
+
if (err instanceof HydrousError) return res.status(err.status).json({ error: err.message });
|
|
341
|
+
res.status(500).json({ error: 'Internal Server Error' });
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
app.listen(3000, () => console.log('Listening on :3000'));
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
---
|
|
349
|
+
|
|
350
|
+
## API Reference
|
|
351
|
+
|
|
352
|
+
### `createClient`
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
import { createClient } from 'hydrousdb';
|
|
356
|
+
|
|
357
|
+
const db = createClient({
|
|
358
|
+
apiKey: string, // required — your HydrousDB API key
|
|
359
|
+
bucketKey: string, // required — your bucket identifier
|
|
360
|
+
baseUrl?: string, // override API base URL
|
|
361
|
+
timeout?: number, // request timeout in ms (default: 30_000)
|
|
362
|
+
retries?: number, // retries on network/5xx errors (default: 2)
|
|
363
|
+
});
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
---
|
|
367
|
+
|
|
368
|
+
### Records
|
|
369
|
+
|
|
370
|
+
All methods live on `db.records`.
|
|
371
|
+
|
|
372
|
+
| Method | Description |
|
|
373
|
+
|---|---|
|
|
374
|
+
| `get(recordId, opts?)` | Fetch a single record |
|
|
375
|
+
| `getSnapshot(recordId, generation, opts?)` | Fetch a historical version |
|
|
376
|
+
| `query(opts?)` | Query a collection with filters / pagination |
|
|
377
|
+
| `queryAll(opts?)` | Fetch all pages automatically |
|
|
378
|
+
| `insert(payload, opts?)` | Create a new record |
|
|
379
|
+
| `update(payload, opts?)` | Update an existing record |
|
|
380
|
+
| `delete(recordId, opts?)` | Delete a record |
|
|
381
|
+
| `exists(recordId, opts?)` | HEAD check — returns metadata or `null` |
|
|
382
|
+
| `batchInsert(payload, opts?)` | Insert up to 500 records |
|
|
383
|
+
| `batchUpdate(payload, opts?)` | Update up to 500 records |
|
|
384
|
+
| `batchDelete(payload, opts?)` | Delete up to 500 records |
|
|
385
|
+
|
|
386
|
+
#### `db.records.get(recordId, options?)`
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
const { data, history } = await db.records.get('rec_abc', { showHistory: true });
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
#### `db.records.query(options?)`
|
|
393
|
+
|
|
394
|
+
```ts
|
|
395
|
+
const { data, meta } = await db.records.query({
|
|
396
|
+
filters: [{ field: 'status', op: '==', value: 'active' }],
|
|
397
|
+
timeScope: '30d',
|
|
398
|
+
sortOrder: 'desc',
|
|
399
|
+
limit: 50,
|
|
400
|
+
cursor: meta.nextCursor ?? undefined, // for pagination
|
|
401
|
+
fields: 'id,name,status', // select specific fields
|
|
402
|
+
});
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
**Filter operators:** `==` `!=` `>` `<` `>=` `<=` `contains`
|
|
406
|
+
**Max 3 filters per query.**
|
|
407
|
+
|
|
408
|
+
#### `db.records.insert(payload)`
|
|
409
|
+
|
|
410
|
+
```ts
|
|
411
|
+
const { data, meta } = await db.records.insert({
|
|
412
|
+
values: { name: 'Alice', role: 'admin', score: 100 },
|
|
413
|
+
queryableFields: ['name', 'role'], // fields you want to filter by later
|
|
414
|
+
userEmail: 'system@example.com',
|
|
415
|
+
});
|
|
416
|
+
// meta.id — the new record's ID
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
#### `db.records.update(payload)`
|
|
420
|
+
|
|
421
|
+
```ts
|
|
422
|
+
await db.records.update({
|
|
423
|
+
recordId: 'rec_abc',
|
|
424
|
+
values: { score: 150 },
|
|
425
|
+
track_record_history: true, // snapshot the previous version
|
|
426
|
+
reason: 'Manual score adjustment',
|
|
427
|
+
});
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
#### `db.records.batchInsert(payload)`
|
|
431
|
+
|
|
432
|
+
```ts
|
|
433
|
+
const result = await db.records.batchInsert({
|
|
434
|
+
records: [
|
|
435
|
+
{ name: 'Alice', score: 99 },
|
|
436
|
+
{ name: 'Bob', score: 82 },
|
|
437
|
+
],
|
|
438
|
+
queryableFields: ['name'],
|
|
439
|
+
userEmail: 'import@example.com',
|
|
440
|
+
});
|
|
441
|
+
// result.meta.failed — number of records that failed
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
---
|
|
445
|
+
|
|
446
|
+
### Auth
|
|
447
|
+
|
|
448
|
+
All methods live on `db.auth`.
|
|
449
|
+
|
|
450
|
+
| Method | Description |
|
|
451
|
+
|---|---|
|
|
452
|
+
| `signUp(payload, opts?)` | Register a new user |
|
|
453
|
+
| `signIn(payload, opts?)` | Authenticate with email + password |
|
|
454
|
+
| `signOut(payload, opts?)` | Revoke session(s) |
|
|
455
|
+
| `validateSession(sessionId, opts?)` | Verify a session is valid |
|
|
456
|
+
| `refreshSession(refreshToken, opts?)` | Rotate session using refresh token |
|
|
457
|
+
| `getUser(userId, opts?)` | Fetch user by ID |
|
|
458
|
+
| `listUsers(opts?)` | Paginated user list |
|
|
459
|
+
| `listAllUsers(opts?)` | All users (auto-paginates) |
|
|
460
|
+
| `updateUser(payload, opts?)` | Update user profile |
|
|
461
|
+
| `deleteUser(userId, opts?)` | Soft-delete a user |
|
|
462
|
+
| `changePassword(payload, opts?)` | Change password (requires old password) |
|
|
463
|
+
| `requestPasswordReset(payload, opts?)` | Trigger reset email |
|
|
464
|
+
| `confirmPasswordReset(payload, opts?)` | Confirm reset with token |
|
|
465
|
+
| `requestEmailVerification(payload, opts?)` | Trigger verification email |
|
|
466
|
+
| `confirmEmailVerification(payload, opts?)` | Confirm email with token |
|
|
467
|
+
| `lockAccount(payload, opts?)` | Lock account for a duration |
|
|
468
|
+
| `unlockAccount(userId, opts?)` | Unlock account |
|
|
469
|
+
|
|
470
|
+
#### Auth flow example
|
|
471
|
+
|
|
472
|
+
```ts
|
|
473
|
+
// 1. Sign up
|
|
474
|
+
const { data: user, session } = await db.auth.signUp({
|
|
475
|
+
email: 'alice@example.com',
|
|
476
|
+
password: 'Str0ng@Pass!',
|
|
477
|
+
fullName: 'Alice Smith',
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
// 2. Store session tokens (e.g. in a cookie or localStorage)
|
|
481
|
+
const { sessionId, refreshToken, expiresAt } = session;
|
|
482
|
+
|
|
483
|
+
// 3. On each request, validate the session
|
|
484
|
+
const { data: currentUser } = await db.auth.validateSession(sessionId);
|
|
485
|
+
|
|
486
|
+
// 4. Before session expires, refresh it
|
|
487
|
+
const { session: newSession } = await db.auth.refreshSession(refreshToken);
|
|
488
|
+
|
|
489
|
+
// 5. Sign out
|
|
490
|
+
await db.auth.signOut({ sessionId });
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
---
|
|
494
|
+
|
|
495
|
+
### Analytics
|
|
496
|
+
|
|
497
|
+
All methods live on `db.analytics`. Every method maps to a BigQuery-backed analytics query. The server `queryType` string each method sends is noted for reference.
|
|
498
|
+
|
|
499
|
+
| Method | Server `queryType` | Description |
|
|
500
|
+
|---|---|---|
|
|
501
|
+
| `count(opts?)` | `"count"` | Total record count |
|
|
502
|
+
| `distribution(field, opts?)` | `"distribution"` | Value histogram for a field |
|
|
503
|
+
| `sum(field, opts?)` | `"sum"` | Sum a numeric field, with optional group-by |
|
|
504
|
+
| `timeSeries(opts?)` | `"timeSeries"` | Record count over time |
|
|
505
|
+
| `fieldTimeSeries(field, opts?)` | `"fieldTimeSeries"` | Numeric field aggregated over time |
|
|
506
|
+
| `topN(field, n, opts?)` | `"topN"` | Top N field values by frequency |
|
|
507
|
+
| `stats(field, opts?)` | `"stats"` | min/max/avg/stddev/p50/p90/p99 |
|
|
508
|
+
| `records(opts?)` | `"records"` | Filtered + paginated raw records |
|
|
509
|
+
| `multiMetric(metrics, opts?)` | `"multiMetric"` | Multiple aggregations in one call |
|
|
510
|
+
| `storageStats(opts?)` | `"storageStats"` | Bucket storage usage |
|
|
511
|
+
| `crossBucket(opts)` | `"crossBucket"` | Compare metric across buckets |
|
|
512
|
+
| `query(payload, opts?)` | any | Raw query — full control |
|
|
513
|
+
|
|
514
|
+
#### Date ranges
|
|
515
|
+
|
|
516
|
+
All analytics methods accept a `dateRange` option:
|
|
517
|
+
|
|
518
|
+
```ts
|
|
519
|
+
// Scope to a specific date window
|
|
520
|
+
const dateRange = { startDate: '2025-01-01', endDate: '2025-12-31' };
|
|
521
|
+
|
|
522
|
+
// Or scope to a year / month / day
|
|
523
|
+
const dateRange = { year: '2025', month: '03' };
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
#### Examples
|
|
527
|
+
|
|
528
|
+
```ts
|
|
529
|
+
// Total records
|
|
530
|
+
const { data } = await db.analytics.count();
|
|
531
|
+
console.log(data.count);
|
|
532
|
+
|
|
533
|
+
// Status breakdown
|
|
534
|
+
const { data } = await db.analytics.distribution('status');
|
|
535
|
+
// [{ value: 'active', count: 80 }, { value: 'archived', count: 20 }]
|
|
536
|
+
|
|
537
|
+
// Monthly revenue for Q1
|
|
538
|
+
const { data } = await db.analytics.sum('amount', {
|
|
539
|
+
groupBy: 'region',
|
|
540
|
+
dateRange: { startDate: '2025-01-01', endDate: '2025-03-31' },
|
|
541
|
+
});
|
|
542
|
+
|
|
543
|
+
// Daily signups this week
|
|
544
|
+
const { data } = await db.analytics.timeSeries({
|
|
545
|
+
granularity: 'day',
|
|
546
|
+
dateRange: { startDate: '2025-03-01' },
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
// Score percentiles
|
|
550
|
+
const { data } = await db.analytics.stats('score');
|
|
551
|
+
console.log(data.avg, data.p90, data.p99);
|
|
552
|
+
|
|
553
|
+
// Top 5 countries
|
|
554
|
+
const { data } = await db.analytics.topN('country', 5);
|
|
555
|
+
|
|
556
|
+
// Dashboard stats — one round-trip for multiple metrics
|
|
557
|
+
const { data } = await db.analytics.multiMetric([
|
|
558
|
+
{ name: 'totalRevenue', field: 'amount', aggregation: 'sum' },
|
|
559
|
+
{ name: 'avgScore', field: 'score', aggregation: 'avg' },
|
|
560
|
+
{ name: 'userCount', field: 'userId', aggregation: 'count' },
|
|
561
|
+
]);
|
|
562
|
+
console.log(data.totalRevenue, data.avgScore);
|
|
563
|
+
|
|
564
|
+
// Storage usage
|
|
565
|
+
const { data } = await db.analytics.storageStats();
|
|
566
|
+
console.log(data.totalRecords, data.totalBytes);
|
|
567
|
+
|
|
568
|
+
// Cross-bucket revenue comparison
|
|
569
|
+
const { data } = await db.analytics.crossBucket({
|
|
570
|
+
bucketKeys: ['sales-2024', 'sales-2025'],
|
|
571
|
+
field: 'amount',
|
|
572
|
+
aggregation: 'sum',
|
|
573
|
+
});
|
|
574
|
+
|
|
575
|
+
// Raw records with filters (supports: == != > < >= <= CONTAINS)
|
|
576
|
+
const { data } = await db.analytics.records({
|
|
577
|
+
filters: [{ field: 'role', op: '==', value: 'admin' }],
|
|
578
|
+
selectFields: ['email', 'createdAt'],
|
|
579
|
+
limit: 50,
|
|
580
|
+
offset: 0,
|
|
581
|
+
});
|
|
582
|
+
console.log(data.data, data.hasMore);
|
|
583
|
+
```
|
|
584
|
+
|
|
585
|
+
---
|
|
586
|
+
|
|
587
|
+
## Error Handling
|
|
588
|
+
|
|
589
|
+
The SDK throws typed errors you can `instanceof` check:
|
|
590
|
+
|
|
591
|
+
```ts
|
|
592
|
+
import { HydrousError, HydrousNetworkError, HydrousTimeoutError } from 'hydrousdb';
|
|
593
|
+
|
|
594
|
+
try {
|
|
595
|
+
await db.records.get('rec_does_not_exist');
|
|
596
|
+
} catch (err) {
|
|
597
|
+
if (err instanceof HydrousError) {
|
|
598
|
+
console.error(err.message); // human-readable message
|
|
599
|
+
console.error(err.status); // HTTP status code (e.g. 404)
|
|
600
|
+
console.error(err.code); // machine-readable code (e.g. 'NOT_FOUND')
|
|
601
|
+
console.error(err.details); // validation error details array
|
|
602
|
+
console.error(err.requestId); // server request ID for support
|
|
603
|
+
} else if (err instanceof HydrousTimeoutError) {
|
|
604
|
+
console.error('Request timed out');
|
|
605
|
+
} else if (err instanceof HydrousNetworkError) {
|
|
606
|
+
console.error('Network failure:', err.cause);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
---
|
|
612
|
+
|
|
613
|
+
## Pagination
|
|
614
|
+
|
|
615
|
+
HydrousDB uses opaque cursor strings for pagination.
|
|
616
|
+
|
|
617
|
+
```ts
|
|
618
|
+
// Manual pagination
|
|
619
|
+
let cursor: string | null = null;
|
|
620
|
+
|
|
621
|
+
do {
|
|
622
|
+
const { data, meta } = await db.records.query({
|
|
623
|
+
limit: 100,
|
|
624
|
+
cursor: cursor ?? undefined,
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
processBatch(data);
|
|
628
|
+
cursor = meta.nextCursor;
|
|
629
|
+
} while (cursor);
|
|
630
|
+
|
|
631
|
+
// — OR — let the SDK handle it for you
|
|
632
|
+
const allRecords = await db.records.queryAll({
|
|
633
|
+
filters: [{ field: 'status', op: '==', value: 'active' }],
|
|
634
|
+
});
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
---
|
|
638
|
+
|
|
639
|
+
## TypeScript
|
|
640
|
+
|
|
641
|
+
All types are exported from the root package:
|
|
642
|
+
|
|
643
|
+
```ts
|
|
644
|
+
import type {
|
|
645
|
+
HydrousRecord,
|
|
646
|
+
QueryOptions,
|
|
647
|
+
InsertRecordPayload,
|
|
648
|
+
AuthUser,
|
|
649
|
+
SessionInfo,
|
|
650
|
+
HydrousConfig,
|
|
651
|
+
Filter,
|
|
652
|
+
} from 'hydrousdb';
|
|
653
|
+
```
|
|
654
|
+
|
|
655
|
+
You can also use the generic `query<T>` overload to type your records:
|
|
656
|
+
|
|
657
|
+
```ts
|
|
658
|
+
interface Product {
|
|
659
|
+
name: string;
|
|
660
|
+
price: number;
|
|
661
|
+
category: string;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const { data } = await db.records.query<Product>({
|
|
665
|
+
filters: [{ field: 'category', op: '==', value: 'shoes' }],
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
// data is (Product & HydrousRecord)[]
|
|
669
|
+
console.log(data[0].name, data[0].price);
|
|
670
|
+
```
|
|
671
|
+
|
|
672
|
+
---
|
|
673
|
+
|
|
674
|
+
## Contributing
|
|
675
|
+
|
|
676
|
+
1. Fork the repo and clone it
|
|
677
|
+
2. `npm install`
|
|
678
|
+
3. `npm run dev` — TypeScript watch mode
|
|
679
|
+
4. `npm test` — run the test suite
|
|
680
|
+
5. Open a PR 🚀
|
|
681
|
+
|
|
682
|
+
---
|
|
683
|
+
|
|
684
|
+
## License
|
|
685
|
+
|
|
686
|
+
MIT © HydrousDB
|