@harperfast/template-react-studio 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.
Files changed (42) hide show
  1. package/.agents/skills/harper-best-practices/AGENTS.md +284 -0
  2. package/.agents/skills/harper-best-practices/SKILL.md +90 -0
  3. package/.agents/skills/harper-best-practices/rules/adding-tables-with-schemas.md +40 -0
  4. package/.agents/skills/harper-best-practices/rules/automatic-apis.md +34 -0
  5. package/.agents/skills/harper-best-practices/rules/caching.md +46 -0
  6. package/.agents/skills/harper-best-practices/rules/checking-authentication.md +165 -0
  7. package/.agents/skills/harper-best-practices/rules/creating-harper-apps.md +46 -0
  8. package/.agents/skills/harper-best-practices/rules/custom-resources.md +35 -0
  9. package/.agents/skills/harper-best-practices/rules/defining-relationships.md +33 -0
  10. package/.agents/skills/harper-best-practices/rules/deploying-to-harper-fabric.md +24 -0
  11. package/.agents/skills/harper-best-practices/rules/extending-tables.md +37 -0
  12. package/.agents/skills/harper-best-practices/rules/handling-binary-data.md +43 -0
  13. package/.agents/skills/harper-best-practices/rules/programmatic-table-requests.md +39 -0
  14. package/.agents/skills/harper-best-practices/rules/querying-rest-apis.md +22 -0
  15. package/.agents/skills/harper-best-practices/rules/real-time-apps.md +37 -0
  16. package/.agents/skills/harper-best-practices/rules/serving-web-content.md +34 -0
  17. package/.agents/skills/harper-best-practices/rules/typescript-type-stripping.md +32 -0
  18. package/.agents/skills/harper-best-practices/rules/using-blob-datatype.md +36 -0
  19. package/.agents/skills/harper-best-practices/rules/vector-indexing.md +152 -0
  20. package/README.md +1 -1
  21. package/package.json +1 -1
  22. package/resources/README.md +3 -3
  23. package/schemas/README.md +2 -2
  24. package/skills-lock.json +10 -0
  25. package/AGENTS.md +0 -22
  26. package/skills/adding-tables-with-schemas.md +0 -34
  27. package/skills/automatic-apis.md +0 -53
  28. package/skills/automatic-rest-apis.md +0 -41
  29. package/skills/caching.md +0 -113
  30. package/skills/checking-authentication.md +0 -281
  31. package/skills/custom-resources.md +0 -86
  32. package/skills/defining-relationships.md +0 -71
  33. package/skills/deploying-to-harper-fabric.md +0 -20
  34. package/skills/extending-tables.md +0 -70
  35. package/skills/handling-binary-data.md +0 -67
  36. package/skills/programmatic-table-requests.md +0 -185
  37. package/skills/querying-rest-apis.md +0 -69
  38. package/skills/real-time-apps.md +0 -75
  39. package/skills/serving-web-content.md +0 -82
  40. package/skills/typescript-type-stripping.md +0 -47
  41. package/skills/using-blob-datatype.md +0 -131
  42. package/skills/vector-indexing.md +0 -215
@@ -1,34 +0,0 @@
1
- # Adding Tables to Harper
2
-
3
- To add tables to a Harper database, follow these guidelines:
4
-
5
- 1. **Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.
6
-
7
- 2. **Directives**: All available directives for defining your schema are defined in `node_modules/harperdb/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.
8
-
9
- 3. **Defining Relationships**: You can link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.
10
-
11
- 4. **Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.
12
-
13
- - `GET /{TableName}`: Describes the schema itself.
14
- - `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.
15
- - `GET /{TableName}/{id}`: Retrieves a single record by its ID.
16
- - `POST /{TableName}/`: Creates a new record.
17
- - `PUT /{TableName}/{id}`: Updates an existing record.
18
- - `PATCH /{TableName}/{id}`: Performs a partial update on a record.
19
- - `DELETE /{TableName}/`: Deletes all records or filtered records.
20
- - `DELETE /{TableName}/{id}`: Deletes a single record by its ID.
21
-
22
- ### Example
23
-
24
- In `schemas/ExamplePerson.graphql`:
25
-
26
- ```graphql
27
- type ExamplePerson @table @export {
28
- id: ID @primaryKey
29
- name: String
30
- tag: String @indexed
31
- }
32
- ```
33
-
34
- Tip: if you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.
@@ -1,53 +0,0 @@
1
- # Automatic APIs in Harper
2
-
3
- When you define a GraphQL type with the `@table` and `@export` directives, Harper automatically generates a fully-functional REST API and WebSocket interface for that table. This allows for immediate CRUD (Create, Read, Update, Delete) operations and real-time updates without writing any additional code.
4
-
5
- ## Enabling Automatic APIs
6
-
7
- To enable the automatic REST and WebSocket APIs for a table, ensure your GraphQL schema includes the `@export` directive:
8
-
9
- ```graphql
10
- type MyTable @table @export {
11
- id: ID @primaryKey
12
- # ... other fields
13
- }
14
- ```
15
-
16
- ## Available REST Endpoints
17
-
18
- The following endpoints are automatically created for a table named `TableName` (Note: Paths are **case-sensitive**, so `GET /TableName/` is valid while `GET /tablename/` is not):
19
-
20
- - **Describe Schema**: `GET /{TableName}`
21
- Returns the schema definition and metadata for the table.
22
- - **List Records**: `GET /{TableName}/`
23
- Lists all records in the table. This endpoint supports advanced filtering, sorting, and pagination. For more details, see the [Querying REST APIs](querying-rest-apis.md) skill.
24
- - **Get Single Record**: `GET /{TableName}/{id}`
25
- Retrieves a single record by its primary key (`id`).
26
- - **Create Record**: `POST /{TableName}/`
27
- Creates a new record. The request body should be a JSON object containing the record data.
28
- - **Update Record (Full)**: `PUT /{TableName}/{id}`
29
- Replaces the entire record at the specified `id` with the provided JSON data.
30
- - **Update Record (Partial)**: `PATCH /{TableName}/{id}`
31
- Updates only the specified fields of the record at the given `id`.
32
- - **Delete All/Filtered Records**: `DELETE /{TableName}/`
33
- Deletes all records in the table, or a subset of records if filtering parameters are provided.
34
- - **Delete Single Record**: `DELETE /{TableName}/{id}`
35
- Deletes the record with the specified `id`.
36
-
37
- ## Automatic WebSockets
38
-
39
- In addition to REST endpoints, Harper also stands up WebSocket interfaces for exported tables. When you connect to the table's endpoint via WebSocket, you will automatically receive events whenever updates are made to that table.
40
-
41
- - **WebSocket Endpoint**: `ws://your-harper-instance/{TableName}`
42
-
43
- This is the easiest way to add real-time capabilities to your application. For more complex real-time needs, see the [Real-time Applications](real-time-apps.md) skill.
44
-
45
- ## Filtering and Querying
46
-
47
- The `GET /{TableName}/` and `DELETE /{TableName}/` endpoints can be filtered using query parameters. While basic equality filters are straightforward, Harper supports a rich set of operators, sorting, and pagination.
48
-
49
- For a comprehensive guide on advanced querying, see the [Querying REST APIs](querying-rest-apis.md) skill.
50
-
51
- ## Customizing Resources
52
-
53
- If the automatic APIs don't behave how you need, then you can look to [customize the resources](./custom-resources.md).
@@ -1,41 +0,0 @@
1
- # Automatic REST APIs in HarperDB
2
-
3
- When you define a GraphQL type with the `@table` and `@export` directives, HarperDB automatically generates a fully-functional REST API for that table. This allows for immediate CRUD (Create, Read, Update, Delete) operations without writing any additional code.
4
-
5
- ## Enabling REST APIs
6
-
7
- To enable the automatic REST API for a table, ensure your GraphQL schema includes the `@export` directive:
8
-
9
- ```graphql
10
- type MyTable @table @export {
11
- id: ID @primaryKey
12
- # ... other fields
13
- }
14
- ```
15
-
16
- ## Available Endpoints
17
-
18
- The following endpoints are automatically created for a table named `TableName` (Note: Paths are **case-sensitive**, so `GET /TableName/` is valid while `GET /tablename/` is not):
19
-
20
- - **Describe Schema**: `GET /{TableName}`
21
- Returns the schema definition and metadata for the table.
22
- - **List Records**: `GET /{TableName}/`
23
- Lists all records in the table. This endpoint supports advanced filtering, sorting, and pagination. For more details, see the [Querying REST APIs](querying-rest-apis.md) skill.
24
- - **Get Single Record**: `GET /{TableName}/{id}`
25
- Retrieves a single record by its primary key (`id`).
26
- - **Create Record**: `POST /{TableName}/`
27
- Creates a new record. The request body should be a JSON object containing the record data.
28
- - **Update Record (Full)**: `PUT /{TableName}/{id}`
29
- Replaces the entire record at the specified `id` with the provided JSON data.
30
- - **Update Record (Partial)**: `PATCH /{TableName}/{id}`
31
- Updates only the specified fields of the record at the given `id`.
32
- - **Delete All/Filtered Records**: `DELETE /{TableName}/`
33
- Deletes all records in the table, or a subset of records if filtering parameters are provided.
34
- - **Delete Single Record**: `DELETE /{TableName}/{id}`
35
- Deletes the record with the specified `id`.
36
-
37
- ## Filtering and Querying
38
-
39
- The `GET /{TableName}/` and `DELETE /{TableName}/` endpoints can be filtered using query parameters. While basic equality filters are straightforward, HarperDB supports a rich set of operators, sorting, and pagination.
40
-
41
- For a comprehensive guide on advanced querying, see the [Querying REST APIs](querying-rest-apis.md) skill.
package/skills/caching.md DELETED
@@ -1,113 +0,0 @@
1
- # Harper Caching
2
-
3
- Harper includes integrated support for **caching data from external sources**, enabling high-performance, low-latency cache storage that is fully queryable and interoperable with your applications. With built-in caching capabilities and distributed responsiveness, Harper makes an ideal **data caching server** for both edge and centralized use cases.
4
-
5
- ---
6
-
7
- ## What is Harper Caching?
8
-
9
- Harper caching lets you store **cached content** in standard tables, enabling you to:
10
-
11
- - Expose cached entries as **queryable structured data** (e.g., JSON or CSV)
12
- - Serve data to clients with **flexible formats and custom querying**
13
- - Manage cache control with **timestamps and ETags** for downstream caching layers
14
- - Implement **active or passive caching** patterns depending on your source and invalidation strategy
15
-
16
- ---
17
-
18
- ## Configuring a Cache Table
19
-
20
- Define a cache table in your `schema.graphql`:
21
-
22
- ```graphql
23
- type MyCache @table(expiration: 3600) @export {
24
- id: ID @primaryKey
25
- }
26
- ```
27
-
28
- - `expiration` is defined in seconds
29
- - Expired records are refreshed on access
30
- - Evicted records are removed after expiration
31
-
32
- ---
33
-
34
- ## Connecting an External Source
35
-
36
- Create a resource:
37
-
38
- ```js
39
- import { Resource } from 'harperdb';
40
-
41
- export class ThirdPartyAPI extends Resource {
42
- async get() {
43
- const id = this.getId();
44
- const response = await fetch(`https://api.example.com/items/${id}`);
45
- if (!response.ok) {
46
- throw new Error('Source fetch failed');
47
- }
48
- return await response.json();
49
- }
50
- }
51
- ```
52
-
53
- Attach it to your table:
54
-
55
- ```js
56
- import { tables } from 'harperdb';
57
- import { ThirdPartyAPI } from './ThirdPartyAPI.js';
58
-
59
- const { MyCache } = tables;
60
- MyCache.sourcedFrom(ThirdPartyAPI);
61
- ```
62
-
63
- ---
64
-
65
- ## Cache Behavior
66
-
67
- 1. Fresh data is returned immediately
68
- 2. Missing or stale data triggers a fetch
69
- 3. Concurrent misses are deduplicated
70
-
71
- ---
72
-
73
- ## Active Caching
74
-
75
- Use `subscribe()` to proactively update or invalidate cache entries:
76
-
77
- ```js
78
- class MyAPI extends Resource {
79
- async *subscribe() {
80
- // stream updates
81
- }
82
- }
83
- ```
84
-
85
- See [Real Time Apps](real-time-apps.md) for more details.
86
-
87
- ---
88
-
89
- ## Write-Through Caching
90
-
91
- Propagate updates upstream:
92
-
93
- ```js
94
- class ThirdPartyAPI extends Resource {
95
- async put(data) {
96
- await fetch(`https://some-api.com/${this.getId()}`, {
97
- method: 'PUT',
98
- body: JSON.stringify(data),
99
- });
100
- }
101
- }
102
- ```
103
-
104
- ---
105
-
106
- ## Summary
107
-
108
- Harper Caching allows you to:
109
-
110
- - Cache external APIs efficiently
111
- - Query cached data like native tables
112
- - Prevent cache stampedes
113
- - Build real-time or write-through caches
@@ -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.