rystem.repository.client 0.2.7 → 10.1.0-beta.3

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/README.md +321 -161
  2. package/package.json +6 -1
  3. package/lib/engine/Repository.d.ts +0 -27
  4. package/lib/engine/Repository.js +0 -333
  5. package/lib/engine/batch/Batch.d.ts +0 -9
  6. package/lib/engine/batch/Batch.js +0 -17
  7. package/lib/engine/batch/BatchBuilder.d.ts +0 -13
  8. package/lib/engine/batch/BatchBuilder.js +0 -48
  9. package/lib/engine/batch/BatchOperation.d.ts +0 -12
  10. package/lib/engine/batch/BatchOperation.js +0 -16
  11. package/lib/engine/batch/BatchResult.d.ts +0 -13
  12. package/lib/engine/batch/BatchResult.js +0 -18
  13. package/lib/engine/query/FilterOperationAsString.d.ts +0 -5
  14. package/lib/engine/query/FilterOperationAsString.js +0 -2
  15. package/lib/engine/query/FilterOperations.d.ts +0 -11
  16. package/lib/engine/query/FilterOperations.js +0 -15
  17. package/lib/engine/query/QueryBuilder.d.ts +0 -25
  18. package/lib/engine/query/QueryBuilder.js +0 -116
  19. package/lib/engine/query/SerializableFilter.d.ts +0 -4
  20. package/lib/engine/query/SerializableFilter.js +0 -2
  21. package/lib/engine/query/filter/WhereBuilder.d.ts +0 -33
  22. package/lib/engine/query/filter/WhereBuilder.js +0 -170
  23. package/lib/hooks/hooks.d.ts +0 -9
  24. package/lib/hooks/hooks.js +0 -28
  25. package/lib/index.d.ts +0 -11
  26. package/lib/index.js +0 -16
  27. package/lib/interfaces/ICommand.d.ts +0 -14
  28. package/lib/interfaces/ICommand.js +0 -2
  29. package/lib/interfaces/IQuery.d.ts +0 -12
  30. package/lib/interfaces/IQuery.js +0 -2
  31. package/lib/interfaces/IRepository.d.ts +0 -6
  32. package/lib/interfaces/IRepository.js +0 -2
  33. package/lib/models/Entity.d.ts +0 -11
  34. package/lib/models/Entity.js +0 -20
  35. package/lib/models/RepositoryEndpoint.d.ts +0 -12
  36. package/lib/models/RepositoryEndpoint.js +0 -16
  37. package/lib/models/State.d.ts +0 -20
  38. package/lib/models/State.js +0 -26
  39. package/lib/servicecollection/RepositoryServices.d.ts +0 -23
  40. package/lib/servicecollection/RepositoryServices.js +0 -106
  41. package/lib/servicecollection/RepositorySettings.d.ts +0 -22
  42. package/lib/servicecollection/RepositorySettings.js +0 -58
package/README.md CHANGED
@@ -1,205 +1,365 @@
1
- ### [What is Rystem?](https://github.com/KeyserDSoze/Rystem)
1
+ # rystem.repository.client
2
2
 
3
- # Client for Repository Framework
3
+ `rystem.repository.client` is the TypeScript client runtime for Repository Framework API servers.
4
4
 
5
- ## Services setup
6
- You need to install through the RepositoryServices class
7
- all the repository clients, with settings.
5
+ It gives you:
8
6
 
9
- .Create() => set a default uri for all clients.
10
- In settings you have:
11
- - name: a value to retrieve the installed client.
12
- - path: a path which concatened with default uri create the final url for your client.
13
- - uri: override the default uri and the path
7
+ - a singleton repository registry (`RepositoryServices`)
8
+ - typed repository/query/command clients
9
+ - a fluent query builder
10
+ - a fluent batch builder
11
+ - optional transformers for values and keys
14
12
 
15
- ```
16
- import { RepositoryServices } from "rystem.repository.client";
13
+ ## Installation
17
14
 
18
- RepositoryServices
19
- .Create("https://localhost:7058/api/")
20
- .addRepository<IperUser, string>(x => {
21
- x.name = "test";
22
- x.path = "SuperUser";
23
- })
24
- .addRepository<SuperUser, string>(x => {
25
- x.name = "test2"
26
- x.uri = "https://localhost:9090/api/SuperUser/inmemory/"
27
- });
15
+ ```bash
16
+ npm install rystem.repository.client
28
17
  ```
29
18
 
30
- You can also add Command or Query for your CQRS pattern with
19
+ ## What the package exports
20
+
21
+ Runtime exports:
22
+
23
+ - `RepositoryServices`
24
+ - `RepositorySettings`
25
+ - `RepositoryEndpoint`
26
+ - `useRepository`, `useCommand`, `useQuery`
27
+ - `useRepositoryPattern`, `useCommandPattern`, `useQueryPattern`
28
+
29
+ Type exports:
30
+
31
+ - `IRepository`, `ICommand`, `IQuery`
32
+ - `IRepositoryPattern`, `ICommandPattern`, `IQueryPattern`
33
+ - `Entity`
34
+ - `State`
35
+ - `BatchResult`
36
+ - `ITransformer`
37
+
38
+ ## Bootstrap pattern
39
+
40
+ The package uses one singleton service registry.
41
+
42
+ ```typescript
43
+ import { RepositoryServices } from 'rystem.repository.client';
31
44
 
32
- ```
33
45
  RepositoryServices
34
- .Create("https://localhost:7058/api/")
35
- .addCommand<IperUser, string>(x => {
36
- x.name = "test";
37
- x.path = "SuperUser";
38
- })
39
- .addQuery<SuperUser, string>(x => {
40
- x.name = "test2"
41
- x.uri = "https://localhost:9090/api/SuperUser/inmemory/"
42
- });
46
+ .Create('https://localhost:7058/api/')
47
+ .addRepository<User, string>(settings => {
48
+ settings.name = 'users';
49
+ settings.path = '/User';
50
+ });
43
51
  ```
44
52
 
45
- ### Add Custom Headers to each request
46
- For instance when you need to add a token from your authentication flow you can use this implementation.
53
+ Then retrieve the typed client by name:
47
54
 
55
+ ```typescript
56
+ const repo = RepositoryServices.Repository<User, string>('users');
48
57
  ```
49
- RepositoryServices
50
- .Create("http://localhost:5000/api/")
51
- .addRepository<IperUser, string>(x => {
52
- x.name = "test";
53
- x.path = "SuperUser";
54
- x.addHeadersEnricher(async (...args) => {
55
- return {
56
- "Authorization-UI": "Bearer dsjadjalsdjalsdjalsda"
57
- }
58
- });
59
- x.addHeadersEnricher(async (endpoint: RepositoryEndpoint, uri: string, method: string, headers: HeadersInit, body: any) => {
60
- return {
61
- "Authorization-UI2": "Bearer dsjadjalsdjalsdjalsda"
62
- }
63
- })
64
- })
65
- ```
66
-
67
- ### Add Custom Error Handlers
68
- For instance when you need to capture a not authorized error to request a new authentication flow before a new request.
69
- Returning true you can retry automatically the request, with false the request chain will be stopped.
70
58
 
71
- ```
59
+ ## Repository registration
60
+
61
+ Available registration methods:
62
+
63
+ | Method | Result |
64
+ | --- | --- |
65
+ | `addRepository<T, TKey>(...)` | full `IRepository<T, TKey>` |
66
+ | `addCommand<T, TKey>(...)` | `ICommand<T, TKey>` |
67
+ | `addQuery<T, TKey>(...)` | `IQuery<T, TKey>` |
68
+
69
+ Each registration builds one client instance and stores it under `settings.name`.
70
+
71
+ ## `RepositorySettings`
72
+
73
+ `RepositorySettings` includes:
74
+
75
+ | Property | Default | Notes |
76
+ | --- | --- | --- |
77
+ | `name` | required | Lookup key inside `RepositoryServices` |
78
+ | `uri` | `null` | Full URI override for this repository |
79
+ | `path` | `null` | Appended to the global `baseUri` when `uri` is not set |
80
+ | `case` | `PascalCase` | Stored setting; the runtime does not actively transform payload casing by itself |
81
+ | `transformer` | `undefined` | Value transformer for `T` |
82
+ | `keyTransformer` | `undefined` | Transformer for `TKey` |
83
+ | `keySeparator` | `|||` | Used when flattening non-primitive querystring keys |
84
+ | `complexKey` | `false` | Switches key-based operations from querystring to JSON body |
85
+
86
+ ## Basic example
87
+
88
+ ```typescript
89
+ import { RepositoryServices } from 'rystem.repository.client';
90
+
91
+ interface User {
92
+ id: string;
93
+ name: string;
94
+ age: number;
95
+ }
96
+
72
97
  RepositoryServices
73
- .Create("http://localhost:5000/api/")
74
- .addRepository<IperUser, string>(x => {
75
- x.name = "test";
76
- x.path = "SuperUser";
77
- x.addErrorHandler((endpoint: RepositoryEndpoint, uri: string, method: string, headers: HeadersInit, body: any, err: any) => {
78
- return (err as string).startsWith("big error");
79
- });
80
- })
81
- ```
98
+ .Create('https://api.example.com/api/')
99
+ .addRepository<User, string>(settings => {
100
+ settings.name = 'users';
101
+ settings.path = '/User';
102
+ });
82
103
 
83
- ## Usage
84
- Always with RepositoryServices class you can retrieve with
85
- the correct name the integration you setup during your startup.
104
+ const repo = RepositoryServices.Repository<User, string>('users');
86
105
 
87
- ```
88
- const repository = RepositoryServices
89
- .Repository<IperUser, string>("test");
106
+ const user = await repo.get('alice');
107
+ const created = await repo.insert('alice', { id: 'alice', name: 'Alice', age: 30 });
90
108
  ```
91
109
 
92
- You can also retrieve CQRS interfaces.
110
+ ## Hooks
93
111
 
94
- ```
95
- const command = RepositoryServices
96
- .Command<IperUser, string>("test");
97
- const query = RepositoryServices
98
- .Query<IperUser, string>("test2");
112
+ The package exports `useRepository`, `useCommand`, and `useQuery`, plus untyped `use*Pattern` helpers.
113
+
114
+ ```typescript
115
+ import { useRepository, useQuery, useCommand } from 'rystem.repository.client';
116
+
117
+ const repo = useRepository<User, string>('users');
118
+ const query = useQuery<User, string>('usersQuery');
119
+ const command = useCommand<User, string>('usersCommand');
99
120
  ```
100
121
 
101
- ## Methods
122
+ Important note: these are simple accessor functions over `RepositoryServices`. They are named like React hooks, but they do not use React state, effects, or context.
102
123
 
103
- ### Insert
124
+ ## CRUD API
104
125
 
105
- ```
106
- let response: State<IperUser, string> =
107
- await repository.insert(id, iperUser);
108
- ```
126
+ `IQuery<T, TKey>`:
109
127
 
110
- ### Update
128
+ - `get(key)` -> `Promise<T>`
129
+ - `exist(key)` -> `Promise<State<T, TKey>>`
130
+ - `query()` -> `QueryBuilder<T, TKey>`
111
131
 
112
- ```
113
- let response: State<IperUser, string> =
114
- await repository.update(id, iperUser);
115
- ```
132
+ `ICommand<T, TKey>`:
116
133
 
117
- ### Exist
134
+ - `insert(key, value)` -> `Promise<State<T, TKey>>`
135
+ - `update(key, value)` -> `Promise<State<T, TKey>>`
136
+ - `delete(key)` -> `Promise<State<T, TKey>>`
137
+ - `batch()` -> `BatchBuilder<T, TKey>`
118
138
 
119
- ```
120
- let response: State<IperUser, string> =
121
- await repository.exist(id);
122
- ```
139
+ ## Query builder
123
140
 
124
- ### Delete
141
+ Start with `repo.query()`.
125
142
 
126
- ```
127
- let response: State<IperUser, string> =
128
- await repository.delete(id);
143
+ ```typescript
144
+ const items = await repo
145
+ .query()
146
+ .where()
147
+ .select(x => x.name).equal('Alice')
148
+ .and()
149
+ .select(x => x.age).greaterThanOrEqual(18)
150
+ .build()
151
+ .orderBy(x => x.name)
152
+ .top(10)
153
+ .execute();
129
154
  ```
130
155
 
131
- ### Batch operations
156
+ Supported fluent methods:
132
157
 
133
- ```
134
- const batcher = repository.batch();
135
- batcher
136
- .addInsert(id1, iperUser1)
137
- .addUpdate(id2, iperUser2)
138
- .addDelete(id3);
139
- const batchResults: BatchResults<IperUser, string> =
140
- await batcher.execute();
141
- ```
158
+ - `where()`
159
+ - `filter(predicate: string)`
160
+ - `top(value)`
161
+ - `skip(value)`
162
+ - `orderBy(predicate)`
163
+ - `orderByDescending(predicate)`
164
+ - `thenBy(predicate)`
165
+ - `thenByDescending(predicate)`
166
+ - `execute()`
167
+ - `executeAsStream(reader, token?)`
168
+ - `count()`
169
+ - `max(predicate)`
170
+ - `min(predicate)`
171
+ - `average(predicate)`
172
+ - `sum(predicate)`
142
173
 
143
- ### Query operations
144
- - get all elements
145
- ```
146
- let queryResults = await repository.query().execute();
174
+ ## How query serialization works
175
+
176
+ The builder serializes filters as string expressions intended for the Repository Framework server.
177
+
178
+ Examples:
179
+
180
+ - `orderBy(x => x.name)` becomes a string like `_rystem => _rystem.name`
181
+ - `where().select(x => x.age).greaterThan(18)` becomes a raw lambda string
182
+
183
+ So this client works best with simple property-access lambdas.
184
+
185
+ ## Where builder
186
+
187
+ `where()` returns a `WhereBuilder<T, TKey>`.
188
+
189
+ ```typescript
190
+ const adults = await repo
191
+ .query()
192
+ .where()
193
+ .openRoundBracket()
194
+ .select(x => x.role).equal('admin')
195
+ .or()
196
+ .select(x => x.role).equal('moderator')
197
+ .closeRoundBracket()
198
+ .and()
199
+ .select(x => x.age).greaterThanOrEqual(18)
200
+ .execute();
147
201
  ```
148
- - filter as string
202
+
203
+ Comparison methods:
204
+
205
+ - `equal`
206
+ - `notEqual`
207
+ - `greaterThan`
208
+ - `greaterThanOrEqual`
209
+ - `lesserThan`
210
+ - `lesserThanOrEqual`
211
+ - `contains`
212
+ - `startsWith`
213
+ - `endsWith`
214
+
215
+ ## Batch builder
216
+
217
+ ```typescript
218
+ const results = await repo
219
+ .batch()
220
+ .addInsert('a', { id: 'a', name: 'Alice', age: 30 })
221
+ .addUpdate('b', { id: 'b', name: 'Bob', age: 31 })
222
+ .addDelete('c')
223
+ .execute();
149
224
  ```
150
- let id = "someId";
151
- let queryResults = await repository
152
- .query()
153
- .filter(`x => x.id == "${id}"`)
154
- .execute();
225
+
226
+ Supported methods:
227
+
228
+ - `addInsert(key, value)`
229
+ - `addUpdate(key, value)`
230
+ - `addDelete(key)`
231
+ - `execute()`
232
+ - `executeAsStream(reader, token?)`
233
+
234
+ ## Transformers
235
+
236
+ Use `ITransformer<T>` when the wire JSON should differ from the TypeScript model.
237
+
238
+ ```typescript
239
+ import type { ITransformer } from 'rystem.repository.client';
240
+
241
+ const userTransformer: ITransformer<User> = {
242
+ toPlain: (user) => ({
243
+ ...user,
244
+ createdAt: user.createdAt.toISOString(),
245
+ }),
246
+ fromPlain: (plain) => ({
247
+ ...plain,
248
+ createdAt: new Date(plain.createdAt),
249
+ }),
250
+ };
155
251
  ```
156
- - build a filter (similar to the previous example with addiction of ordering by ascending all retrieved elements)
252
+
253
+ Register it:
254
+
255
+ ```typescript
256
+ RepositoryServices
257
+ .Create('https://api.example.com/api/')
258
+ .addRepository<User, string>(settings => {
259
+ settings.name = 'users';
260
+ settings.path = '/User';
261
+ settings.transformer = userTransformer;
262
+ });
157
263
  ```
158
- let queryResults = await repository
159
- .query()
160
- .where()
161
- .select(x => x.id)
162
- .equal(id)
163
- .build()
164
- .orderBy(x => x.name)
165
- .execute();
264
+
265
+ ## Complex keys
266
+
267
+ For primitive keys, `get`, `exist`, and `delete` default to querystring calls like:
268
+
269
+ - `Get?key=...`
270
+ - `Exist?key=...`
271
+ - `Delete?key=...`
272
+
273
+ For complex keys, set:
274
+
275
+ ```typescript
276
+ settings.complexKey = true;
277
+ settings.keyTransformer = complexKeyTransformer;
166
278
  ```
167
- - build a filter and count all elements
279
+
280
+ Then key-based operations switch to JSON-body requests instead of querystring serialization.
281
+
282
+ This is the safer mode for object keys.
283
+
284
+ ## Header enrichers
285
+
286
+ You can register async header enrichers.
287
+
288
+ ```typescript
289
+ settings.addHeadersEnricher(async (endpoint, uri, method, headers, body) => {
290
+ const token = await getToken();
291
+ return {
292
+ ...headers as Record<string, string>,
293
+ Authorization: `Bearer ${token}`,
294
+ };
295
+ });
168
296
  ```
169
- const count = await repository
170
- .query()
171
- .where()
172
- .select(x => x.id)
173
- .equal(id)
174
- .count();
297
+
298
+ Important implementation note: enrichers are chained, but later enrichers do not overwrite headers that are already present.
299
+
300
+ ## Error handlers
301
+
302
+ You can register async error handlers.
303
+
304
+ ```typescript
305
+ settings.addErrorHandler(async (endpoint, uri, method, headers, body, err) => {
306
+ if (err?.status === 401) {
307
+ await refreshToken();
308
+ return true;
309
+ }
310
+ return false;
311
+ });
175
312
  ```
176
- - build a filter and sum a column of all elements
313
+
314
+ Important note: the runtime is clearly designed for retry-on-`true`, but the current `makeRequest(...)` implementation does not reliably perform the retry loop. Treat error handlers as interception hooks first, and verify retry behavior in your app before depending on it.
315
+
316
+ ## Response models
317
+
318
+ `Entity<T, TKey>`:
319
+
320
+ ```typescript
321
+ type Entity<T, TKey> = {
322
+ value: T;
323
+ key: TKey;
324
+ };
177
325
  ```
178
- const sum = await repository
179
- .query()
180
- .where()
181
- .select(x => x.id)
182
- .equal(id)
183
- .sum(x => x.port);
326
+
327
+ `State<T, TKey>`:
328
+
329
+ ```typescript
330
+ type State<T, TKey> = {
331
+ isOk: boolean;
332
+ entity: {
333
+ key: TKey;
334
+ value: T;
335
+ };
336
+ code: number | null;
337
+ message: string | null;
338
+ };
184
339
  ```
185
- - build a filter with greaterThanOrEqual for instance
340
+
341
+ `BatchResult<T, TKey>`:
342
+
343
+ ```typescript
344
+ type BatchResult<T, TKey> = {
345
+ code: 1 | 2 | 4;
346
+ key: TKey;
347
+ state: State<T, TKey>;
348
+ };
186
349
  ```
187
- const portGreaterThanZero = await repository
188
- .query()
189
- .where()
190
- .openRoundBracket()
191
- .select(x => x.port)
192
- .greaterThanOrEqual(0)
193
- .count();
194
- ```
195
- - same of previous but ordered by a column
196
- ```
197
- const portGreaterThanZeroOrderedByName = await repository
198
- .query()
199
- .where()
200
- .select(x => x.port)
201
- .greaterThanOrEqual(0)
202
- .build()
203
- .orderBy(x => x.name)
204
- .execute();
205
- ```
350
+
351
+ ## Streaming note
352
+
353
+ `executeAsStream(...)` exists for query and batch operations and reads streamed JSON objects from the server.
354
+
355
+ The current stream decoder is simple and works best with normal Repository Framework streamed payloads. If your payload strings themselves contain many `{` or `}` characters, test carefully.
356
+
357
+ ## When to use this package
358
+
359
+ Use it when you want:
360
+
361
+ - a lightweight TypeScript client for Repository Framework APIs
362
+ - a central registry for typed repositories
363
+ - fluent query and batch helpers without generating a custom SDK first
364
+
365
+ If you want generated typed bootstrap and transformers from your C# models, pair it with `Rystem.RepositoryFramework.TypescriptGenerator`.
package/package.json CHANGED
@@ -1,9 +1,14 @@
1
1
  {
2
2
  "name": "rystem.repository.client",
3
- "version": "0.2.7",
3
+ "version": "10.1.0-beta.3",
4
4
  "author": "Alessandro Rapiti <alessandro.rapiti44@gmail.com>",
5
5
  "license": "MIT",
6
6
  "description": "It can simplify the integration with rystem repository server.",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/KeyserDSoze/Rystem.git",
10
+ "directory": "src/Repository/repositoryframework.api.client.typescript/src/rystem"
11
+ },
7
12
  "main": "./lib/index.js",
8
13
  "types": "./lib/index.d.ts",
9
14
  "devDependencies": {
@@ -1,27 +0,0 @@
1
- import { CancellationToken } from "typescript";
2
- import { IRepository } from "../interfaces/IRepository";
3
- import { RepositoryEndpoint } from "../models/RepositoryEndpoint";
4
- import { State } from "../models/State";
5
- import { RepositorySettings } from "../servicecollection/RepositorySettings";
6
- import { BatchBuilder } from "./batch/BatchBuilder";
7
- import { QueryBuilder } from "./query/QueryBuilder";
8
- export declare class Repository<T, TKey> implements IRepository<T, TKey> {
9
- private baseUri;
10
- private settings;
11
- constructor(baseUri: string | null, settings: RepositorySettings);
12
- private serializeRequestBody;
13
- private transformResponse;
14
- makeRequest<TResponse>(endpoint: RepositoryEndpoint, path: string, method: string, body?: any, bodyIsKey?: boolean, skipSerialization?: boolean, skipSerializationOnResponse?: boolean, headers?: HeadersInit): Promise<TResponse>;
15
- makeRequestAsStream<TResponse>(endpoint: RepositoryEndpoint, path: string, method: string, reader: (entity: TResponse) => void, body?: any, bodyIsKey?: boolean, skipSerialization?: boolean, skipSerializationOnResponse?: boolean, headers?: HeadersInit, cancellationToken?: CancellationToken | null): Promise<Array<TResponse>>;
16
- private isPrimitive;
17
- private objectToString;
18
- private keyToPlainForQuery;
19
- get(key: TKey): Promise<T>;
20
- insert(key: TKey, value: T): Promise<State<T, TKey>>;
21
- update(key: TKey, value: T): Promise<State<T, TKey>>;
22
- exist(key: TKey): Promise<State<T, TKey>>;
23
- delete(key: TKey): Promise<State<T, TKey>>;
24
- batch(): BatchBuilder<T, TKey>;
25
- query(): QueryBuilder<T, TKey>;
26
- static predicateAsString<T>(predicate: (value: T) => any): string;
27
- }