create-harper 1.2.2 → 1.3.1
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/lib/install.js +5 -0
- package/package.json +1 -1
- package/template-react/README.md +1 -1
- package/template-react/package.json +2 -0
- package/template-react/resources/README.md +3 -3
- package/template-react/schemas/README.md +2 -2
- package/template-react-ts/README.md +1 -1
- package/template-react-ts/package.json +2 -0
- package/template-react-ts/resources/README.md +3 -3
- package/template-react-ts/schemas/README.md +2 -2
- package/template-vanilla/README.md +1 -1
- package/template-vanilla/package.json +2 -0
- package/template-vanilla/resources/README.md +3 -3
- package/template-vanilla/schemas/README.md +2 -2
- package/template-vanilla-ts/README.md +1 -1
- package/template-vanilla-ts/package.json +2 -0
- package/template-vanilla-ts/resources/README.md +3 -3
- package/template-vanilla-ts/schemas/README.md +2 -2
- package/template-react/AGENTS.md +0 -22
- package/template-react/skills/adding-tables-with-schemas.md +0 -34
- package/template-react/skills/automatic-apis.md +0 -53
- package/template-react/skills/automatic-rest-apis.md +0 -41
- package/template-react/skills/caching.md +0 -113
- package/template-react/skills/checking-authentication.md +0 -281
- package/template-react/skills/custom-resources.md +0 -86
- package/template-react/skills/defining-relationships.md +0 -71
- package/template-react/skills/deploying-to-harper-fabric.md +0 -20
- package/template-react/skills/extending-tables.md +0 -70
- package/template-react/skills/handling-binary-data.md +0 -67
- package/template-react/skills/programmatic-table-requests.md +0 -185
- package/template-react/skills/querying-rest-apis.md +0 -69
- package/template-react/skills/real-time-apps.md +0 -75
- package/template-react/skills/serving-web-content.md +0 -82
- package/template-react/skills/typescript-type-stripping.md +0 -47
- package/template-react/skills/using-blob-datatype.md +0 -131
- package/template-react/skills/vector-indexing.md +0 -215
- package/template-react-ts/AGENTS.md +0 -22
- package/template-react-ts/skills/adding-tables-with-schemas.md +0 -34
- package/template-react-ts/skills/automatic-apis.md +0 -53
- package/template-react-ts/skills/automatic-rest-apis.md +0 -41
- package/template-react-ts/skills/caching.md +0 -113
- package/template-react-ts/skills/checking-authentication.md +0 -281
- package/template-react-ts/skills/custom-resources.md +0 -86
- package/template-react-ts/skills/defining-relationships.md +0 -71
- package/template-react-ts/skills/deploying-to-harper-fabric.md +0 -20
- package/template-react-ts/skills/extending-tables.md +0 -70
- package/template-react-ts/skills/handling-binary-data.md +0 -67
- package/template-react-ts/skills/programmatic-table-requests.md +0 -185
- package/template-react-ts/skills/querying-rest-apis.md +0 -69
- package/template-react-ts/skills/real-time-apps.md +0 -75
- package/template-react-ts/skills/serving-web-content.md +0 -82
- package/template-react-ts/skills/typescript-type-stripping.md +0 -47
- package/template-react-ts/skills/using-blob-datatype.md +0 -131
- package/template-react-ts/skills/vector-indexing.md +0 -215
- package/template-vanilla/AGENTS.md +0 -22
- package/template-vanilla/skills/adding-tables-with-schemas.md +0 -34
- package/template-vanilla/skills/automatic-apis.md +0 -53
- package/template-vanilla/skills/automatic-rest-apis.md +0 -41
- package/template-vanilla/skills/caching.md +0 -113
- package/template-vanilla/skills/checking-authentication.md +0 -281
- package/template-vanilla/skills/custom-resources.md +0 -86
- package/template-vanilla/skills/defining-relationships.md +0 -71
- package/template-vanilla/skills/deploying-to-harper-fabric.md +0 -20
- package/template-vanilla/skills/extending-tables.md +0 -70
- package/template-vanilla/skills/handling-binary-data.md +0 -67
- package/template-vanilla/skills/programmatic-table-requests.md +0 -185
- package/template-vanilla/skills/querying-rest-apis.md +0 -69
- package/template-vanilla/skills/real-time-apps.md +0 -75
- package/template-vanilla/skills/serving-web-content.md +0 -82
- package/template-vanilla/skills/typescript-type-stripping.md +0 -47
- package/template-vanilla/skills/using-blob-datatype.md +0 -131
- package/template-vanilla/skills/vector-indexing.md +0 -215
- package/template-vanilla-ts/AGENTS.md +0 -22
- package/template-vanilla-ts/skills/adding-tables-with-schemas.md +0 -34
- package/template-vanilla-ts/skills/automatic-apis.md +0 -53
- package/template-vanilla-ts/skills/automatic-rest-apis.md +0 -41
- package/template-vanilla-ts/skills/caching.md +0 -113
- package/template-vanilla-ts/skills/checking-authentication.md +0 -281
- package/template-vanilla-ts/skills/custom-resources.md +0 -86
- package/template-vanilla-ts/skills/defining-relationships.md +0 -71
- package/template-vanilla-ts/skills/deploying-to-harper-fabric.md +0 -20
- package/template-vanilla-ts/skills/extending-tables.md +0 -70
- package/template-vanilla-ts/skills/handling-binary-data.md +0 -67
- package/template-vanilla-ts/skills/programmatic-table-requests.md +0 -185
- package/template-vanilla-ts/skills/querying-rest-apis.md +0 -69
- package/template-vanilla-ts/skills/real-time-apps.md +0 -75
- package/template-vanilla-ts/skills/serving-web-content.md +0 -82
- package/template-vanilla-ts/skills/typescript-type-stripping.md +0 -47
- package/template-vanilla-ts/skills/using-blob-datatype.md +0 -131
- package/template-vanilla-ts/skills/vector-indexing.md +0 -215
|
@@ -1,281 +0,0 @@
|
|
|
1
|
-
# Checking Authentication and Sessions in this app (Harper Resources)
|
|
2
|
-
|
|
3
|
-
This project uses Harper Resource classes with cookie-backed sessions to enforce authentication and authorization. Below are the concrete patterns used across resources like `resources/me.ts`, `resources/signIn.ts`, `resources/signOut.ts`, and protected endpoints such as `resources/downloadAlbumArtwork.ts`.
|
|
4
|
-
|
|
5
|
-
Important: To actually enforce sessions (even on localhost), Harper must not auto-authorize the local loopback as the superuser. Ensure the following in your Harper config (see `~/hdb/harperdb-config.yaml`):
|
|
6
|
-
|
|
7
|
-
```yaml
|
|
8
|
-
authentication:
|
|
9
|
-
authorizeLocal: false
|
|
10
|
-
enableSessions: true
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
With `authorizeLocal: true`, all local requests would be auto-authorized as the superuser, bypassing these checks. We keep it off to ensure session checks are respected.
|
|
14
|
-
|
|
15
|
-
## Public vs protected routes
|
|
16
|
-
|
|
17
|
-
- Public resources explicitly allow the method via `allowRead()` or `allowCreate()` or similara returning `true`.
|
|
18
|
-
- Protected handlers perform checks up-front using the current session user (and, for privileged actions, a helper like `ensureSuperUser`).
|
|
19
|
-
|
|
20
|
-
## Creating a session (sign in)
|
|
21
|
-
|
|
22
|
-
Pattern from `resources/signIn.ts`:
|
|
23
|
-
|
|
24
|
-
```ts
|
|
25
|
-
import { type Context, type RequestTargetOrId, Resource } from 'harperdb';
|
|
26
|
-
|
|
27
|
-
export interface LoginBody {
|
|
28
|
-
username?: string;
|
|
29
|
-
password?: string;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export class SignIn extends Resource {
|
|
33
|
-
static loadAsInstance = false;
|
|
34
|
-
|
|
35
|
-
allowCreate() {
|
|
36
|
-
return true; // public endpoint
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
async post(_target: RequestTargetOrId, data: LoginBody) {
|
|
40
|
-
const errors: string[] = [];
|
|
41
|
-
if (!data.username) { errors.push('username'); }
|
|
42
|
-
if (!data.password) { errors.push('password'); }
|
|
43
|
-
if (errors.length) {
|
|
44
|
-
return new Response(
|
|
45
|
-
`Please include the ${errors.join(' and ')} in your request.`,
|
|
46
|
-
{ status: 400 },
|
|
47
|
-
);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const context = this.getContext() as Context as any;
|
|
51
|
-
try {
|
|
52
|
-
await context.login(data.username, data.password);
|
|
53
|
-
} catch {
|
|
54
|
-
return new Response('Please check your credentials and try again.', {
|
|
55
|
-
status: 403,
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
return new Response('Welcome back!', { status: 200 });
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
- `context.login(username, password)` creates a session and sets the session cookie on the response.
|
|
64
|
-
- Missing fields → `400 Bad Request`.
|
|
65
|
-
- Invalid credentials → `403 Forbidden` (don’t leak which field was wrong).
|
|
66
|
-
|
|
67
|
-
## Reading the current user (who am I)
|
|
68
|
-
|
|
69
|
-
Pattern from `resources/me.ts`:
|
|
70
|
-
|
|
71
|
-
```ts
|
|
72
|
-
import { Resource } from 'harperdb';
|
|
73
|
-
|
|
74
|
-
export class Me extends Resource {
|
|
75
|
-
static loadAsInstance = false;
|
|
76
|
-
|
|
77
|
-
allowRead() {
|
|
78
|
-
return true; // public: returns data only if session exists
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
async get() {
|
|
82
|
-
const user = this.getCurrentUser?.();
|
|
83
|
-
if (!user?.username) {
|
|
84
|
-
// Not signed in; return 200 with no body to make polling simple on the client
|
|
85
|
-
return new Response(null, { status: 200 });
|
|
86
|
-
}
|
|
87
|
-
return {
|
|
88
|
-
active: user.active,
|
|
89
|
-
role: user.role,
|
|
90
|
-
username: user.username,
|
|
91
|
-
created: user.__createdtime__,
|
|
92
|
-
updated: user.__updatedtime__,
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
- Use `this.getCurrentUser?.()` to access the session’s user (if any).
|
|
99
|
-
- It may be `undefined` when unauthenticated. Handle that case explicitly.
|
|
100
|
-
|
|
101
|
-
## Destroying a session (sign out)
|
|
102
|
-
|
|
103
|
-
Pattern from `resources/signOut.ts`:
|
|
104
|
-
|
|
105
|
-
```ts
|
|
106
|
-
import { type Context, Resource } from 'harperdb';
|
|
107
|
-
|
|
108
|
-
export class SignOut extends Resource {
|
|
109
|
-
static loadAsInstance = false;
|
|
110
|
-
|
|
111
|
-
allowCreate() {
|
|
112
|
-
return true; // public endpoint, but requires a session to actually act
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
async post() {
|
|
116
|
-
const user = this.getCurrentUser();
|
|
117
|
-
if (!user?.username) {
|
|
118
|
-
return new Response('Not signed in.', { status: 401 });
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const context = this.getContext() as Context as any;
|
|
122
|
-
await context.session?.delete?.(context.session.id);
|
|
123
|
-
return new Response('Signed out successfully.', { status: 200 });
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
```
|
|
127
|
-
|
|
128
|
-
- If the request has no session, return `401 Unauthorized`.
|
|
129
|
-
- Otherwise delete the current session via `context.session.delete(sessionId)`.
|
|
130
|
-
|
|
131
|
-
## Protecting privileged endpoints
|
|
132
|
-
|
|
133
|
-
For admin-only or otherwise privileged actions, use the `ensureSuperUser` helper with the current user.
|
|
134
|
-
|
|
135
|
-
```ts
|
|
136
|
-
import {
|
|
137
|
-
RequestTarget,
|
|
138
|
-
type RequestTargetOrId,
|
|
139
|
-
Resource,
|
|
140
|
-
tables,
|
|
141
|
-
} from 'harperdb';
|
|
142
|
-
import { ensureSuperUser } from './common/ensureSuperUser.ts';
|
|
143
|
-
|
|
144
|
-
export class DoSomethingInteresting extends Resource {
|
|
145
|
-
static loadAsInstance = false;
|
|
146
|
-
|
|
147
|
-
async get(target: RequestTargetOrId) {
|
|
148
|
-
ensureSuperUser(this.getCurrentUser());
|
|
149
|
-
// … fetch and return the artwork
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
```
|
|
153
|
-
|
|
154
|
-
`ensureSuperUser` throws a `403` if the user is not a super user:
|
|
155
|
-
|
|
156
|
-
```ts
|
|
157
|
-
import { type User } from 'harperdb';
|
|
158
|
-
|
|
159
|
-
export function ensureSuperUser(user: User | undefined) {
|
|
160
|
-
if (!user?.role?.permission?.super_user) {
|
|
161
|
-
let error = new Error('You do not have permission to perform this action.');
|
|
162
|
-
(error as any).statusCode = 403;
|
|
163
|
-
throw error;
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
```
|
|
167
|
-
|
|
168
|
-
## Status code conventions used here
|
|
169
|
-
|
|
170
|
-
- 200: Successful operation. For `GET /me`, a `200` with empty body means “not signed in”.
|
|
171
|
-
- 400: Missing required fields (e.g., username/password on sign-in).
|
|
172
|
-
- 401: No current session for an action that requires one (e.g., sign out when not signed in).
|
|
173
|
-
- 403: Authenticated but not authorized (bad credentials on login attempt, or insufficient privileges).
|
|
174
|
-
|
|
175
|
-
## Client considerations
|
|
176
|
-
|
|
177
|
-
- Sessions are cookie-based; the server handles setting and reading the cookie via Harper. If you make cross-origin requests, ensure the appropriate `credentials` mode and CORS settings.
|
|
178
|
-
- If developing locally, double-check the server config still has `authentication.authorizeLocal: false` to avoid accidental superuser bypass.
|
|
179
|
-
|
|
180
|
-
## Token-based auth (JWT + refresh token) for non-browser clients
|
|
181
|
-
|
|
182
|
-
Cookie-backed sessions are great for browser flows. For CLI tools, mobile apps, or other non-browser clients, it’s often easier to use **explicit tokens**:
|
|
183
|
-
|
|
184
|
-
- **JWT (`operation_token`)**: short-lived bearer token used to authorize API requests.
|
|
185
|
-
- **Refresh token (`refresh_token`)**: longer-lived token used to mint a new JWT when it expires.
|
|
186
|
-
|
|
187
|
-
This project includes two Resource patterns for that flow:
|
|
188
|
-
|
|
189
|
-
### Issuing tokens: `IssueTokens`
|
|
190
|
-
|
|
191
|
-
**Description / use case:** Generate `{ refreshToken, jwt }` either:
|
|
192
|
-
|
|
193
|
-
- with an existing Authorization token (either Basic Auth or a JWT) and you want to issue new tokens, or
|
|
194
|
-
- from an explicit `{ username, password }` payload (useful for direct “login” from a CLI/mobile client).
|
|
195
|
-
|
|
196
|
-
```
|
|
197
|
-
js
|
|
198
|
-
export class IssueTokens extends Resource {
|
|
199
|
-
static loadAsInstance = false;
|
|
200
|
-
|
|
201
|
-
async get(target) {
|
|
202
|
-
const { refresh_token: refreshToken, operation_token: jwt } =
|
|
203
|
-
await databases.system.hdb_user.operation(
|
|
204
|
-
{ operation: 'create_authentication_tokens' },
|
|
205
|
-
this.getContext(),
|
|
206
|
-
);
|
|
207
|
-
return { refreshToken, jwt };
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
async post(target, data) {
|
|
211
|
-
if (!data.username || !data.password) {
|
|
212
|
-
throw new Error('username and password are required');
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
const { refresh_token: refreshToken, operation_token: jwt } =
|
|
216
|
-
await databases.system.hdb_user.operation({
|
|
217
|
-
operation: 'create_authentication_tokens',
|
|
218
|
-
username: data.username,
|
|
219
|
-
password: data.password,
|
|
220
|
-
});
|
|
221
|
-
return { refreshToken, jwt };
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
```
|
|
225
|
-
|
|
226
|
-
**Recommended documentation notes to include:**
|
|
227
|
-
|
|
228
|
-
- `GET` variant: intended for “I already have an Authorization token, give me new tokens”.
|
|
229
|
-
- `POST` variant: intended for “I have credentials, give me tokens”.
|
|
230
|
-
- Response shape:
|
|
231
|
-
- `refreshToken`: store securely (long-lived).
|
|
232
|
-
- `jwt`: attach to requests (short-lived).
|
|
233
|
-
|
|
234
|
-
### Refreshing a JWT: `RefreshJWT`
|
|
235
|
-
|
|
236
|
-
**Description / use case:** When the JWT expires, the client uses the refresh token to get a new JWT without re-supplying username/password.
|
|
237
|
-
|
|
238
|
-
```
|
|
239
|
-
js
|
|
240
|
-
export class RefreshJWT extends Resource {
|
|
241
|
-
static loadAsInstance = false;
|
|
242
|
-
|
|
243
|
-
async post(target, data) {
|
|
244
|
-
if (!data.refreshToken) {
|
|
245
|
-
throw new Error('refreshToken is required');
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
const { operation_token: jwt } = await databases.system.hdb_user.operation({
|
|
249
|
-
operation: 'refresh_operation_token',
|
|
250
|
-
refresh_token: data.refreshToken,
|
|
251
|
-
});
|
|
252
|
-
return { jwt };
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
```
|
|
256
|
-
|
|
257
|
-
**Recommended documentation notes to include:**
|
|
258
|
-
|
|
259
|
-
- Requires `refreshToken` in the request body.
|
|
260
|
-
- Returns a new `{ jwt }`.
|
|
261
|
-
- If refresh fails (expired/revoked), client must re-authenticate (e.g., call `IssueTokens.post` again).
|
|
262
|
-
|
|
263
|
-
### Suggested client flow (high-level)
|
|
264
|
-
|
|
265
|
-
1. **Sign in (token flow)**
|
|
266
|
-
- POST /IssueTokens/ with a body of `{ "username": "your username", "password": "your password" }` or GET /IssueTokens/ with an existing Authorization token.
|
|
267
|
-
- Receive `{ jwt, refreshToken }` in the response
|
|
268
|
-
2. **Call protected APIs**
|
|
269
|
-
- Send the JWT with each request in the Authorization header (as your auth mechanism expects)
|
|
270
|
-
3. **JWT expires**
|
|
271
|
-
- POST /RefreshJWT/ with a body of `{ "refreshToken": "your refresh token" }`.
|
|
272
|
-
- Receive `{ jwt }` in the response and continue
|
|
273
|
-
|
|
274
|
-
## Quick checklist
|
|
275
|
-
|
|
276
|
-
- [ ] Public endpoints explicitly `allowRead`/`allowCreate` as needed.
|
|
277
|
-
- [ ] Sign-in uses `context.login` and handles 400/403 correctly.
|
|
278
|
-
- [ ] Protected routes call `ensureSuperUser(this.getCurrentUser())` (or another role check) before doing work.
|
|
279
|
-
- [ ] Sign-out verifies a session and deletes it.
|
|
280
|
-
- [ ] `authentication.authorizeLocal` is `false` and `enableSessions` is `true` in Harper config.
|
|
281
|
-
- [ ] If using tokens: `IssueTokens` issues `{ jwt, refreshToken }`, `RefreshJWT` refreshes `{ jwt }` with a `refreshToken`.
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
# Custom Resources in Harper
|
|
2
|
-
|
|
3
|
-
Custom Resources allow you to define your own REST endpoints with custom logic by writing JavaScript or TypeScript code. This is useful when the automatic CRUD operations provided by `@table @export` are not enough.
|
|
4
|
-
|
|
5
|
-
Harper supports [TypeScript Type Stripping](typescript-type-stripping.md), allowing you to use TypeScript directly without additional build tools on supported Node.js versions.
|
|
6
|
-
|
|
7
|
-
## Do you need a custom resource?
|
|
8
|
-
|
|
9
|
-
Exported tables have [automatic APIs](./automatic-apis.md) as a part of them. These APIs may be enough for what you need. Take a look at [extendings tables](./extending-tables.md) to learn more about resources with a backing table.
|
|
10
|
-
|
|
11
|
-
## Defining a Custom Resource
|
|
12
|
-
|
|
13
|
-
To create a custom resource:
|
|
14
|
-
|
|
15
|
-
1. Create a `.ts` (or `.js`) file in the directory specified by `jsResource` in `config.yaml` (usually `resources/`).
|
|
16
|
-
2. Export a class that extends the `Resource` class from the `harperdb` module.
|
|
17
|
-
|
|
18
|
-
### Example: `resources/greeting.ts`
|
|
19
|
-
|
|
20
|
-
```typescript
|
|
21
|
-
import { type RecordObject, type RequestTargetOrId, Resource } from 'harperdb';
|
|
22
|
-
|
|
23
|
-
interface GreetingRecord {
|
|
24
|
-
greeting: string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export class Greeting extends Resource<GreetingRecord> {
|
|
28
|
-
// Set to false if you want Harper to manage the instance lifecycle
|
|
29
|
-
static loadAsInstance = false;
|
|
30
|
-
|
|
31
|
-
async get(target?: RequestTargetOrId): Promise<GreetingRecord> {
|
|
32
|
-
return { greeting: 'Hello from a custom GET endpoint!' };
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
async post(
|
|
36
|
-
target: RequestTargetOrId,
|
|
37
|
-
newRecord: Partial<GreetingRecord & RecordObject>,
|
|
38
|
-
): Promise<GreetingRecord> {
|
|
39
|
-
// Custom logic for handling POST requests
|
|
40
|
-
return { greeting: `Hello, ${newRecord.greeting || 'stranger'}!` };
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
## Supported HTTP Methods
|
|
46
|
-
|
|
47
|
-
You can implement any of the following methods in your resource class to handle the corresponding HTTP requests:
|
|
48
|
-
|
|
49
|
-
- `get(target?: RequestTargetOrId)`
|
|
50
|
-
- `post(target: RequestTargetOrId, body: any)`
|
|
51
|
-
- `put(target: RequestTargetOrId, body: any)`
|
|
52
|
-
- `patch(target: RequestTargetOrId, body: any)`
|
|
53
|
-
- `delete(target: RequestTargetOrId)`
|
|
54
|
-
|
|
55
|
-
The `target` parameter typically contains the ID or sub-path from the URL.
|
|
56
|
-
|
|
57
|
-
## Accessing Tables
|
|
58
|
-
|
|
59
|
-
Within your custom resource, you can easily access your database tables using the `tables` object:
|
|
60
|
-
|
|
61
|
-
```typescript
|
|
62
|
-
import { Resource, tables } from 'harperdb';
|
|
63
|
-
|
|
64
|
-
export class MyCustomResource extends Resource {
|
|
65
|
-
async get() {
|
|
66
|
-
// Query a table
|
|
67
|
-
const results = await tables.ExamplePeople.list();
|
|
68
|
-
return results;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
## Configuration
|
|
74
|
-
|
|
75
|
-
Ensure your `config.yaml` is configured to load your resources:
|
|
76
|
-
|
|
77
|
-
```yaml
|
|
78
|
-
jsResource:
|
|
79
|
-
files: 'resources/*.ts'
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
Once defined and configured, your resource will be available at a REST endpoint matching the class name exactly.
|
|
83
|
-
|
|
84
|
-
### Case Sensitivity
|
|
85
|
-
|
|
86
|
-
Paths in Harper are **case-sensitive**. A resource class named `MyResource` will be accessible only at `/MyResource/`, not `/myresource/`.
|
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
# Defining Relationships in Harper
|
|
2
|
-
|
|
3
|
-
Harper allows you to define relationships between tables using the `@relationship` directive in your GraphQL schema. This enables powerful features like automatic joins when querying through REST APIs.
|
|
4
|
-
|
|
5
|
-
## The `@relationship` Directive
|
|
6
|
-
|
|
7
|
-
The `@relationship` directive is applied to a field in your GraphQL type and takes two optional arguments:
|
|
8
|
-
|
|
9
|
-
- `from`: The field in the _current_ table that holds the foreign key.
|
|
10
|
-
- `to`: The field in the _related_ table that holds the foreign key.
|
|
11
|
-
|
|
12
|
-
## Relationship Types
|
|
13
|
-
|
|
14
|
-
### One-to-One and Many-to-One
|
|
15
|
-
|
|
16
|
-
To define a relationship where the current table holds the foreign key, use the `from` argument.
|
|
17
|
-
|
|
18
|
-
```graphql
|
|
19
|
-
type Author @table @export {
|
|
20
|
-
id: ID @primaryKey
|
|
21
|
-
name: String
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
type Book @table @export {
|
|
25
|
-
id: ID @primaryKey
|
|
26
|
-
title: String
|
|
27
|
-
authorId: ID
|
|
28
|
-
# This field resolves to an Author object using authorId
|
|
29
|
-
author: Author @relationship(from: "authorId")
|
|
30
|
-
}
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
### One-to-Many and Many-to-Many
|
|
34
|
-
|
|
35
|
-
To define a relationship where the _related_ table holds the foreign key, use the `to` argument. The field type should be an array.
|
|
36
|
-
|
|
37
|
-
```graphql
|
|
38
|
-
type Author @table @export {
|
|
39
|
-
id: ID @primaryKey
|
|
40
|
-
name: String
|
|
41
|
-
# This field resolves to an array of Books that have this author's ID in their authorId field
|
|
42
|
-
books: [Book] @relationship(to: "authorId")
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
type Book @table @export {
|
|
46
|
-
id: ID @primaryKey
|
|
47
|
-
title: String
|
|
48
|
-
authorId: ID
|
|
49
|
-
}
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
## Querying Relationships
|
|
53
|
-
|
|
54
|
-
Once relationships are defined, you can use them in your REST API queries using dot syntax.
|
|
55
|
-
|
|
56
|
-
Example:
|
|
57
|
-
`GET /Book/?author.name=Harper`
|
|
58
|
-
|
|
59
|
-
This will automatically perform a join and return all books whose author's name is "Harper".
|
|
60
|
-
|
|
61
|
-
You can also use the `select()` operator to include related data in the response:
|
|
62
|
-
|
|
63
|
-
`GET /Author/?select(name,books(title))`
|
|
64
|
-
|
|
65
|
-
This returns authors with their names and a list of their books (only the titles).
|
|
66
|
-
|
|
67
|
-
## Benefits of `@relationship`
|
|
68
|
-
|
|
69
|
-
- **Simplified Queries**: No need for complex manual joins in your code.
|
|
70
|
-
- **Efficient Data Fetching**: Harper optimizes relationship lookups.
|
|
71
|
-
- **Improved API Discoverability**: Related data structures are clearly defined in your schema.
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
# Deploying to Harper Fabric
|
|
2
|
-
|
|
3
|
-
To deploy your application to Harper Fabric, follow these steps:
|
|
4
|
-
|
|
5
|
-
1. **Sign up**: Create an account at [https://fabric.harper.fast](https://fabric.harper.fast) and create a cluster.
|
|
6
|
-
|
|
7
|
-
2. **Configure Environment**: Add your credentials and cluster URL to your `.env` file:
|
|
8
|
-
```bash
|
|
9
|
-
# Deployments
|
|
10
|
-
CLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'
|
|
11
|
-
CLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'
|
|
12
|
-
CLI_TARGET='YOUR_FABRIC.HARPER.FAST_CLUSTER_URL_HERE'
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
3. **Deploy Locally**: Run the following command to deploy from your local environment:
|
|
16
|
-
```bash
|
|
17
|
-
npm run deploy
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
4. **Set up CI/CD**: Customize the included `.github/workflow/deploy.yaml` file and define your secrets in your GitHub repository's action settings to enable continuous deployment.
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
# Extending Table Resources in Harper
|
|
2
|
-
|
|
3
|
-
In Harper, when you define a table in GraphQL and export it, you can extend the automatically generated resource class to add custom logic, validation, or hooks to standard CRUD operations.
|
|
4
|
-
|
|
5
|
-
## Do you need to extend tables?
|
|
6
|
-
|
|
7
|
-
Exported tables have [automatic APIs](./automatic-apis.md) as a part of them. These APIs may be sufficient for what you need.
|
|
8
|
-
|
|
9
|
-
## How to Extend a Table Resource
|
|
10
|
-
|
|
11
|
-
1. Identify the table you want to extend (e.g., `ExamplePeople`).
|
|
12
|
-
2. Create a TypeScript file in your `resources/` folder.
|
|
13
|
-
3. Export a class that extends `tables.YourTableName`.
|
|
14
|
-
4. Override the desired methods (e.g., `post`, `get`, `put`, `patch`, `delete`).
|
|
15
|
-
|
|
16
|
-
### Example: `resources/examplePeople.ts`
|
|
17
|
-
|
|
18
|
-
```typescript
|
|
19
|
-
import { type RequestTargetOrId, tables } from 'harperdb';
|
|
20
|
-
|
|
21
|
-
export interface ExamplePerson {
|
|
22
|
-
id: string;
|
|
23
|
-
name: string;
|
|
24
|
-
tag: string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// Extend the automatically generated table resource
|
|
28
|
-
export class ExamplePeople extends tables.ExamplePeople<ExamplePerson> {
|
|
29
|
-
// Override the custom POST handler
|
|
30
|
-
async post(target: RequestTargetOrId, newRecord: Omit<ExamplePerson, 'id'>) {
|
|
31
|
-
// Add custom validation or transformation logic
|
|
32
|
-
if (!newRecord.name) {
|
|
33
|
-
throw new Error('Name is required');
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
console.log(`Adding new person: ${newRecord.name}`);
|
|
37
|
-
|
|
38
|
-
// Call the super method to perform the actual insertion
|
|
39
|
-
return super.post(target, newRecord);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// Override the custom GET handler
|
|
43
|
-
async get(target: RequestTargetOrId) {
|
|
44
|
-
const record = await super.get(target);
|
|
45
|
-
// Modify the record before returning if necessary
|
|
46
|
-
return record;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
## Why Extend Tables?
|
|
52
|
-
|
|
53
|
-
- **Validation**: Ensure data meets specific criteria before it's saved to the database.
|
|
54
|
-
- **Side Effects**: Send an email, trigger a webhook, or log an event when a record is created or updated.
|
|
55
|
-
- **Data Transformation**: Format or enrich data before it's returned to the client.
|
|
56
|
-
- **Access Control**: Add custom logic to determine if a user has permission to access or modify a specific record.
|
|
57
|
-
|
|
58
|
-
## Important Note
|
|
59
|
-
|
|
60
|
-
When you extend a table resource, Harper uses your custom class for all REST API interactions with that table. Make sure to call `super[method]` if you still want the default behavior to occur after your custom logic.
|
|
61
|
-
|
|
62
|
-
Extended tables do not need to be `@export`ed in their schema .graphql.
|
|
63
|
-
|
|
64
|
-
```graphql
|
|
65
|
-
type ExamplePerson @table {
|
|
66
|
-
id: ID @primaryKey
|
|
67
|
-
name: String
|
|
68
|
-
tag: String @indexed
|
|
69
|
-
}
|
|
70
|
-
```
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
# Handling Binary Data in Harper
|
|
2
|
-
|
|
3
|
-
When working with binary data (such as images or audio files) in Harper, you often receive this data as base64-encoded strings through JSON REST APIs. To store this data efficiently in a `Blob` field, you should convert it to a `Buffer`.
|
|
4
|
-
|
|
5
|
-
## Storing Base64 Strings as Buffers
|
|
6
|
-
|
|
7
|
-
In a custom resource or a table resource override, you can intercept the incoming record and convert base64 strings to buffers before saving them to the database.
|
|
8
|
-
|
|
9
|
-
### Example
|
|
10
|
-
|
|
11
|
-
Suppose you have a table with a `Blob` field named `data`. You can use `Buffer.from(string, 'base64')` to perform the conversion to a buffer, and then use Harper's `createBlob` function to turn that buffer into a blob with a type such as `{ type: 'image/jpeg' }`.
|
|
12
|
-
|
|
13
|
-
```typescript
|
|
14
|
-
import { RequestTargetOrId, Resource } from 'harperdb';
|
|
15
|
-
|
|
16
|
-
export class MyResource extends Resource {
|
|
17
|
-
async post(target: RequestTargetOrId, record: any) {
|
|
18
|
-
if (record.data) {
|
|
19
|
-
// Convert base64-encoded string to a Buffer
|
|
20
|
-
record.data = createBlob(Buffer.from(record.artwork, 'base64'), {
|
|
21
|
-
type: 'image/jpeg',
|
|
22
|
-
});
|
|
23
|
-
}
|
|
24
|
-
// Call the super method to perform the actual storage
|
|
25
|
-
return super.post(target, record);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
## Responding with Binary Data
|
|
31
|
-
|
|
32
|
-
When you want to serve binary data (like an image or an MP3 file) back to the client, you can return a response object from your resource's `get` method. This object should include the appropriate `status`, `headers`, and the binary data itself in the `body`.
|
|
33
|
-
|
|
34
|
-
### Example: Responding with a JPEG File
|
|
35
|
-
|
|
36
|
-
In this example, we retrieve a thumbnail from the database. If it contains binary data in the `data` field, we return it with the `image/jpeg` content type.
|
|
37
|
-
|
|
38
|
-
```typescript
|
|
39
|
-
import { RequestTarget, RequestTargetOrId, Resource } from 'harperdb';
|
|
40
|
-
|
|
41
|
-
export class TrackResource extends Resource {
|
|
42
|
-
async get(target: RequestTargetOrId) {
|
|
43
|
-
const id = (target as RequestTarget)?.id;
|
|
44
|
-
if (!id) {
|
|
45
|
-
return super.get(target);
|
|
46
|
-
}
|
|
47
|
-
const thumbnail = await super.get(target);
|
|
48
|
-
if (thumbnail?.data) {
|
|
49
|
-
return {
|
|
50
|
-
status: 200,
|
|
51
|
-
headers: {
|
|
52
|
-
'Content-Type': 'image/jpeg',
|
|
53
|
-
'Content-Disposition': `inline; filename="${thumbnail.name}.jpg"`,
|
|
54
|
-
},
|
|
55
|
-
body: thumbnail.data,
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
return thumbnail;
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
## Why Use Blobs?
|
|
64
|
-
|
|
65
|
-
- **Efficiency**: `Blob` fields are optimized for storing binary data. Buffers are the standard way to handle binary data in Node.js.
|
|
66
|
-
- **Compatibility**: Many Harper features and external libraries expect binary data to be in `Buffer` or `Uint8Array` format.
|
|
67
|
-
- **Storage**: Storing data as binary is more compact than storing it as a base64-encoded string.
|