create-harper 0.12.3 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/package.json +1 -1
  2. package/template-react/AGENTS.md +5 -2
  3. package/template-react/resources/README.md +1 -1
  4. package/template-react/skills/adding-tables-with-schemas.md +2 -2
  5. package/template-react/skills/automatic-apis.md +53 -0
  6. package/template-react/skills/caching.md +113 -0
  7. package/template-react/skills/checking-authentication.md +100 -5
  8. package/template-react/skills/custom-resources.md +8 -4
  9. package/template-react/skills/defining-relationships.md +3 -3
  10. package/template-react/skills/extending-tables.md +7 -3
  11. package/template-react/skills/handling-binary-data.md +3 -3
  12. package/template-react/skills/programmatic-table-requests.md +3 -3
  13. package/template-react/skills/querying-rest-apis.md +2 -2
  14. package/template-react/skills/real-time-apps.md +8 -4
  15. package/template-react/skills/typescript-type-stripping.md +4 -4
  16. package/template-react/skills/using-blob-datatype.md +131 -0
  17. package/template-react/skills/vector-indexing.md +215 -0
  18. package/template-react-ts/AGENTS.md +5 -2
  19. package/template-react-ts/resources/README.md +1 -1
  20. package/template-react-ts/skills/adding-tables-with-schemas.md +2 -2
  21. package/template-react-ts/skills/automatic-apis.md +53 -0
  22. package/template-react-ts/skills/caching.md +113 -0
  23. package/template-react-ts/skills/checking-authentication.md +100 -5
  24. package/template-react-ts/skills/custom-resources.md +8 -4
  25. package/template-react-ts/skills/defining-relationships.md +3 -3
  26. package/template-react-ts/skills/extending-tables.md +7 -3
  27. package/template-react-ts/skills/handling-binary-data.md +3 -3
  28. package/template-react-ts/skills/programmatic-table-requests.md +3 -3
  29. package/template-react-ts/skills/querying-rest-apis.md +2 -2
  30. package/template-react-ts/skills/real-time-apps.md +8 -4
  31. package/template-react-ts/skills/typescript-type-stripping.md +4 -4
  32. package/template-react-ts/skills/using-blob-datatype.md +131 -0
  33. package/template-react-ts/skills/vector-indexing.md +215 -0
  34. package/template-vanilla/AGENTS.md +5 -2
  35. package/template-vanilla/resources/README.md +1 -1
  36. package/template-vanilla/skills/adding-tables-with-schemas.md +2 -2
  37. package/template-vanilla/skills/automatic-apis.md +53 -0
  38. package/template-vanilla/skills/caching.md +113 -0
  39. package/template-vanilla/skills/checking-authentication.md +100 -5
  40. package/template-vanilla/skills/custom-resources.md +8 -4
  41. package/template-vanilla/skills/defining-relationships.md +3 -3
  42. package/template-vanilla/skills/extending-tables.md +7 -3
  43. package/template-vanilla/skills/handling-binary-data.md +3 -3
  44. package/template-vanilla/skills/programmatic-table-requests.md +3 -3
  45. package/template-vanilla/skills/querying-rest-apis.md +2 -2
  46. package/template-vanilla/skills/real-time-apps.md +8 -4
  47. package/template-vanilla/skills/typescript-type-stripping.md +4 -4
  48. package/template-vanilla/skills/using-blob-datatype.md +131 -0
  49. package/template-vanilla/skills/vector-indexing.md +215 -0
  50. package/template-vanilla-ts/AGENTS.md +5 -2
  51. package/template-vanilla-ts/resources/README.md +1 -1
  52. package/template-vanilla-ts/skills/adding-tables-with-schemas.md +2 -2
  53. package/template-vanilla-ts/skills/automatic-apis.md +53 -0
  54. package/template-vanilla-ts/skills/caching.md +113 -0
  55. package/template-vanilla-ts/skills/checking-authentication.md +100 -5
  56. package/template-vanilla-ts/skills/custom-resources.md +8 -4
  57. package/template-vanilla-ts/skills/defining-relationships.md +3 -3
  58. package/template-vanilla-ts/skills/extending-tables.md +7 -3
  59. package/template-vanilla-ts/skills/handling-binary-data.md +3 -3
  60. package/template-vanilla-ts/skills/programmatic-table-requests.md +3 -3
  61. package/template-vanilla-ts/skills/querying-rest-apis.md +2 -2
  62. package/template-vanilla-ts/skills/real-time-apps.md +8 -4
  63. package/template-vanilla-ts/skills/typescript-type-stripping.md +4 -4
  64. package/template-vanilla-ts/skills/using-blob-datatype.md +131 -0
  65. package/template-vanilla-ts/skills/vector-indexing.md +215 -0
@@ -1,10 +1,14 @@
1
- # Real-time Applications in HarperDB
1
+ # Real-time Applications in Harper
2
2
 
3
- HarperDB provides built-in support for real-time data synchronization using WebSockets and a Pub/Sub mechanism. This allows clients to receive immediate updates when data changes in the database.
3
+ Harper provides built-in support for real-time data synchronization using WebSockets and a Pub/Sub mechanism. This allows clients to receive immediate updates when data changes in the database.
4
+
5
+ ## Automatic WebSockets
6
+
7
+ For many use cases, the [Automatic APIs](automatic-apis.md) provided by Harper are more than enough. When you `@export` a table, Harper automatically provides a WebSocket endpoint that publishes events whenever data in that table is updated.
4
8
 
5
9
  ## Implementing a WebSocket Resource
6
10
 
7
- To handle WebSocket connections, implement the `connect` method in your custom resource class.
11
+ Customizing resources by implementing a `connect` method is only necessary when you want to come up with a more specific back-and-forth or custom message handling. To handle WebSocket connections, implement the `connect` method in your custom resource class.
8
12
 
9
13
  ### Example: `resources/exampleSocket.ts`
10
14
 
@@ -68,4 +72,4 @@ socket.send(JSON.stringify({ type: 'ping' }));
68
72
 
69
73
  - **Automatic Table Subscriptions**: Easily stream changes from any database table.
70
74
  - **Bi-directional Communication**: Send and receive messages in real-time.
71
- - **Scalable Pub/Sub**: HarperDB handles the efficient distribution of messages to subscribers.
75
+ - **Scalable Pub/Sub**: Harper handles the efficient distribution of messages to subscribers.
@@ -1,16 +1,16 @@
1
1
  # TypeScript Type Stripping
2
2
 
3
- HarperDB supports using TypeScript directly without any additional build tools (like `tsc` or `esbuild`) by leveraging Node.js's native Type Stripping capability. This allows you to write `.ts` files for your Custom Resources and have them run directly in HarperDB.
3
+ Harper supports using TypeScript directly without any additional build tools (like `tsc` or `esbuild`) by leveraging Node.js's native Type Stripping capability. This allows you to write `.ts` files for your Custom Resources and have them run directly in Harper.
4
4
 
5
5
  ## Requirements
6
6
 
7
7
  - **Node.js Version**: You must be running a version of Node.js that supports type stripping (Node.js v22.6.0 or higher).
8
- - **No Experimental Flags**: When running on supported Node.js versions, HarperDB can automatically handle type stripping for your resource files.
8
+ - **No Experimental Flags**: When running on supported Node.js versions, Harper can automatically handle type stripping for your resource files.
9
9
 
10
10
  ## Benefits
11
11
 
12
12
  - **Faster Development**: No need to wait for a build step or manage complex build pipelines.
13
- - **Simplified Tooling**: You don't need to install or configure `ts-node`, `tsx`, or other TypeScript execution engines for your HarperDB resources.
13
+ - **Simplified Tooling**: You don't need to install or configure `ts-node`, `tsx`, or other TypeScript execution engines for your Harper resources.
14
14
  - **Native Performance**: Leverages Node.js's built-in support for stripping types, which is highly efficient.
15
15
 
16
16
  ## Usage
@@ -44,4 +44,4 @@ jsResource:
44
44
  files: 'resources/*.ts'
45
45
  ```
46
46
 
47
- When HarperDB starts, it will detect the `.ts` files and, if running on a compatible Node.js version, will execute them using type stripping.
47
+ When Harper starts, it will detect the `.ts` files and, if running on a compatible Node.js version, will execute them using type stripping.
@@ -0,0 +1,131 @@
1
+ # Blob (Binary Large Objects)
2
+
3
+ Harper supports **Blobs** — binary large objects for storing unstructured or large binary data — with integrated streaming support and efficient storage. Blobs are ideal for media files, documents, and any data where size or throughput makes standard JSON fields impractical.
4
+
5
+ ---
6
+
7
+ ## What Are Blobs
8
+
9
+ Blobs extend the native JavaScript `Blob` type and allow you to store **binary or arbitrary data** inside Harper tables. The blob reference is stored in the record, while the blob’s contents are streamed to and from storage.
10
+
11
+ - Designed for binary data such as images, audio, and documents
12
+ - Supports streaming reads and writes
13
+ - Blob data is stored separately from record attributes
14
+ - Optimized for large payloads
15
+
16
+ ---
17
+
18
+ ## Defining Blob Fields
19
+
20
+ Declare a blob field using the `Blob` type in your schema:
21
+
22
+ ```graphql
23
+ type MyTable @table {
24
+ id: ID @primaryKey
25
+ data: Blob
26
+ }
27
+ ```
28
+
29
+ Any record written to this field will store a reference to the blob’s contents.
30
+
31
+ ---
32
+
33
+ ## Creating and Storing Blobs
34
+
35
+ ### Creating a Blob from a Buffer
36
+
37
+ ```js
38
+ const blob = createBlob(largeBuffer);
39
+ await MyTable.put({ id: 'my-record', data: blob });
40
+ ```
41
+
42
+ - `createBlob()` returns a blob reference
43
+ - Data is streamed to storage asynchronously
44
+ - Records may be committed before the blob finishes writing
45
+
46
+ ---
47
+
48
+ ### Creating a Blob from a Stream
49
+
50
+ ```js
51
+ const blob = createBlob(stream);
52
+ await MyTable.put({ id: 'streamed-record', data: blob });
53
+ ```
54
+
55
+ Streaming allows large data to be written without loading it fully into memory.
56
+
57
+ ---
58
+
59
+ ## Reading Blob Data
60
+
61
+ Retrieve a record and read its blob contents:
62
+
63
+ ```js
64
+ const record = await MyTable.get('my-record');
65
+ const buffer = await record.data.bytes();
66
+ ```
67
+
68
+ Blob objects also support streaming interfaces for large reads.
69
+
70
+ ---
71
+
72
+ ## Blob Attributes and Events
73
+
74
+ ### Size
75
+
76
+ The blob size may not be immediately available when streaming:
77
+
78
+ ```js
79
+ if (blob.size === undefined) {
80
+ blob.on('size', size => {
81
+ console.log('Blob size:', size);
82
+ });
83
+ }
84
+ ```
85
+
86
+ ---
87
+
88
+ ### saveBeforeCommit
89
+
90
+ Blobs are not atomic while streaming. To ensure the blob is fully written before committing the record:
91
+
92
+ ```js
93
+ const blob = createBlob(stream, { saveBeforeCommit: true });
94
+ await MyTable.put({ id: 'safe-record', data: blob });
95
+ ```
96
+
97
+ ---
98
+
99
+ ## Error Handling
100
+
101
+ Handle streaming errors by attaching an error listener:
102
+
103
+ ```js
104
+ blob.on('error', () => {
105
+ MyTable.invalidate('my-record');
106
+ });
107
+ ```
108
+
109
+ This prevents partially written blobs from being used.
110
+
111
+ ---
112
+
113
+ ## Automatic Coercion
114
+
115
+ When a field is defined as `Blob`, assigning a string or buffer automatically converts it into a blob when using `put`, `patch`, or `publish`.
116
+
117
+ ---
118
+
119
+ ## Related Skill
120
+
121
+ - [Handling Binary Data with Blobs](handling-binary-data.md) How to store and serve binary data like images or MP3s using the Blob data type.
122
+
123
+ ---
124
+
125
+ ## Summary
126
+
127
+ - Blobs store large or binary data efficiently
128
+ - Blob fields reference streamed content
129
+ - Supports buffered and streamed writes
130
+ - Optional write-before-commit behavior
131
+ - Integrates seamlessly with Harper tables
@@ -0,0 +1,215 @@
1
+ # Vector Indexing
2
+
3
+ Harper supports **vector indexing** on array attributes, enabling efficient similarity search over high-dimensional vector data. This is essential for AI-powered features such as semantic search, recommendations, and embeddings-based retrieval.
4
+
5
+ ---
6
+
7
+ ## What Is Vector Indexing
8
+
9
+ Vector indexing organizes numeric vectors so that Harper can efficiently find records that are closest to a given query vector using a distance metric such as cosine similarity or Euclidean distance.
10
+
11
+ Unlike traditional indexes that rely on exact matches, vector indexes enable **nearest-neighbor search** across high-dimensional spaces, making them ideal for embeddings and machine learning workloads.
12
+
13
+ ---
14
+
15
+ ## Enabling a Vector Index
16
+
17
+ Vector indexes are defined using the `@indexed` directive on numeric array attributes.
18
+
19
+ ```graphql
20
+ type Product @table {
21
+ id: Long @primaryKey
22
+ name: String
23
+ description: String
24
+ textEmbeddings: [Float] @indexed(type: "HNSW")
25
+ price: Float
26
+ }
27
+ ```
28
+
29
+ - `type: "HNSW"` enables Harper’s vector index using the HNSW algorithm
30
+ - The indexed field must be an array of numeric values
31
+ - Vector indexes are stored and maintained automatically
32
+
33
+ ---
34
+
35
+ ## Querying with a Vector Index
36
+
37
+ ### Search Vectors with sort
38
+
39
+ Once defined, vector indexes can be used by specifying a `sort` configuration with a target vector. To view the similarity of a result to a given query vector, use the `$distance` attribute in the `select` clause.
40
+
41
+ ```js
42
+ const results = Product.search({
43
+ select: ['name', 'description', 'price', '$distance'],
44
+ sort: {
45
+ attribute: 'textEmbeddings',
46
+ target: searchVector,
47
+ },
48
+ limit: 5,
49
+ });
50
+ ```
51
+
52
+ - `attribute` is the vector index attribute
53
+ - `target` is the vector to compare against
54
+ - `searchVector` is the embedding to compare against
55
+ - Results are ordered by similarity
56
+ - Vector search can be combined with filters and limits
57
+ - The `$distance` attribute in the `select` (optional) returns the distance between the result and the query vector
58
+
59
+ ### Search Vectors limited by distance
60
+
61
+ Vector indexes results can be limited by distance using the `conditions` clause. In the following example, results are returned that are less than 0.1 similar to the query vector.
62
+ The `conditions` clause can be combined with `sort` and `limit` and the `comparator` can be any of the following: `lt`, `lte`, `gt`, `gte`, `between`.
63
+
64
+ ```js
65
+ const results = Product.search({
66
+ select: ['name', 'description', 'price', '$distance'],
67
+ conditions: {
68
+ attribute: 'textEmbeddings',
69
+ comparator: 'lt',
70
+ value: 0.1, // '0.1' is the similarity threshold
71
+ target: searchVector,
72
+ },
73
+ });
74
+ ```
75
+
76
+ - `attribute` is the vector index attribute
77
+ - `comparator` is the comparison operator (`lt`, `lte`, `gt`, `gte`, `between` are accepted)
78
+ - `value` is the threshold value
79
+ - `target` is the vector to compare against
80
+ - `searchVector` is the embedding to compare against
81
+ - Vector search can be combined with filters, sort, and limits
82
+ - The `$distance` attribute in the `select` (optional) returns the distance between the result and the query vector
83
+
84
+ ---
85
+
86
+ ## Vector Index Options
87
+
88
+ Additional tuning options can be provided on the `@indexed` directive:
89
+
90
+ | Option | Description |
91
+ | ---------------------- | ------------------------------------------- |
92
+ | `distance` | Similarity metric (`cosine` or `euclidean`) |
93
+ | `efConstruction` | Index build quality vs performance |
94
+ | `M` | Graph connectivity per HNSW layer |
95
+ | `optimizeRouting` | Improves routing efficiency |
96
+ | `efSearchConstruction` | Search breadth during queries |
97
+
98
+ These options allow fine-tuning for performance and recall tradeoffs.
99
+
100
+ ---
101
+
102
+ ## How to Generate and Search Vector Embeddings
103
+
104
+ Here is a full example that generates embeddings for a set of products and then searches for similar products using vector indexes. The following example shows how to generate embeddings using OpenAI or Ollama.
105
+
106
+ ```js
107
+ import { Ollama } from 'ollama';
108
+ const ollama = new Ollama({ host: 'http://127.0.0.1:11434' });
109
+ // The name of the ollama embedding model
110
+ const OLLAMA_EMBEDDING_MODEL = 'nomic-embed-text';
111
+
112
+ const { Product } = tables;
113
+
114
+ import OpenAI from 'openai';
115
+ const openai = new OpenAI();
116
+ // the name of the OpenAI embedding model
117
+ const OPENAI_EMBEDDING_MODEL = 'text-embedding-3-small';
118
+
119
+ const SIMILARITY_THRESHOLD = 0.5;
120
+
121
+ export class ProductSearch extends Resource {
122
+ // based on env variable we choose the appropriate embedding generator
123
+ generateEmbedding = process.env.EMBEDDING_GENERATOR === 'ollama'
124
+ ? this._generateOllamaEmbedding
125
+ : this._generateOpenAIEmbedding;
126
+
127
+ /**
128
+ * Executes a search query using a generated text embedding and returns the matching products.
129
+ *
130
+ * @param {Object} data - The input data for the request.
131
+ * @param {string} data.prompt - The prompt to generate the text embedding from.
132
+ * @return {Promise<Array>} Returns a promise that resolves to an array of products matching the conditions,
133
+ * including fields: name, description, price, and $distance.
134
+ */
135
+ async post(data) {
136
+ const embedding = await this.generateEmbedding(data.prompt);
137
+
138
+ return await Product.search({
139
+ select: ['name', 'description', 'price', '$distance'],
140
+ conditions: {
141
+ attribute: 'textEmbeddings',
142
+ comparator: 'lt',
143
+ value: SIMILARITY_THRESHOLD,
144
+ target: embedding[0],
145
+ },
146
+ limit: 5,
147
+ });
148
+ }
149
+
150
+ /**
151
+ * Generates an embedding using the Ollama API.
152
+ *
153
+ * @param {string} promptData - The input data for which the embedding is to be generated.
154
+ * @return {Promise<number[][]>} A promise that resolves to the generated embedding as an array of numbers.
155
+ */
156
+ async _generateOllamaEmbedding(promptData) {
157
+ const embedding = await ollama.embed({
158
+ model: OLLAMA_EMBEDDING_MODEL,
159
+ input: promptData,
160
+ });
161
+ return embedding?.embeddings;
162
+ }
163
+
164
+ /**
165
+ * Generates OpenAI embeddings based on the given prompt data.
166
+ *
167
+ * @param {string} promptData - The input data used for generating the embedding.
168
+ * @return {Promise<number[][]>} A promise that resolves to an array of embeddings, where each embedding is an array of floats.
169
+ */
170
+ async _generateOpenAIEmbedding(promptData) {
171
+ const embedding = await openai.embeddings.create({
172
+ model: OPENAI_EMBEDDING_MODEL,
173
+ input: promptData,
174
+ encoding_format: 'float',
175
+ });
176
+
177
+ let embeddings = [];
178
+ embedding.data.forEach((embeddingData) => {
179
+ embeddings.push(embeddingData.embedding);
180
+ });
181
+
182
+ return embeddings;
183
+ }
184
+ }
185
+ ```
186
+
187
+ Sample request to the `ProductSearch` resource which prompts to find "shorts for the gym":
188
+
189
+ ```bash
190
+ curl -X POST "http://localhost:9926/ProductSearch/" \
191
+ -H "accept: \
192
+ -H "Content-Type: application/json" \
193
+ -H "Authorization: Basic <YOUR_AUTH>" \
194
+ -d '{"prompt": "shorts for the gym"}'
195
+ ```
196
+
197
+ ---
198
+
199
+ ## When to Use Vector Indexing
200
+
201
+ Vector indexing is ideal when:
202
+
203
+ - Storing embedding vectors from ML models
204
+ - Performing semantic or similarity-based search
205
+ - Working with high-dimensional numeric data
206
+ - Exact-match indexes are insufficient
207
+
208
+ ---
209
+
210
+ ## Summary
211
+
212
+ - Vector indexing enables fast similarity search on numeric arrays
213
+ - Defined using `@indexed(type: "HNSW")`
214
+ - Queried using a target vector in search sorting
215
+ - Tunable for performance and accuracy
@@ -1,11 +1,11 @@
1
- # HarperDB Agent Skills
1
+ # Harper Agent Skills
2
2
 
3
3
  This repository contains "skills" that guide AI agents in developing Harper applications.
4
4
 
5
5
  ## Available Skills
6
6
 
7
7
  - [Adding Tables with Schemas](skills/adding-tables-with-schemas.md): Learn how to define schemas and enable automatic REST APIs for your database tables with schema .graphql files in Harper.
8
- - [Automatic REST APIs](skills/automatic-rest-apis.md): Details on the CRUD endpoints automatically generated for exported tables.
8
+ - [Automatic APIs](skills/automatic-apis.md): Details on the CRUD endpoints automatically generated for exported tables with REST and WebSockets.
9
9
  - [Querying REST APIs](skills/querying-rest-apis.md): How to use filters, operators, sorting, and pagination in REST requests.
10
10
  - [Programmatic Table Requests](skills/programmatic-table-requests.md): How to use filters, operators, sorting, and pagination in programmatic table requests.
11
11
  - [Custom Resources](skills/custom-resources.md): How to define custom REST endpoints using JavaScript or TypeScript (Note: Paths are case-sensitive).
@@ -16,3 +16,6 @@ This repository contains "skills" that guide AI agents in developing Harper appl
16
16
  - [Handling Binary Data](skills/handling-binary-data.md): How to store and serve binary data like images or MP3s.
17
17
  - [Serving Web Content](skills/serving-web-content): Two ways to serve web content from a Harper application.
18
18
  - [Checking Authentication](skills/checking-authentication.md): How to use sessions to verify user identity and roles.
19
+ - [Caching](skills/caching.md): How caching is defined and implemented in Harper applications.
20
+ - [Using Blobs](skills/using-blob-datatype.md): How to store and retrieve large data in HarperDB.
21
+ - [Vector Indexing](skills/vector-indexing.md): How to define and use vector indexes for efficient similarity search.
@@ -1,6 +1,6 @@
1
1
  # Resources
2
2
 
3
- The [schemas you define in .GraphQL files](../skills/adding-tables-with-schemas.md) will [automatically stand-up REST APIs](../skills/automatic-rest-apis.md).
3
+ The [schemas you define in .GraphQL files](../skills/adding-tables-with-schemas.md) will [automatically stand-up REST APIs](../skills/automatic-apis.md).
4
4
 
5
5
  But you can [extend your tables with custom logic](../skills/extending-tables.md) and [create your own resources](../skills/custom-resources.md) in this directory.
6
6
 
@@ -1,4 +1,4 @@
1
- # Adding Tables to HarperDB
1
+ # Adding Tables to Harper
2
2
 
3
3
  To add tables to a Harper database, follow these guidelines:
4
4
 
@@ -8,7 +8,7 @@ To add tables to a Harper database, follow these guidelines:
8
8
 
9
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
10
 
11
- 4. **Automatic REST APIs**: If you add `@table @export` to a schema type, HarperDB automatically sets up REST 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-rest-apis.md) skill.
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
12
 
13
13
  - `GET /{TableName}`: Describes the schema itself.
14
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.
@@ -0,0 +1,53 @@
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).
@@ -0,0 +1,113 @@
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