@weclapp/sdk 2.0.0-dev.24 → 2.0.0-dev.26

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/README.md CHANGED
@@ -1,17 +1,25 @@
1
1
  <br/>
2
2
 
3
3
  <div align="center">
4
- <h3>weclapp sdk generator</h3>
4
+ <h1>weclapp sdk generator</h1>
5
5
  </div>
6
6
 
7
7
  <br/>
8
8
 
9
- ### Getting started
9
+ # Introduction
10
+
11
+ This is an SDK generator, it will take an [`openapi.json`](https://swagger.io/specification/) from [weclapp](https://weclapp.com/) and build services and typescript types according to the entities defined in it. Each service is responsible for a _single_ entity. Every service contains all functions available for this
12
+ entity, this may include functions such as `update`, `remove`, `some` and many more. With these functions you can send requests to your weclapp system to get data or manipulate them.
13
+
14
+ An entity is a resource with properties in weclapp. This can be an article, a contract or a quotation. The SDK generates a well-defined typescript type for each entity and its property. In this way, the SDK makes it possible to work with the data retrieved via the API in a type-safe manner.
15
+
16
+ Check out [generated types and utilities](#generated-types-and-utilities) for more possibilities!
10
17
 
11
- This is an SDK generator, it will take an [`openapi.json`](https://swagger.io/specification/) from [weclapp](https://weclapp.com/) and build services and types according to the entities defined in it.
12
18
  What's being generated depends on the weclapp version you're using.
13
19
 
14
- The SDK generator requires the current or LTS version of nodejs, as well as npm v9 or v8.
20
+ # Getting started
21
+
22
+ The SDK generator requires the current or LTS version of nodejs, as well as npm v10.
15
23
 
16
24
  You can install the generator via the package manager of your choice:
17
25
 
@@ -31,28 +39,343 @@ This way, every time someone installs or updates dependencies, the SDK is genera
31
39
  ```json5
32
40
  {
33
41
  // in your package.json
34
- "scripts": {
42
+ scripts: {
35
43
  "sdk:generate": "build-weclapp-sdk company.weclapp.com --key [your api key] --cache --target browser",
36
- "postinstall": "npm run sdk:generate",
37
- }
44
+ postinstall: "npm run sdk:generate",
45
+ },
38
46
  }
39
47
  ```
40
48
 
49
+ ## Available flags
50
+
51
+ | Flag | Description | Value / Type |
52
+ | --------------------- | ----------------------------------------------------------------------------- | -------------------------------------------- |
53
+ | `--cache` / `-c` | Extra query params when fetching the openapi.json from a server. | `boolean` |
54
+ | `--deprecated` / `-d` | Include deprecated functions and services. | `boolean` |
55
+ | `--from-env` / `-e` | Use env variables `WECLAPP_BACKEND_URL` and `WECLAPP_API_KEY` as credentials. | `boolean` |
56
+ | `--generate-unique` | Generate additional `.unique` functions. | `boolean` |
57
+ | `--help` / `-h` | Show help. | `boolean` |
58
+ | `--key` / `-k` | API Key in case of using a remote. | `string` |
59
+ | `--target` / `-t` | Specify the target platform. | `browser`, `browser.rx`, `node` or `node.rx` |
60
+ | `--query` / `-q` | Extra query params when fetching the openapi.json from a server | `string` |
61
+ | `--version` / `-v` | Show version of SDK. | `boolean` |
62
+
41
63
  After that, you can import the sdk via `@weclapp/sdk`.
42
64
  Check out the [docs](docs) for how the generated SDK looks like and how to use it!
43
65
 
44
- ### Available flags
66
+ # Initialization
67
+
68
+ To initialize a service a `ServiceConfig` is needed, you can specify a global config in case you don't want to pass the config every time to the service you
69
+ want to use manually. If you pass an empty object as ServiceConfig the [location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) will be used to get the domain and the protocol (secure config option).
70
+
71
+ ## The Service Configuration
72
+
73
+ The configuration looks like the following (taken from [globalConfig.ts](/src/generator/01-base/static/globalConfig.ts.txt)):
74
+
75
+ ```ts
76
+ interface ServiceConfig {
77
+ // Your API-Key, this is optional in the sense of if you omit this, and you're in a browser, the
78
+ // cookie-authentication (include-credentials) will be used.
79
+ key?: string;
80
+
81
+ // Your domain, if omitted location.host will be used.
82
+ domain?: string;
83
+
84
+ // If you want to use https, defaults to false.
85
+ secure?: boolean;
86
+
87
+ // If you want that some and count requests are bundled into multi requests.
88
+ multiRequest?: boolean;
89
+
90
+ // If you want that the ignoreMissingProperties parameter to be set for each post request.
91
+ ignoreMissingProperties?: boolean;
92
+
93
+ // Optional request/response interceptors.
94
+ interceptors?: {
95
+ // Takes the generated request, you can either return a new request,
96
+ // a response (which will be taken as "the" response) or nothing.
97
+ // The payload contains the raw input generated by the SDK.
98
+ request?: (
99
+ request: Request,
100
+ payload: RequestPayload,
101
+ ) => Request | Response | void | Promise<Request | Response | void>;
102
+
103
+ // Takes the response. This can either be the one from the server or an
104
+ // artificially-crafted one by the request interceptor.
105
+ response?: (
106
+ response: Response,
107
+ ) => Response | void | Promise<Response | void>;
108
+ };
109
+ }
110
+ ```
111
+
112
+ ### Usage
113
+
114
+ There are three ways of accessing a service through the SDK:
115
+
116
+ #### Using a Global Config
117
+
118
+ ```ts
119
+ import { setGlobalConfig, partyService } from "@weclapp/sdk";
120
+
121
+ setGlobalConfig({
122
+ key: "mykey",
123
+ domain: "myweclapp.com",
124
+ });
125
+
126
+ const party = partyService();
127
+
128
+ console.log(`Total amount of parties: ${await party.count()}`);
129
+ ```
130
+
131
+ #### Using a Config per Service
132
+
133
+ ```ts
134
+ import { partyService } from "@weclapp/sdk";
135
+
136
+ const party = partyService({
137
+ key: "mykey",
138
+ domain: "myweclapp.com",
139
+ });
140
+
141
+ console.log(`Total amount of parties: ${await party.count()}`);
142
+ ```
143
+
144
+ > If a global config is specified as well the one passed to the service will **always** take precedence over the global one!
145
+
146
+ #### Using the raw function
147
+
148
+ The raw function can be used if none of the provided function suits your needs. The services use the raw function, which makes the API requests via [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API):
149
+
150
+ ```ts
151
+ import { raw } from '@weclapp/sdk';
152
+
153
+ const result = await raw(
154
+ cfg: ServiceConfig | undefined = globalConfig,
155
+ endpoint: string,
156
+ payload: RequestPayload = {}
157
+ );
158
+ ```
159
+
160
+ where `RequestPayload` looks like this:
161
+
162
+ ```ts
163
+ interface RequestPayload {
164
+ method?: RequestPayloadMethod; // Optional request method, default is GET
165
+ query?: Record<string, any>; // Optional query parameters
166
+ body?: any; // Optional body
167
+
168
+ // In case the response body is an object with a result-prop the value will be extracted
169
+ unwrap?: boolean;
170
+
171
+ // If in any case the response should be returned as a blob.
172
+ // Required for download endpoints as json will be parsed automatically.
173
+ forceBlob?: boolean;
174
+ }
175
+ ```
176
+
177
+ # Generated types and utilities
178
+
179
+ The generator generates various utilities that can be used to integrate it in a generic way into your app.
45
180
 
46
- | Flag | Description | Value / Type |
47
- |---------------------|-------------------------------------------------------------------------------|----------------------------------------------|
48
- | `--help` / `-h` | Show help. | `boolean` |
49
- | `--version` / `-v` | Show version of SDK. | `boolean` |
50
- | `--key` / `-k` | API Key in case of using a remote. | `string` |
51
- | `--cache` / `-c` | Extra query params when fetching the openapi.json from a server. | `boolean` |
52
- | `--from-env` / `-e` | Use env variables `WECLAPP_BACKEND_URL` and `WECLAPP_API_KEY` as credentials. | `boolean` |
53
- | `--target` / `-t` | Specify the target platform. | `browser`, `browser.rx`, `node` or `node.rx` |
54
- | `--generate-unique` | Generate additional `.unique` functions. | `boolean` |
181
+ ## Exported constants
182
+
183
+ | Constant | Description |
184
+ | --------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
185
+ | `wServiceWith[method]Names` | An array of services (strings) that have this function. Example: `wServiceWithUpdateNames`. |
186
+ | `wCustomValueServiceNames` | An array of services (strings) that work with `CustomValue`. |
187
+ | `wEnums` | Object with the name of the enum as key and the corresponding enum as value. |
188
+ | `wServiceFactories` | Object with all services where the name is the key and the value a function taking a config and returning the service. |
189
+ | `wServices` | Object with all services where the name is the key and the value the service (that is using the global config). |
190
+ | `wEntityProperties` | Object with all entity names as key and properties including the type and format as value. |
191
+
192
+ ## Exported types
193
+
194
+ | Type | Description | Type guards available? |
195
+ | ----------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------- |
196
+ | `WServiceWith[method]` | A tuple of strings with the names of the services that contain this function. Example: `WServiceWithSome`. | Yes, for example `isWServiceWithSome` |
197
+ | `WServicesWith[method]` | An interface with the service-name as key and corresponding service as value. Example: `WServicesWithSome`. | |
198
+ | `WCustomValueService` | Tuple of services (strings) that work with `CustomValue`. | Yes: `isWCustomValueService` |
199
+ | `WEnums` | Type of `wEnums`. | |
200
+ | `WEnum` | All keys of `WEnums`. | |
201
+ | `WEntities` | Interface will all entities from weclapp with their name as key and type as value | |
202
+ | `WEntity` | All keys of `WEntities`. | |
203
+ | `WServiceFactories` | Type of `wServiceFactories`. | |
204
+ | `WServices` | Type of `wServices`. | |
205
+ | `WEntityProperties` | Generalized type of `wEntityProperties`. | |
206
+
207
+ # Services and Raw in depth
208
+ As already described above, the api endpoints can be requested via services or the raw function. The advantage of wServices over the raw function is that all endpoints of the entities are available as functions and these functions are typed. This makes it easier to work with the data provided via the weclapp API.
209
+
210
+ A service of an entity has in general the following base function:
211
+
212
+ some: // get entity data
213
+ create: // creates a entity
214
+ count: // get the count of entities
215
+ remove: // deletes a entity
216
+ update: // updates a entity
217
+
218
+ In addition there are some custom endpoint functions. The generated PartyService is shown below as an example:
219
+ ```ts
220
+ interface PartyService {
221
+ some: PartyService_Some;
222
+ create: PartyService_Create;
223
+ count: PartyService_Count;
224
+ remove: PartyService_Remove;
225
+ update: PartyService_Update;
226
+ postCreatePublicPageById: PartyService_PostCreatePublicPageById;
227
+ getDownloadImageById: PartyService_GetDownloadImageById;
228
+ getTopPurchaseArticlesById: PartyService_GetTopPurchaseArticlesById;
229
+ getTopSalesArticlesById: PartyService_GetTopSalesArticlesById;
230
+ postUploadImageById: PartyService_PostUploadImageById;
231
+ }
232
+ ```
233
+
234
+ ## Comparison
235
+ ```ts
236
+ import { PartyType, setGlobalConfig, wServices } from '@weclapp/sdk';
237
+
238
+ setGlobalConfig({
239
+ domain: 'company.weclapp.com',
240
+ secure: true
241
+ });
242
+
243
+ // to get the count of parties via service
244
+ const serviceN = await wServices['party'].count();
245
+
246
+ // to get the count of parties via raw
247
+ const rawN = await raw(undefined, '/party/count');
248
+
249
+ // to get all parties via service
250
+ const partiesService = await wServices['party'].some();
251
+
252
+ // to get all parties via raw
253
+ const partiesRaw = await raw(undefined, '/party');
254
+
255
+ // to create a party via service
256
+ const contact = await wServices['party'].create({ partyType: PartyType.PERSON, lastName: 'Mueller' }); // the returned object is already typed as Party
257
+
258
+ // to create a party via raw
259
+ const contactRaw = await await raw(undefined, '/party', { // the returned object has the type any.
260
+ method: 'POST',
261
+ body: { partyType: PartyType.PERSON, lastName: 'Mueller' }
262
+ });
263
+
264
+ // to delete a party via service
265
+ await wServices['party'].remove(contact.id);
266
+
267
+ // to delete a party via raw
268
+ if (contactRaw && typeof contactRaw.id === 'string') {
269
+ await raw(undefined, `/party/id/${contactRaw.id}`, {
270
+ method: 'DELETE'
271
+ });
272
+ }
273
+ ```
274
+
275
+ ## Service request arguments
276
+ ### Filtering
277
+ With the some and count functions you can filter the requested data.
278
+ ```ts
279
+ wServices['article'].some({
280
+ filter: {
281
+ name: { EQ: 'toy 1'},
282
+ articleNumber: { EQ: '12345' }
283
+ }
284
+ });
285
+ ```
286
+ The SDK makes an AND operator between the properties. So this equivalent to the follwing expression:
287
+
288
+ name EQ 'toy 1' AND articleNumber EQ '12345'.
289
+
290
+ If you want an OR operator you have to set an array in the or property:
291
+ ```ts
292
+ wServices['article'].some({
293
+ or: [
294
+ {
295
+ name: { EQ: 'toy 1'},
296
+ articleNumber: { EQ: '12345' }
297
+ }
298
+ ]
299
+ });
300
+ ```
301
+ The above example is the equivalent of the expression
302
+
303
+ name EQ 'toy 1' OR articleNumber EQ '12345'.
304
+
305
+ To combine OR and AND clauses, you can also group OR expressions by adding several objects to the array:
306
+ ```ts
307
+ wServices['article'].some({
308
+ or: [
309
+ {
310
+ name: { EQ: 'toy 1'},
311
+ articleNumber: { EQ: '12345' }
312
+ },
313
+ {
314
+ batchNumberRequired: { EQ: true}
315
+ }
316
+ ]
317
+ })
318
+ ```
319
+ This is evaluated to:
320
+ (name EQ 'toy 1' OR articleNumber EQ '12345') AND batchNumberRequired EQ true
321
+
322
+ ### Where filter
323
+ <strong>Warning: This is still a beta feature.</strong>
324
+
325
+ It is also possible to specify complex filter expressions that can combine multiple conditions and express relations between properties:
326
+ ```ts
327
+ wServices['article'].some({
328
+ where: {
329
+ AND: [
330
+ { OR: [{ name: { LIKE: '%test%', lower: true } }, { articleNumber: { LIKE: '%345%' } }] },
331
+ { batchNumberRequired: { EQ: true } }
332
+ ]
333
+ }
334
+ });
335
+ ```
336
+ "where" parameters are ANDed with other filter parameters.
337
+
338
+ ### Sort
339
+ You can sort your requested data with an array properties.
340
+ ```ts
341
+ wServices['article'].some({
342
+ sort: [{ name: 'asc' }, { minimumPurchaseQuantity: 'desc' }]
343
+ });
344
+ ```
345
+ Sort by name (ascending) and then minimumPurchaseQuantity descending.
346
+
347
+ ### Pagination
348
+ By default the API returns only the first 100 entities. You can increase the size of one response to the maximum of 1000. To get the next 1000 entities you have increase the page number.
349
+ ```ts
350
+ wServices['article'].some({
351
+ pagination: {
352
+ page: 2,
353
+ pageSize: 10
354
+ }
355
+ });
356
+ ```
357
+ This returns the first 10 articles of the second page.
358
+
359
+ ### Select
360
+ With the select option you can fetch specific subset of properties:
361
+ ```ts
362
+ wServices['article'].some({
363
+ select: { articleNumber: true }
364
+ });
365
+ ```
366
+ This only returns the articleNumber property of all articles.
367
+
368
+ # Enums
369
+
370
+ The generated enums are a good posibility to check if an entity is of a specific type. For example, you can get all articles of a certain article type:
371
+ ```ts
372
+ wServices['article'].some({
373
+ filter: {
374
+ articleType: { EQ: ArticleType.STORABLE }
375
+ }
376
+ });
377
+ ```
55
378
 
56
- ### Contributing
379
+ # Contributing
57
380
 
58
- Check out the [contributing guidelines](.github/CONTRIBUTING.md).
381
+ Check out the [contributing guidelines](.github/CONTRIBUTING.md).
package/bin/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import '../dist/cli.js';
2
+ import "../dist/cli.js";