@harperfast/template-react-studio 1.5.8 → 1.5.10
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/.agents/skills/harper-best-practices/AGENTS.md +92 -45
- package/.agents/skills/harper-best-practices/SKILL.md +13 -10
- package/.agents/skills/harper-best-practices/rules/adding-tables-with-schemas.md +2 -2
- package/.agents/skills/harper-best-practices/rules/automatic-apis.md +22 -19
- package/.agents/skills/harper-best-practices/rules/caching.md +36 -32
- package/.agents/skills/harper-best-practices/rules/checking-authentication.md +51 -15
- package/.agents/skills/harper-best-practices/rules/creating-a-fabric-account-and-cluster.md +12 -7
- package/.agents/skills/harper-best-practices/rules/creating-harper-apps.md +3 -0
- package/.agents/skills/harper-best-practices/rules/custom-resources.md +3 -1
- package/.agents/skills/harper-best-practices/rules/defining-relationships.md +1 -1
- package/.agents/skills/harper-best-practices/rules/deploying-to-harper-fabric.md +16 -11
- package/.agents/skills/harper-best-practices/rules/extending-tables.md +6 -2
- package/.agents/skills/harper-best-practices/rules/handling-binary-data.md +15 -13
- package/.agents/skills/harper-best-practices/rules/programmatic-table-requests.md +1 -1
- package/.agents/skills/harper-best-practices/rules/querying-rest-apis.md +1 -1
- package/.agents/skills/harper-best-practices/rules/real-time-apps.md +26 -20
- package/.agents/skills/harper-best-practices/rules/serving-web-content.md +34 -3
- package/.agents/skills/harper-best-practices/rules/typescript-type-stripping.md +1 -1
- package/.agents/skills/harper-best-practices/rules/using-blob-datatype.md +1 -1
- package/.agents/skills/harper-best-practices/rules/vector-indexing.md +73 -68
- package/package.json +3 -3
- package/skills-lock.json +1 -1
|
@@ -40,16 +40,19 @@ Guidelines for building scalable, secure, and performant applications on Harper.
|
|
|
40
40
|
Instructions for the agent to follow when adding tables to a Harper database.
|
|
41
41
|
|
|
42
42
|
#### When to Use
|
|
43
|
+
|
|
43
44
|
Use this skill when you need to define new data structures or modify existing ones in a Harper database.
|
|
44
45
|
|
|
45
|
-
####
|
|
46
|
+
#### How It Works
|
|
47
|
+
|
|
46
48
|
1. **Create 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.
|
|
47
49
|
2. **Use 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`.
|
|
48
|
-
3. **Define Relationships**: Link tables together using the `@relationship` directive.
|
|
49
|
-
4. **Enable 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.
|
|
50
|
+
3. **Define Relationships**: Link tables together using the `@relationship` directive.
|
|
51
|
+
4. **Enable 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.
|
|
50
52
|
5. **Consider Table Extensions**: If you are going to extend the table in your resources, then do not `@export` the table from the schema.
|
|
51
53
|
|
|
52
54
|
#### Example
|
|
55
|
+
|
|
53
56
|
```graphql
|
|
54
57
|
type ExamplePerson @table @export {
|
|
55
58
|
id: ID @primaryKey
|
|
@@ -63,29 +66,42 @@ type ExamplePerson @table @export {
|
|
|
63
66
|
Using the `@relationship` directive to link tables.
|
|
64
67
|
|
|
65
68
|
#### When to Use
|
|
69
|
+
|
|
66
70
|
Use this when you have two or more tables that need to be logically linked (e.g., a "Product" table and a "Category" table).
|
|
67
71
|
|
|
68
|
-
####
|
|
69
|
-
|
|
72
|
+
#### How It Works
|
|
73
|
+
|
|
74
|
+
1. **Identify the Relationship Type**: Determine if it's one-to-one, many-to-one, or one-to-many.
|
|
70
75
|
2. **Apply the `@relationship` Directive**: In your GraphQL schema, use the `@relationship` directive on the field that links to another table.
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
76
|
+
- **Many-to-One (Current table holds FK)**: Use `from`.
|
|
77
|
+
```graphql
|
|
78
|
+
type Book @table @export {
|
|
79
|
+
authorId: ID
|
|
80
|
+
author: Author @relationship(from: "authorId")
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
- **One-to-Many (Related table holds FK)**: Use `to` and an array type.
|
|
84
|
+
```graphql
|
|
85
|
+
type Author @table @export {
|
|
86
|
+
books: [Book] @relationship(to: "authorId")
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
3. **Query with Relationships**: Use dot syntax in REST API calls for filtering or the `select()` operator for including related data.
|
|
75
90
|
|
|
76
91
|
#### Example
|
|
92
|
+
|
|
77
93
|
```graphql
|
|
78
94
|
type Product @table @export {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
95
|
+
id: ID @primaryKey
|
|
96
|
+
name: String
|
|
97
|
+
categoryId: ID
|
|
98
|
+
category: Category @relationship(from: "categoryId")
|
|
83
99
|
}
|
|
84
100
|
|
|
85
101
|
type Category @table @export {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
102
|
+
id: ID @primaryKey
|
|
103
|
+
name: String
|
|
104
|
+
products: [Product] @relationship(to: "categoryId")
|
|
89
105
|
}
|
|
90
106
|
```
|
|
91
107
|
|
|
@@ -94,31 +110,36 @@ type Category @table @export {
|
|
|
94
110
|
How to define and use vector indexes for efficient similarity search.
|
|
95
111
|
|
|
96
112
|
#### When to Use
|
|
113
|
+
|
|
97
114
|
Use this when you need to perform similarity searches on high-dimensional data, such as image embeddings, text embeddings, or any other numeric vectors.
|
|
98
115
|
|
|
99
|
-
####
|
|
116
|
+
#### How It Works
|
|
117
|
+
|
|
100
118
|
1. **Define the Vector Field**: In your GraphQL schema, define a field with a list of floats (e.g., `[Float]`).
|
|
101
119
|
2. **Apply the `@indexed` Directive**: Use the `@indexed` directive on the vector field and specify the index type as `vector`.
|
|
102
120
|
3. **Configure the Index (Optional)**: You can provide additional configuration for the vector index, such as the distance metric (e.g., `cosine`, `euclidean`).
|
|
103
121
|
4. **Querying**: Use the `vector` operator in your REST or programmatic requests to perform similarity searches.
|
|
104
122
|
|
|
105
123
|
#### Example
|
|
124
|
+
|
|
106
125
|
```graphql
|
|
107
126
|
type Document @table @export {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
127
|
+
id: ID @primaryKey
|
|
128
|
+
content: String
|
|
129
|
+
embedding: [Float] @indexed(type: "vector", options: { dims: 1536, metric: "cosine" })
|
|
111
130
|
}
|
|
112
131
|
```
|
|
113
132
|
|
|
114
133
|
### 1.4 Using Blobs
|
|
115
134
|
|
|
116
|
-
How to store and retrieve large data in
|
|
135
|
+
How to store and retrieve large data in Harper.
|
|
117
136
|
|
|
118
137
|
#### When to Use
|
|
138
|
+
|
|
119
139
|
Use this when you need to store large, unstructured data such as files, images, or large text documents that exceed the typical size of a standard database field.
|
|
120
140
|
|
|
121
|
-
####
|
|
141
|
+
#### How It Works
|
|
142
|
+
|
|
122
143
|
1. **Define the Blob Field**: Use the `Blob` scalar type in your GraphQL schema.
|
|
123
144
|
2. **Storing Data**: Send the data as a buffer or a stream when creating or updating a record.
|
|
124
145
|
3. **Retrieving Data**: Access the blob field, which will return the data as a stream or buffer.
|
|
@@ -128,10 +149,12 @@ Use this when you need to store large, unstructured data such as files, images,
|
|
|
128
149
|
How to store and serve binary data like images or MP3s.
|
|
129
150
|
|
|
130
151
|
#### When to Use
|
|
152
|
+
|
|
131
153
|
Use this when your application needs to handle binary files, particularly for storage and retrieval.
|
|
132
154
|
|
|
133
|
-
####
|
|
134
|
-
|
|
155
|
+
#### How It Works
|
|
156
|
+
|
|
157
|
+
1. **Use the `Blob` type**: As with general large data, the `Blob` type is best for binary files. Ensure you store and retrieve the appropriate MIME type (e.g., `image/jpeg`, `audio/mpeg`) for the data.
|
|
135
158
|
2. **Streaming**: For large files, use streaming to minimize memory usage during upload and download.
|
|
136
159
|
3. **MIME Types**: Store the MIME type alongside the binary data to ensure it is served correctly by your application logic.
|
|
137
160
|
|
|
@@ -146,6 +169,7 @@ Use this when your application needs to handle binary files, particularly for st
|
|
|
146
169
|
Details on the CRUD endpoints automatically generated for exported tables.
|
|
147
170
|
|
|
148
171
|
#### Endpoints
|
|
172
|
+
|
|
149
173
|
- `GET /{TableName}`: Describes the schema.
|
|
150
174
|
- `GET /{TableName}/`: Lists records (supports filtering/sorting).
|
|
151
175
|
- `GET /{TableName}/{id}`: Gets a record by ID.
|
|
@@ -160,6 +184,7 @@ Details on the CRUD endpoints automatically generated for exported tables.
|
|
|
160
184
|
How to use filters, operators, sorting, and pagination in REST requests.
|
|
161
185
|
|
|
162
186
|
#### Query Parameters
|
|
187
|
+
|
|
163
188
|
- `limit`: Number of records to return.
|
|
164
189
|
- `offset`: Number of records to skip.
|
|
165
190
|
- `sort`: Field to sort by.
|
|
@@ -171,10 +196,12 @@ How to use filters, operators, sorting, and pagination in REST requests.
|
|
|
171
196
|
Implementing WebSockets and Pub/Sub for live data updates.
|
|
172
197
|
|
|
173
198
|
#### When to Use
|
|
199
|
+
|
|
174
200
|
Use this for applications that require live updates, such as chat apps, live dashboards, or collaborative tools.
|
|
175
201
|
|
|
176
|
-
####
|
|
177
|
-
|
|
202
|
+
#### How It Works
|
|
203
|
+
|
|
204
|
+
1. **WebSocket Connection**: Connect to the Harper WebSocket endpoint. Use `wss://` for secure connections over HTTPS, or `ws://` for local development.
|
|
178
205
|
2. **Subscribing**: Subscribe to table updates or specific records.
|
|
179
206
|
3. **Pub/Sub**: Use the internal bus to publish and subscribe to custom events.
|
|
180
207
|
|
|
@@ -183,9 +210,11 @@ Use this for applications that require live updates, such as chat apps, live das
|
|
|
183
210
|
How to use sessions to verify user identity and roles.
|
|
184
211
|
|
|
185
212
|
#### When to Use
|
|
213
|
+
|
|
186
214
|
Use this to secure your application by ensuring that only authorized users can access certain resources or perform specific actions.
|
|
187
215
|
|
|
188
|
-
####
|
|
216
|
+
#### How It Works
|
|
217
|
+
|
|
189
218
|
1. **Session Handling**: Access the session object from the request context.
|
|
190
219
|
2. **Identity Verification**: Check for the presence of a user ID or token.
|
|
191
220
|
3. **Role Checks**: Verify if the user has the required roles for the action.
|
|
@@ -200,7 +229,8 @@ Use this to secure your application by ensuring that only authorized users can a
|
|
|
200
229
|
|
|
201
230
|
How to define custom REST endpoints using JavaScript or TypeScript.
|
|
202
231
|
|
|
203
|
-
####
|
|
232
|
+
#### How It Works
|
|
233
|
+
|
|
204
234
|
1. **Create Resource File**: Define your logic in a JS or TS file.
|
|
205
235
|
2. **Export Handlers**: Export functions like `GET`, `POST`, etc.
|
|
206
236
|
3. **Registration**: Ensure the resource is correctly registered in your application configuration.
|
|
@@ -209,7 +239,8 @@ How to define custom REST endpoints using JavaScript or TypeScript.
|
|
|
209
239
|
|
|
210
240
|
Adding custom logic to automatically generated table resources.
|
|
211
241
|
|
|
212
|
-
####
|
|
242
|
+
#### How It Works
|
|
243
|
+
|
|
213
244
|
1. **Define Extension**: Create a resource file that targets an existing table.
|
|
214
245
|
2. **Intercept Requests**: Use handlers to add custom validation or data transformation.
|
|
215
246
|
3. **No `@export`**: If extending, remember not to `@export` the table in the schema.
|
|
@@ -219,6 +250,7 @@ Adding custom logic to automatically generated table resources.
|
|
|
219
250
|
How to use filters, operators, sorting, and pagination in programmatic table requests.
|
|
220
251
|
|
|
221
252
|
#### Usage
|
|
253
|
+
|
|
222
254
|
When writing custom resources, use the internal API to query tables with full support for advanced filtering and sorting.
|
|
223
255
|
|
|
224
256
|
### 3.4 TypeScript Type Stripping
|
|
@@ -226,6 +258,7 @@ When writing custom resources, use the internal API to query tables with full su
|
|
|
226
258
|
Using TypeScript directly without build tools via Node.js Type Stripping.
|
|
227
259
|
|
|
228
260
|
#### Configuration
|
|
261
|
+
|
|
229
262
|
Harper supports native TypeScript type stripping, allowing you to run `.ts` files directly. Ensure your environment is configured to take advantage of this for faster development cycles.
|
|
230
263
|
|
|
231
264
|
### 3.5 Caching
|
|
@@ -233,6 +266,7 @@ Harper supports native TypeScript type stripping, allowing you to run `.ts` file
|
|
|
233
266
|
How caching is defined and implemented in Harper applications.
|
|
234
267
|
|
|
235
268
|
#### Strategies
|
|
269
|
+
|
|
236
270
|
- **In-memory**: For fast access to frequently used data.
|
|
237
271
|
- **Distributed**: For scaling across multiple nodes in Harper Fabric.
|
|
238
272
|
|
|
@@ -247,22 +281,27 @@ How caching is defined and implemented in Harper applications.
|
|
|
247
281
|
The fastest way to start a new Harper project is using the `create-harper` CLI tool. This command initializes a project with a standard folder structure, essential configuration files, and basic schema definitions.
|
|
248
282
|
|
|
249
283
|
#### When to Use
|
|
284
|
+
|
|
250
285
|
Use this command when starting a new Harper application or adding a new Harper microservice to an existing architecture.
|
|
251
286
|
|
|
252
287
|
#### Commands
|
|
288
|
+
|
|
253
289
|
Initialize a project using your preferred package manager:
|
|
254
290
|
|
|
255
291
|
**NPM**
|
|
292
|
+
|
|
256
293
|
```bash
|
|
257
294
|
npm create harper@latest
|
|
258
295
|
```
|
|
259
296
|
|
|
260
297
|
**PNPM**
|
|
298
|
+
|
|
261
299
|
```bash
|
|
262
300
|
pnpm create harper@latest
|
|
263
301
|
```
|
|
264
302
|
|
|
265
303
|
**Bun**
|
|
304
|
+
|
|
266
305
|
```bash
|
|
267
306
|
bun create harper@latest
|
|
268
307
|
```
|
|
@@ -271,7 +310,7 @@ bun create harper@latest
|
|
|
271
310
|
|
|
272
311
|
Follow these steps to set up your Harper Fabric environment for deployment.
|
|
273
312
|
|
|
274
|
-
####
|
|
313
|
+
#### How It Works
|
|
275
314
|
|
|
276
315
|
1. **Sign Up/In**: Go to [https://fabric.harper.fast/](https://fabric.harper.fast/) and sign up or sign in.
|
|
277
316
|
2. **Create an Organization**: Create an organization (org) to manage your projects.
|
|
@@ -290,11 +329,13 @@ Follow these steps to set up your Harper Fabric environment for deployment.
|
|
|
290
329
|
Globally scaling your Harper application.
|
|
291
330
|
|
|
292
331
|
#### Benefits
|
|
332
|
+
|
|
293
333
|
- **Global Distribution**: Low latency for users everywhere.
|
|
294
334
|
- **Automatic Sync**: Data is synced across the fabric automatically.
|
|
295
335
|
- **Free Tier**: Start for free and scale as you grow.
|
|
296
336
|
|
|
297
|
-
####
|
|
337
|
+
#### How It Works
|
|
338
|
+
|
|
298
339
|
1. **Sign up**: Follow the [Creating a Fabric Account and Cluster](#42-creating-a-fabric-account-and-cluster) steps to create a Harper Fabric account, organization, and cluster.
|
|
299
340
|
2. **Configure Environment**: Add your cluster credentials and cluster application URL to `.env`:
|
|
300
341
|
```bash
|
|
@@ -309,33 +350,33 @@ Globally scaling your Harper application.
|
|
|
309
350
|
|
|
310
351
|
If your application was not created with `npm create harper`, you'll need to manually configure the deployment scripts and CI/CD workflow.
|
|
311
352
|
|
|
312
|
-
|
|
353
|
+
#### 1. Update `package.json`
|
|
313
354
|
|
|
314
355
|
Add the following scripts and dependencies to your `package.json`:
|
|
315
356
|
|
|
316
357
|
```json
|
|
317
358
|
{
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
359
|
+
"scripts": {
|
|
360
|
+
"deploy": "dotenv -- npm run deploy:component",
|
|
361
|
+
"deploy:component": "harperdb deploy_component . restart=rolling replicated=true"
|
|
362
|
+
},
|
|
363
|
+
"devDependencies": {
|
|
364
|
+
"dotenv-cli": "^11.0.0",
|
|
365
|
+
"harperdb": "^4.7.20"
|
|
366
|
+
}
|
|
326
367
|
}
|
|
327
368
|
```
|
|
328
369
|
|
|
329
|
-
|
|
370
|
+
#### Why split the scripts?
|
|
330
371
|
|
|
331
|
-
The `deploy` script is separated from `deploy:component` to ensure environment variables from your `.env` file are properly loaded and passed to the Harper CLI.
|
|
372
|
+
The `deploy` script is separated from `deploy:component` to ensure environment variables from your `.env` file are properly loaded and passed to the Harper CLI.
|
|
332
373
|
|
|
333
374
|
- `deploy`: Uses `dotenv-cli` to load environment variables (like `CLI_TARGET`, `CLI_TARGET_USERNAME`, and `CLI_TARGET_PASSWORD`) before executing the next command.
|
|
334
|
-
- `deploy:component`: The actual command that performs the deployment.
|
|
375
|
+
- `deploy:component`: The actual command that performs the deployment.
|
|
335
376
|
|
|
336
377
|
By using `dotenv -- npm run deploy:component`, the environment variables are correctly set in the shell session before `harperdb deploy_component` is called, allowing it to authenticate with your cluster.
|
|
337
378
|
|
|
338
|
-
|
|
379
|
+
#### 2. Configure GitHub Actions
|
|
339
380
|
|
|
340
381
|
Create a `.github/workflows/deploy.yaml` file with the following content:
|
|
341
382
|
|
|
@@ -368,9 +409,14 @@ jobs:
|
|
|
368
409
|
run: npm run lint
|
|
369
410
|
- name: Deploy
|
|
370
411
|
run: npm run deploy
|
|
412
|
+
env:
|
|
413
|
+
CLI_TARGET: ${{ secrets.CLI_TARGET }}
|
|
414
|
+
CLI_TARGET_USERNAME: ${{ secrets.CLI_TARGET_USERNAME }}
|
|
415
|
+
CLI_TARGET_PASSWORD: ${{ secrets.CLI_TARGET_PASSWORD }}
|
|
371
416
|
```
|
|
372
417
|
|
|
373
418
|
Be sure to set the following repository secrets in your GitHub repository:
|
|
419
|
+
|
|
374
420
|
- `CLI_TARGET`
|
|
375
421
|
- `CLI_TARGET_USERNAME`
|
|
376
422
|
- `CLI_TARGET_PASSWORD`
|
|
@@ -380,5 +426,6 @@ Be sure to set the following repository secrets in your GitHub repository:
|
|
|
380
426
|
Two ways to serve web content from a Harper application.
|
|
381
427
|
|
|
382
428
|
#### Methods
|
|
383
|
-
|
|
429
|
+
|
|
430
|
+
1. **Static Serving**: Serve HTML, CSS, and JS files directly. If using the Vite plugin for development, ensure Harper is running (e.g., `harperdb run .`) to allow for Hot Module Replacement (HMR).
|
|
384
431
|
2. **Dynamic Rendering**: Use custom resources to render content on the fly.
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: harper-best-practices
|
|
3
|
-
description:
|
|
4
|
-
Best practices for building Harper applications, covering schema definition,
|
|
3
|
+
description: Best practices for building Harper applications, covering schema definition,
|
|
5
4
|
automatic APIs, authentication, custom resources, and data handling.
|
|
6
5
|
Triggers on tasks involving Harper database design, API implementation,
|
|
7
6
|
and deployment.
|
|
@@ -26,7 +25,7 @@ Reference these guidelines when:
|
|
|
26
25
|
- Optimizing data storage and retrieval (Blobs, Vector Indexing)
|
|
27
26
|
- Deploying applications to Harper Fabric
|
|
28
27
|
|
|
29
|
-
##
|
|
28
|
+
## How It Works
|
|
30
29
|
|
|
31
30
|
1. Review the requirements for the task (schema design, API needs, or infrastructure setup).
|
|
32
31
|
2. Consult the relevant category under "Rule Categories by Priority" to understand the impact of your decisions.
|
|
@@ -35,14 +34,18 @@ Reference these guidelines when:
|
|
|
35
34
|
5. If you're extending functionality, consult the `logic-` and `api-` rules.
|
|
36
35
|
6. Validate your implementation against the `ops-` rules before deployment.
|
|
37
36
|
|
|
37
|
+
## Examples
|
|
38
|
+
|
|
39
|
+
See the concrete examples embedded in each rule subsection below (GraphQL schemas, REST query patterns, and deployment workflow snippets).
|
|
40
|
+
|
|
38
41
|
## Rule Categories by Priority
|
|
39
42
|
|
|
40
|
-
| Priority | Category
|
|
41
|
-
| -------- |
|
|
42
|
-
| 1 | Schema & Data Design
|
|
43
|
-
| 2 | API & Communication
|
|
44
|
-
| 3 | Logic & Extension
|
|
45
|
-
| 4 | Infrastructure & Ops
|
|
43
|
+
| Priority | Category | Impact | Prefix |
|
|
44
|
+
| -------- | -------------------- | ------ | --------- |
|
|
45
|
+
| 1 | Schema & Data Design | HIGH | `schema-` |
|
|
46
|
+
| 2 | API & Communication | HIGH | `api-` |
|
|
47
|
+
| 3 | Logic & Extension | MEDIUM | `logic-` |
|
|
48
|
+
| 4 | Infrastructure & Ops | MEDIUM | `ops-` |
|
|
46
49
|
|
|
47
50
|
## Quick Reference
|
|
48
51
|
|
|
@@ -58,7 +61,7 @@ Reference these guidelines when:
|
|
|
58
61
|
|
|
59
62
|
- `automatic-apis` - Leverage automatically generated CRUD endpoints
|
|
60
63
|
- `querying-rest-apis` - Filters, sorting, and pagination in REST requests
|
|
61
|
-
- `real-time-apps` - WebSockets and Pub/Sub for
|
|
64
|
+
- `real-time-apps` - WebSockets and Pub/Sub for Real-Time Apps
|
|
62
65
|
- `checking-authentication` - Secure apps with session-based identity verification
|
|
63
66
|
|
|
64
67
|
### 3. Logic & Extension (MEDIUM)
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when adding tables to a Harper database.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to define new data structures or modify existing ones in a Harper database.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Create 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.
|
|
17
17
|
2. **Use 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`.
|
|
@@ -27,7 +27,7 @@ Use this skill when you need to define new data structures or modify existing on
|
|
|
27
27
|
- `DELETE /{TableName}/{id}`: Deletes a single record by its ID.
|
|
28
28
|
5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
## Examples
|
|
31
31
|
|
|
32
32
|
In a hypothetical `schemas/ExamplePerson.graphql`:
|
|
33
33
|
|
|
@@ -11,24 +11,27 @@ Instructions for the agent to follow when utilizing Harper's automatic APIs.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you want to interact with Harper tables via REST or WebSockets without writing custom resource logic. This is ideal for basic CRUD operations and real-time updates.
|
|
13
13
|
|
|
14
|
-
##
|
|
15
|
-
|
|
16
|
-
1. **Enable Automatic APIs**: Ensure your GraphQL schema includes the `@export` directive for the table
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
id: ID @primaryKey
|
|
20
|
-
# ... other fields
|
|
21
|
-
}
|
|
22
|
-
```
|
|
23
|
-
2. **Access REST Endpoints**: Use the following endpoints for a table named `TableName` (Note: Paths are **case-sensitive**):
|
|
24
|
-
- **Describe Schema**: `GET /{TableName}`
|
|
25
|
-
- **List Records**: `GET /{TableName}/` (Supports filtering, sorting, and pagination. See [Querying REST APIs](querying-rest-apis.md)).
|
|
26
|
-
- **Get Single Record**: `GET /{TableName}/{id}`
|
|
27
|
-
- **Create Record**: `POST /{TableName}/` (Request body should be JSON).
|
|
28
|
-
- **Update Record (Full)**: `PUT /{TableName}/{id}`
|
|
29
|
-
- **Update Record (Partial)**: `PATCH /{TableName}/{id}`
|
|
30
|
-
- **Delete All/Filtered Records**: `DELETE /{TableName}/`
|
|
31
|
-
- **Delete Single Record**: `DELETE /{TableName}/{id}`
|
|
32
|
-
3. **Use Automatic WebSockets**: Connect to `ws://your-harper-instance/{TableName}` to receive events whenever updates are made to that table. This is the easiest way to add real-time capabilities. For more complex needs, see [Real-time Applications](real-time-apps.md).
|
|
14
|
+
## How It Works
|
|
15
|
+
|
|
16
|
+
1. **Enable Automatic APIs**: Ensure your GraphQL schema includes the `@export` directive for the table.
|
|
17
|
+
2. **Access REST Endpoints**: Use the standard endpoints for your table (Note: Paths are case-sensitive).
|
|
18
|
+
3. **Use Automatic WebSockets**: Connect to `wss://your-harper-instance/{TableName}` to receive events whenever updates are made to that table. This is the easiest way to add real-time capabilities. (Use `ws://` for local development without SSL). For more complex needs, see [Real-time Apps](real-time-apps.md).
|
|
33
19
|
4. **Apply Filtering and Querying**: Use query parameters with `GET /{TableName}/` and `DELETE /{TableName}/`. See the [Querying REST APIs](querying-rest-apis.md) skill for advanced details.
|
|
34
20
|
5. **Customize if Needed**: If the automatic APIs don't meet your requirements, [customize the resources](./custom-resources.md).
|
|
21
|
+
|
|
22
|
+
## Examples
|
|
23
|
+
|
|
24
|
+
### Schema Configuration
|
|
25
|
+
|
|
26
|
+
```graphql
|
|
27
|
+
type MyTable @table @export {
|
|
28
|
+
id: ID @primaryKey
|
|
29
|
+
name: String
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Common REST Operations
|
|
34
|
+
|
|
35
|
+
- **List Records**: `GET /MyTable/`
|
|
36
|
+
- **Create Record**: `POST /MyTable/`
|
|
37
|
+
- **Update Record**: `PATCH /MyTable/{id}`
|
|
@@ -11,36 +11,40 @@ Instructions for the agent to follow when implementing caching in Harper.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need high-performance, low-latency storage for data from external sources. It's ideal for reducing API calls to third-party services, preventing cache stampedes, and making external data queryable as if it were native Harper tables.
|
|
13
13
|
|
|
14
|
-
##
|
|
15
|
-
|
|
16
|
-
1. **Configure a Cache Table**: Define a table in your `schema.graphql` with an `expiration` (in seconds)
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
```
|
|
22
|
-
2. **Define an External Source**: Create a Resource class that fetches the data:
|
|
23
|
-
```js
|
|
24
|
-
import { Resource } from 'harperdb';
|
|
25
|
-
|
|
26
|
-
export class ThirdPartyAPI extends Resource {
|
|
27
|
-
async get() {
|
|
28
|
-
const id = this.getId();
|
|
29
|
-
const response = await fetch(`https://api.example.com/items/${id}`);
|
|
30
|
-
if (!response.ok) {
|
|
31
|
-
throw new Error('Source fetch failed');
|
|
32
|
-
}
|
|
33
|
-
return await response.json();
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
```
|
|
37
|
-
3. **Attach Source to Table**: Use `sourcedFrom` to link your resource to the table:
|
|
38
|
-
```js
|
|
39
|
-
import { tables } from 'harperdb';
|
|
40
|
-
import { ThirdPartyAPI } from './ThirdPartyAPI.js';
|
|
41
|
-
|
|
42
|
-
const { MyCache } = tables;
|
|
43
|
-
MyCache.sourcedFrom(ThirdPartyAPI);
|
|
44
|
-
```
|
|
45
|
-
4. **Implement Active Caching (Optional)**: Use `subscribe()` for proactive updates. See [Real Time Apps](real-time-apps.md).
|
|
14
|
+
## How It Works
|
|
15
|
+
|
|
16
|
+
1. **Configure a Cache Table**: Define a table in your `schema.graphql` with an `expiration` (in seconds).
|
|
17
|
+
2. **Define an External Source**: Create a Resource class that fetches the data from your source.
|
|
18
|
+
3. **Attach Source to Table**: Use `sourcedFrom` to link your resource to the table.
|
|
19
|
+
4. **Implement Active Caching (Optional)**: Use `subscribe()` for proactive updates. See [Real-Time Apps](real-time-apps.md).
|
|
46
20
|
5. **Implement Write-Through Caching (Optional)**: Define `put` or `post` in your resource to propagate updates upstream.
|
|
21
|
+
|
|
22
|
+
## Examples
|
|
23
|
+
|
|
24
|
+
### Schema Configuration
|
|
25
|
+
|
|
26
|
+
```graphql
|
|
27
|
+
type MyCache @table(expiration: 3600) @export {
|
|
28
|
+
id: ID @primaryKey
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Resource Implementation
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
import { Resource, tables } from 'harperdb';
|
|
36
|
+
|
|
37
|
+
export class ThirdPartyAPI extends Resource {
|
|
38
|
+
async get() {
|
|
39
|
+
const id = this.getId();
|
|
40
|
+
const response = await fetch(`https://api.example.com/items/${id}`);
|
|
41
|
+
if (!response.ok) {
|
|
42
|
+
throw new Error('Source fetch failed');
|
|
43
|
+
}
|
|
44
|
+
return await response.json();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Attach source to table
|
|
49
|
+
tables.MyCache.sourcedFrom(ThirdPartyAPI);
|
|
50
|
+
```
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when handling authentication and sessions.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to implement sign-in/sign-out functionality, protect specific resource endpoints, or identify the currently logged-in user in a Harper application.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Configure Harper for Sessions**: Ensure `harperdb-config.yaml` has sessions enabled and local auto-authorization disabled for testing:
|
|
17
17
|
```yaml
|
|
@@ -20,19 +20,19 @@ Use this skill when you need to implement sign-in/sign-out functionality, protec
|
|
|
20
20
|
enableSessions: true
|
|
21
21
|
```
|
|
22
22
|
2. **Implement Sign In**: Use `this.getContext().login(username, password)` to create a session:
|
|
23
|
-
```
|
|
23
|
+
```typescript
|
|
24
24
|
async post(_target, data) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
25
|
+
const context = this.getContext();
|
|
26
|
+
try {
|
|
27
|
+
await context.login(data.username, data.password);
|
|
28
|
+
} catch {
|
|
29
|
+
return new Response('Invalid credentials', { status: 403 });
|
|
30
|
+
}
|
|
31
|
+
return new Response('Logged in', { status: 200 });
|
|
32
32
|
}
|
|
33
33
|
```
|
|
34
34
|
3. **Identify Current User**: Use `this.getCurrentUser()` to access session data:
|
|
35
|
-
```
|
|
35
|
+
```typescript
|
|
36
36
|
async get() {
|
|
37
37
|
const user = this.getCurrentUser?.();
|
|
38
38
|
if (!user) return new Response(null, { status: 401 });
|
|
@@ -40,7 +40,7 @@ Use this skill when you need to implement sign-in/sign-out functionality, protec
|
|
|
40
40
|
}
|
|
41
41
|
```
|
|
42
42
|
4. **Implement Sign Out**: Use `this.getContext().logout()` or delete the session from context:
|
|
43
|
-
```
|
|
43
|
+
```typescript
|
|
44
44
|
async post() {
|
|
45
45
|
const context = this.getContext();
|
|
46
46
|
await context.session?.delete?.(context.session.id);
|
|
@@ -49,6 +49,42 @@ Use this skill when you need to implement sign-in/sign-out functionality, protec
|
|
|
49
49
|
```
|
|
50
50
|
5. **Protect Routes**: In your Resource, use `allowRead()`, `allowUpdate()`, etc., to enforce authorization logic based on `this.getCurrentUser()`. For privileged actions, verify `user.role.permission.super_user`.
|
|
51
51
|
|
|
52
|
+
## Examples
|
|
53
|
+
|
|
54
|
+
### Sign In Implementation
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
async post(_target, data) {
|
|
58
|
+
const context = this.getContext();
|
|
59
|
+
try {
|
|
60
|
+
await context.login(data.username, data.password);
|
|
61
|
+
} catch {
|
|
62
|
+
return new Response('Invalid credentials', { status: 403 });
|
|
63
|
+
}
|
|
64
|
+
return new Response('Logged in', { status: 200 });
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Identify Current User
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
async get() {
|
|
72
|
+
const user = this.getCurrentUser?.();
|
|
73
|
+
if (!user) return new Response(null, { status: 401 });
|
|
74
|
+
return { username: user.username, role: user.role };
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Sign Out Implementation
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
async post() {
|
|
82
|
+
const context = this.getContext();
|
|
83
|
+
await context.session?.delete?.(context.session.id);
|
|
84
|
+
return new Response('Logged out', { status: 200 });
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
52
88
|
## Status code conventions used here
|
|
53
89
|
|
|
54
90
|
- 200: Successful operation. For `GET /me`, a `200` with empty body means “not signed in”.
|
|
@@ -77,9 +113,9 @@ This project includes two Resource patterns for that flow:
|
|
|
77
113
|
- with an existing Authorization token (either Basic Auth or a JWT) and you want to issue new tokens, or
|
|
78
114
|
- from an explicit `{ username, password }` payload (useful for direct “login” from a CLI/mobile client).
|
|
79
115
|
|
|
80
|
-
```
|
|
116
|
+
```javascript
|
|
81
117
|
export class IssueTokens extends Resource {
|
|
82
|
-
static loadAsInstance = false;
|
|
118
|
+
static loadAsInstance = false;
|
|
83
119
|
|
|
84
120
|
async get(target) {
|
|
85
121
|
const { refresh_token: refreshToken, operation_token: jwt } =
|
|
@@ -118,9 +154,9 @@ static loadAsInstance = false;
|
|
|
118
154
|
|
|
119
155
|
**Description / use case:** When the JWT expires, the client uses the refresh token to get a new JWT without re-supplying username/password.
|
|
120
156
|
|
|
121
|
-
```
|
|
157
|
+
```javascript
|
|
122
158
|
export class RefreshJWT extends Resource {
|
|
123
|
-
static loadAsInstance = false;
|
|
159
|
+
static loadAsInstance = false;
|
|
124
160
|
|
|
125
161
|
async post(target, data) {
|
|
126
162
|
if (!data.refreshToken) {
|
|
@@ -7,17 +7,22 @@ description: How to create a Harper Fabric account, organization, and cluster.
|
|
|
7
7
|
|
|
8
8
|
Follow these steps to set up your Harper Fabric environment for deployment.
|
|
9
9
|
|
|
10
|
-
##
|
|
10
|
+
## How It Works
|
|
11
11
|
|
|
12
12
|
1. **Sign Up/In**: Go to [https://fabric.harper.fast/](https://fabric.harper.fast/) and sign up or sign in.
|
|
13
13
|
2. **Create an Organization**: Create an organization (org) to manage your projects.
|
|
14
14
|
3. **Create a Cluster**: Create a new cluster. This can be on the free tier, no credit card required.
|
|
15
15
|
4. **Set Credentials**: During setup, set the cluster username and password to finish configuring it.
|
|
16
16
|
5. **Get Application URL**: Navigate to the **Config** tab and copy the **Application URL**.
|
|
17
|
-
6. **Configure Environment**: Update your `.env` file or GitHub Actions secrets with
|
|
18
|
-
```bash
|
|
19
|
-
CLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'
|
|
20
|
-
CLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'
|
|
21
|
-
CLI_TARGET='YOUR_CLUSTER_URL'
|
|
22
|
-
```
|
|
17
|
+
6. **Configure Environment**: Update your `.env` file or GitHub Actions secrets with cluster-specific credentials.
|
|
23
18
|
7. **Next Steps**: See the [deploying-to-harper-fabric](deploying-to-harper-fabric.md) rule for detailed instructions on deploying your application successfully.
|
|
19
|
+
|
|
20
|
+
## Examples
|
|
21
|
+
|
|
22
|
+
### Environment Configuration
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
CLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'
|
|
26
|
+
CLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'
|
|
27
|
+
CLI_TARGET='YOUR_CLUSTER_URL'
|
|
28
|
+
```
|
|
@@ -16,16 +16,19 @@ Use this command when starting a new Harper application or adding a new Harper m
|
|
|
16
16
|
Initialize a project using your preferred package manager:
|
|
17
17
|
|
|
18
18
|
### NPM
|
|
19
|
+
|
|
19
20
|
```bash
|
|
20
21
|
npm create harper@latest
|
|
21
22
|
```
|
|
22
23
|
|
|
23
24
|
### PNPM
|
|
25
|
+
|
|
24
26
|
```bash
|
|
25
27
|
pnpm create harper@latest
|
|
26
28
|
```
|
|
27
29
|
|
|
28
30
|
### Bun
|
|
31
|
+
|
|
29
32
|
```bash
|
|
30
33
|
bun create harper@latest
|
|
31
34
|
```
|
|
@@ -11,11 +11,12 @@ Instructions for the agent to follow when creating custom resources in Harper.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when the automatic CRUD operations provided by `@table @export` are insufficient, and you need custom logic, third-party API integration, or specialized data handling for your REST endpoints.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Check if a Custom Resource is Necessary**: Verify if [Automatic APIs](./automatic-apis.md) or [Extending Tables](./extending-tables.md) can satisfy the requirement first.
|
|
17
17
|
2. **Create the Resource File**: Create a `.ts` or `.js` file in the directory specified by `jsResource` in `config.yaml` (typically `resources/`).
|
|
18
18
|
3. **Define the Resource Class**: Export a class extending `Resource` from `harperdb`:
|
|
19
|
+
|
|
19
20
|
```typescript
|
|
20
21
|
import { type RequestTargetOrId, Resource } from 'harperdb';
|
|
21
22
|
|
|
@@ -25,6 +26,7 @@ Use this skill when the automatic CRUD operations provided by `@table @export` a
|
|
|
25
26
|
}
|
|
26
27
|
}
|
|
27
28
|
```
|
|
29
|
+
|
|
28
30
|
4. **Implement HTTP Methods**: Add methods like `get`, `post`, `put`, `patch`, or `delete` to handle corresponding requests. Note that paths are **case-sensitive** and match the class name.
|
|
29
31
|
5. **Access Tables (Optional)**: Import and use the `tables` object to interact with your data:
|
|
30
32
|
```typescript
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when defining relationships between Harper
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to link data across different tables, enabling automatic joins and efficient related-data fetching via REST APIs.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Identify the Relationship Type**: Determine if it's one-to-one, many-to-one, or one-to-many.
|
|
17
17
|
2. **Use the `@relationship` Directive**: Apply it to a field in your GraphQL schema.
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when deploying to Harper Fabric.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you are ready to move your Harper application from local development to a cloud-hosted environment.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Sign up**: Follow the [creating-a-fabric-account-and-cluster](creating-a-fabric-account-and-cluster.md) rule to create a Harper Fabric account, organization, and cluster.
|
|
17
17
|
2. **Configure Environment**: Add your cluster credentials and cluster application URL to `.env`:
|
|
@@ -33,23 +33,23 @@ Add the following scripts and dependencies to your `package.json`:
|
|
|
33
33
|
|
|
34
34
|
```json
|
|
35
35
|
{
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
36
|
+
"scripts": {
|
|
37
|
+
"deploy": "dotenv -- npm run deploy:component",
|
|
38
|
+
"deploy:component": "harperdb deploy_component . restart=rolling replicated=true"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"dotenv-cli": "^11.0.0",
|
|
42
|
+
"harperdb": "^4.7.20"
|
|
43
|
+
}
|
|
44
44
|
}
|
|
45
45
|
```
|
|
46
46
|
|
|
47
47
|
#### Why split the scripts?
|
|
48
48
|
|
|
49
|
-
The `deploy` script is separated from `deploy:component` to ensure environment variables from your `.env` file are properly loaded and passed to the Harper CLI.
|
|
49
|
+
The `deploy` script is separated from `deploy:component` to ensure environment variables from your `.env` file are properly loaded and passed to the Harper CLI.
|
|
50
50
|
|
|
51
51
|
- `deploy`: Uses `dotenv-cli` to load environment variables (like `CLI_TARGET`, `CLI_TARGET_USERNAME`, and `CLI_TARGET_PASSWORD`) before executing the next command.
|
|
52
|
-
- `deploy:component`: The actual command that performs the deployment.
|
|
52
|
+
- `deploy:component`: The actual command that performs the deployment.
|
|
53
53
|
|
|
54
54
|
By using `dotenv -- npm run deploy:component`, the environment variables are correctly set in the shell session before `harperdb deploy_component` is called, allowing it to authenticate with your cluster.
|
|
55
55
|
|
|
@@ -89,9 +89,14 @@ jobs:
|
|
|
89
89
|
run: npm run lint
|
|
90
90
|
- name: Deploy
|
|
91
91
|
run: npm run deploy
|
|
92
|
+
env:
|
|
93
|
+
CLI_TARGET: ${{ secrets.CLI_TARGET }}
|
|
94
|
+
CLI_TARGET_USERNAME: ${{ secrets.CLI_TARGET_USERNAME }}
|
|
95
|
+
CLI_TARGET_PASSWORD: ${{ secrets.CLI_TARGET_PASSWORD }}
|
|
92
96
|
```
|
|
93
97
|
|
|
94
98
|
Be sure to set the following repository secrets in your GitHub repository's /settings/secrets/actions:
|
|
99
|
+
|
|
95
100
|
- `CLI_TARGET`
|
|
96
101
|
- `CLI_TARGET_USERNAME`
|
|
97
102
|
- `CLI_TARGET_PASSWORD`
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when extending table resources in Harper.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to add custom validation, side effects (like webhooks), data transformation, or custom access control to the standard CRUD operations of a Harper table.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Define the Table in GraphQL**: In your `.graphql` schema, define the table using the `@table` directive. **Do not** use `@export` if you plan to extend it.
|
|
17
17
|
```graphql
|
|
@@ -22,16 +22,20 @@ Use this skill when you need to add custom validation, side effects (like webhoo
|
|
|
22
22
|
```
|
|
23
23
|
2. **Create the Extension File**: Create a `.ts` file in your `resources/` directory.
|
|
24
24
|
3. **Extend the Table Resource**: Export a class that extends `tables.YourTableName`:
|
|
25
|
+
|
|
25
26
|
```typescript
|
|
26
27
|
import { type RequestTargetOrId, tables } from 'harperdb';
|
|
27
28
|
|
|
28
29
|
export class MyTable extends tables.MyTable {
|
|
29
30
|
async post(target: RequestTargetOrId, record: any) {
|
|
30
31
|
// Custom logic here
|
|
31
|
-
if (!record.name) {
|
|
32
|
+
if (!record.name) {
|
|
33
|
+
throw new Error('Name required');
|
|
34
|
+
}
|
|
32
35
|
return super.post(target, record);
|
|
33
36
|
}
|
|
34
37
|
}
|
|
35
38
|
```
|
|
39
|
+
|
|
36
40
|
4. **Override Methods**: Override `get`, `post`, `put`, `patch`, or `delete` as needed. Always call `super[method]` to maintain default Harper functionality unless you intend to replace it entirely.
|
|
37
41
|
5. **Implement Logic**: Use overrides for validation, side effects, or transforming data before/after database operations.
|
|
@@ -11,33 +11,35 @@ Instructions for the agent to follow when handling binary data in Harper.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to store binary files (images, audio, etc.) in the database or serve them back to clients via REST endpoints.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
|
+
|
|
16
|
+
1. **Store Binary Data**: In your resource's `post` or `put` method, convert incoming data to Buffers and then to Blobs using `createBlob`. Include the MIME type if available:
|
|
15
17
|
|
|
16
|
-
1. **Store Base64 as Blobs**: In your resource's `post` or `put` method, convert incoming base64 strings to Buffers and then to Blobs using `createBlob`:
|
|
17
18
|
```typescript
|
|
18
19
|
import { createBlob } from 'harperdb';
|
|
19
20
|
|
|
20
21
|
async post(target, record) {
|
|
21
22
|
if (record.data) {
|
|
22
|
-
record.data = createBlob(Buffer.from(record.data, 'base64'), {
|
|
23
|
-
type: '
|
|
23
|
+
record.data = createBlob(Buffer.from(record.data, record.encoding || 'base64'), {
|
|
24
|
+
type: record.contentType || 'application/octet-stream',
|
|
24
25
|
});
|
|
25
26
|
}
|
|
26
27
|
return super.post(target, record);
|
|
27
28
|
}
|
|
28
29
|
```
|
|
30
|
+
|
|
29
31
|
2. **Serve Binary Data**: In your resource's `get` method, return a response object with the appropriate `Content-Type` and the binary data in the `body`:
|
|
30
32
|
```typescript
|
|
31
33
|
async get(target) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
34
|
+
const record = await super.get(target);
|
|
35
|
+
if (record?.data) {
|
|
36
|
+
return {
|
|
37
|
+
status: 200,
|
|
38
|
+
headers: { 'Content-Type': record.data.type || 'application/octet-stream' },
|
|
39
|
+
body: record.data,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return record;
|
|
41
43
|
}
|
|
42
44
|
```
|
|
43
45
|
3. **Use the Blob Type**: Ensure your GraphQL schema uses the `Blob` scalar for binary fields.
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when interacting with Harper tables via cod
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to perform database operations (CRUD, search, subscribe) from within Harper Resources or scripts.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Access the Table**: Use the global `tables` object followed by your table name (e.g., `tables.MyTable`).
|
|
17
17
|
2. **Perform CRUD Operations**:
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when querying Harper's REST APIs.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to perform advanced data retrieval (filtering, sorting, pagination, joins) using Harper's automatic REST endpoints.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Basic Filtering**: Use attribute names as query parameters: `GET /Table/?key=value`.
|
|
17
17
|
2. **Use Comparison Operators**: Append operators like `gt`, `ge`, `lt`, `le`, `ne` using FIQL-style syntax: `GET /Table/?price=gt=100`.
|
|
@@ -11,27 +11,33 @@ Instructions for the agent to follow when building real-time applications in Har
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to stream live updates to clients, implement chat features, or provide real-time data synchronization between the database and a frontend.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Check Automatic WebSockets**: If you only need to stream table changes, use [Automatic APIs](automatic-apis.md) which provide a WebSocket endpoint for every `@export`ed table.
|
|
17
|
-
2. **Implement `connect` in a Resource**: For custom bi-directional logic, implement the `connect` method
|
|
18
|
-
```typescript
|
|
19
|
-
import { Resource, tables } from 'harperdb';
|
|
20
|
-
|
|
21
|
-
export class MySocket extends Resource {
|
|
22
|
-
async *connect(target, incomingMessages) {
|
|
23
|
-
// Subscribe to table changes
|
|
24
|
-
const subscription = await tables.MyTable.subscribe(target);
|
|
25
|
-
if (!incomingMessages) { return subscription; // SSE mode
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// Handle incoming client messages
|
|
29
|
-
for await (let message of incomingMessages) {
|
|
30
|
-
yield { received: message };
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
```
|
|
17
|
+
2. **Implement `connect` in a Resource**: For custom bi-directional logic, implement the `connect` method.
|
|
35
18
|
3. **Use Pub/Sub**: Use `tables.TableName.subscribe(query)` to listen for specific data changes and stream them to the client.
|
|
36
19
|
4. **Handle SSE**: Ensure your `connect` method gracefully handles cases where `incomingMessages` is null (Server-Sent Events).
|
|
37
|
-
5. **Connect from Client**: Use standard WebSockets (`new WebSocket('
|
|
20
|
+
5. **Connect from Client**: Use standard WebSockets (`new WebSocket('wss://...')`) to connect to your resource endpoint. Ensure you use the appropriate scheme (`ws://` for HTTP, `wss://` for HTTPS).
|
|
21
|
+
|
|
22
|
+
## Examples
|
|
23
|
+
|
|
24
|
+
### Bi-directional WebSocket Resource
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
import { Resource, tables } from 'harperdb';
|
|
28
|
+
|
|
29
|
+
export class MySocket extends Resource {
|
|
30
|
+
async *connect(target, incomingMessages) {
|
|
31
|
+
// Subscribe to table changes
|
|
32
|
+
const subscription = await tables.MyTable.subscribe(target);
|
|
33
|
+
if (!incomingMessages) {
|
|
34
|
+
return subscription; // SSE mode
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Handle incoming client messages
|
|
38
|
+
for await (let message of incomingMessages) {
|
|
39
|
+
yield { received: message };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
```
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when serving web content from Harper.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to serve a frontend (HTML, CSS, JS, or a React app) directly from your Harper instance.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Choose a Method**: Decide between the simple Static Plugin or the integrated Vite Plugin.
|
|
17
17
|
2. **Option A: Static Plugin (Simple)**:
|
|
@@ -29,6 +29,37 @@ Use this skill when you need to serve a frontend (HTML, CSS, JS, or a React app)
|
|
|
29
29
|
package: '@harperfast/vite-plugin'
|
|
30
30
|
```
|
|
31
31
|
- Ensure `vite.config.ts` and `index.html` are in the project root.
|
|
32
|
+
|
|
33
|
+
```javascript
|
|
34
|
+
import vue from '@vitejs/plugin-vue';
|
|
35
|
+
import path from 'node:path';
|
|
36
|
+
import { defineConfig } from 'vite';
|
|
37
|
+
|
|
38
|
+
// https://vite.dev/config/
|
|
39
|
+
export default defineConfig({
|
|
40
|
+
plugins: [vue()],
|
|
41
|
+
resolve: {
|
|
42
|
+
alias: {
|
|
43
|
+
'@': path.resolve(import.meta.dirname, './src'),
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
build: {
|
|
47
|
+
outDir: 'web',
|
|
48
|
+
emptyOutDir: true,
|
|
49
|
+
rolldownOptions: {
|
|
50
|
+
external: ['**/*.test.*', '**/*.spec.*'],
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
32
56
|
- Install dependencies: `npm install --save-dev vite @harperfast/vite-plugin`.
|
|
33
|
-
-
|
|
34
|
-
|
|
57
|
+
- Then `harper run .` will start up Harper and Vite with HMR. Vite does _not_ need to be executed separately.
|
|
58
|
+
|
|
59
|
+
4. **Deploy for Production**: For Vite apps, use a build script to generate static files into a `web/` folder and deploy them using the static handler pattern. For example, these scripts in a package.json can perform the necessary steps:
|
|
60
|
+
```json
|
|
61
|
+
"build": "vite build",
|
|
62
|
+
"deploy": "rm -Rf deploy && npm run build && mkdir deploy && mv web deploy/ && cp -R deploy-template/* deploy/ && cp -R schemas resources deploy/ && dotenv -- npm run deploy:component && rm -Rf deploy",
|
|
63
|
+
"deploy:component": "(cd deploy && harper deploy_component . project=web restart=rolling replicated=true)"
|
|
64
|
+
```
|
|
65
|
+
Then in production, the "Static Plugin" option will performantly and securely serve your assets. `npm create harper@latest` scaffolds all of this for you.
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when using TypeScript in Harper.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you want to write Harper Resources in TypeScript and have them execute directly in Node.js without an intermediate build or compilation step.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Verify Node.js Version**: Ensure you are using Node.js v22.6.0 or higher.
|
|
17
17
|
2. **Name Files with `.ts`**: Create your resource files in the `resources/` directory with a `.ts` extension.
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when working with the Blob data type in Har
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to store unstructured or large binary data (media, documents) that is too large for standard JSON fields. Blobs provide efficient storage and integrated streaming support.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Define Blob Fields**: In your GraphQL schema, use the `Blob` type:
|
|
17
17
|
```graphql
|
|
@@ -11,7 +11,7 @@ Instructions for the agent to follow when implementing vector search in Harper.
|
|
|
11
11
|
|
|
12
12
|
Use this skill when you need to perform similarity searches on high-dimensional data, such as AI embeddings for semantic search, recommendations, or image retrieval.
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## How It Works
|
|
15
15
|
|
|
16
16
|
1. **Enable Vector Indexing**: In your GraphQL schema, add `@indexed(type: "HNSW")` to a numeric array field:
|
|
17
17
|
```graphql
|
|
@@ -46,88 +46,93 @@ Use this skill when you need to perform similarity searches on high-dimensional
|
|
|
46
46
|
5. **Generate Embeddings**: Use external services (OpenAI, Ollama) to generate the numeric vectors before storing or searching them in Harper.
|
|
47
47
|
|
|
48
48
|
```typescript
|
|
49
|
-
const { Product } = tables;
|
|
50
|
-
|
|
51
49
|
import OpenAI from 'openai';
|
|
50
|
+
import ollama from 'ollama';
|
|
51
|
+
|
|
52
|
+
const { Product } = tables;
|
|
52
53
|
const openai = new OpenAI();
|
|
53
54
|
// the name of the OpenAI embedding model
|
|
54
55
|
const OPENAI_EMBEDDING_MODEL = 'text-embedding-3-small';
|
|
55
56
|
|
|
57
|
+
// the name of the Ollama embedding model
|
|
58
|
+
const OLLAMA_EMBEDDING_MODEL = 'llama3';
|
|
59
|
+
|
|
56
60
|
const SIMILARITY_THRESHOLD = 0.5;
|
|
57
61
|
|
|
58
62
|
export class ProductSearch extends Resource {
|
|
59
|
-
// based on env variable we choose the appropriate embedding generator
|
|
60
|
-
generateEmbedding =
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
63
|
+
// based on env variable we choose the appropriate embedding generator
|
|
64
|
+
generateEmbedding =
|
|
65
|
+
process.env.EMBEDDING_GENERATOR === 'ollama'
|
|
66
|
+
? this._generateOllamaEmbedding
|
|
67
|
+
: this._generateOpenAIEmbedding;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Executes a search query using a generated text embedding and returns the matching products.
|
|
71
|
+
*
|
|
72
|
+
* @param {Object} data - The input data for the request.
|
|
73
|
+
* @param {string} data.prompt - The prompt to generate the text embedding from.
|
|
74
|
+
* @return {Promise<Array>} Returns a promise that resolves to an array of products matching the conditions,
|
|
75
|
+
* including fields: name, description, price, and $distance.
|
|
76
|
+
*/
|
|
77
|
+
async post(data) {
|
|
78
|
+
const embedding = await this.generateEmbedding(data.prompt);
|
|
79
|
+
|
|
80
|
+
return await Product.search({
|
|
81
|
+
select: ['name', 'description', 'price', '$distance'],
|
|
82
|
+
conditions: {
|
|
83
|
+
attribute: 'textEmbeddings',
|
|
84
|
+
comparator: 'lt',
|
|
85
|
+
value: SIMILARITY_THRESHOLD,
|
|
86
|
+
target: embedding[0],
|
|
87
|
+
},
|
|
88
|
+
limit: 5,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Generates an embedding using the Ollama API.
|
|
94
|
+
*
|
|
95
|
+
* @param {string} promptData - The input data for which the embedding is to be generated.
|
|
96
|
+
* @return {Promise<number[][]>} A promise that resolves to the generated embedding as an array of numbers.
|
|
97
|
+
*/
|
|
98
|
+
async _generateOllamaEmbedding(promptData) {
|
|
99
|
+
const embedding = await ollama.embed({
|
|
100
|
+
model: OLLAMA_EMBEDDING_MODEL,
|
|
101
|
+
input: promptData,
|
|
102
|
+
});
|
|
103
|
+
return embedding?.embeddings;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Generates OpenAI embeddings based on the given prompt data.
|
|
108
|
+
*
|
|
109
|
+
* @param {string} promptData - The input data used for generating the embedding.
|
|
110
|
+
* @return {Promise<number[][]>} A promise that resolves to an array of embeddings, where each embedding is an array of floats.
|
|
111
|
+
*/
|
|
112
|
+
async _generateOpenAIEmbedding(promptData) {
|
|
113
|
+
const embedding = await openai.embeddings.create({
|
|
114
|
+
model: OPENAI_EMBEDDING_MODEL,
|
|
115
|
+
input: promptData,
|
|
116
|
+
encoding_format: 'float',
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
let embeddings = [];
|
|
120
|
+
embedding.data.forEach((embeddingData) => {
|
|
121
|
+
embeddings.push(embeddingData.embedding);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
return embeddings;
|
|
125
|
+
}
|
|
122
126
|
}
|
|
123
|
-
|
|
124
127
|
```
|
|
125
128
|
|
|
129
|
+
## Examples
|
|
130
|
+
|
|
126
131
|
Sample request to the `ProductSearch` resource which prompts to find "shorts for the gym":
|
|
127
132
|
|
|
128
133
|
```bash
|
|
129
134
|
curl -X POST "http://localhost:9926/ProductSearch/" \
|
|
130
|
-
-H "
|
|
135
|
+
-H "Accept: application/json" \
|
|
131
136
|
-H "Content-Type: application/json" \
|
|
132
137
|
-H "Authorization: Basic <YOUR_AUTH>" \
|
|
133
138
|
-d '{"prompt": "shorts for the gym"}'
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@harperfast/template-react-studio",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.10",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": "github:HarperFast/create-harper",
|
|
6
6
|
"scripts": {},
|
|
7
7
|
"devDependencies": {
|
|
8
8
|
"@eslint/js": "^10.0.1",
|
|
9
|
-
"@harperfast/schema-codegen": "^1.0.
|
|
10
|
-
"@harperfast/vite-plugin": "^0.1
|
|
9
|
+
"@harperfast/schema-codegen": "^1.0.10",
|
|
10
|
+
"@harperfast/vite-plugin": "^0.2.1",
|
|
11
11
|
"@vitejs/plugin-react": "^6.0.1",
|
|
12
12
|
"dotenv-cli": "^11.0.0",
|
|
13
13
|
"eslint": "^10.0.2",
|
package/skills-lock.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"harper-best-practices": {
|
|
5
5
|
"source": "harperfast/skills",
|
|
6
6
|
"sourceType": "github",
|
|
7
|
-
"computedHash": "
|
|
7
|
+
"computedHash": "a63855b5afa53053dea933f18e9f0b6487cc404414c02e77d3b848e31e100401"
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
10
|
}
|