@weclapp/sdk 2.0.0-dev.25 → 2.0.0-dev.28

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 (3) hide show
  1. package/README.md +371 -15
  2. package/dist/cli.js +19 -10
  3. package/package.json +2 -4
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
 
@@ -38,21 +46,369 @@ This way, every time someone installs or updates dependencies, the SDK is genera
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.
180
+
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
+
209
+ 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.
210
+
211
+ A service of an entity has in general the following base function:
212
+
213
+ some: // get entity data
214
+ create: // creates a entity
215
+ count: // get the count of entities
216
+ remove: // deletes a entity
217
+ update: // updates a entity
218
+
219
+ In addition there are some custom endpoint functions. The generated PartyService is shown below as an example:
220
+
221
+ ```ts
222
+ interface PartyService {
223
+ some: PartyService_Some;
224
+ create: PartyService_Create;
225
+ count: PartyService_Count;
226
+ remove: PartyService_Remove;
227
+ update: PartyService_Update;
228
+ postCreatePublicPageById: PartyService_PostCreatePublicPageById;
229
+ getDownloadImageById: PartyService_GetDownloadImageById;
230
+ getTopPurchaseArticlesById: PartyService_GetTopPurchaseArticlesById;
231
+ getTopSalesArticlesById: PartyService_GetTopSalesArticlesById;
232
+ postUploadImageById: PartyService_PostUploadImageById;
233
+ }
234
+ ```
235
+
236
+ ## Comparison
237
+
238
+ ```ts
239
+ import { PartyType, setGlobalConfig, wServices } from "@weclapp/sdk";
240
+
241
+ setGlobalConfig({
242
+ domain: "company.weclapp.com",
243
+ secure: true,
244
+ });
245
+
246
+ // to get the count of parties via service
247
+ const serviceN = await wServices["party"].count();
248
+
249
+ // to get the count of parties via raw
250
+ const rawN = await raw(undefined, "/party/count");
251
+
252
+ // to get all parties via service
253
+ const partiesService = await wServices["party"].some();
254
+
255
+ // to get all parties via raw
256
+ const partiesRaw = await raw(undefined, "/party");
257
+
258
+ // to create a party via service
259
+ const contact = await wServices["party"].create({
260
+ partyType: PartyType.PERSON,
261
+ lastName: "Mueller",
262
+ }); // the returned object is already typed as Party
263
+
264
+ // to create a party via raw
265
+ const contactRaw = await await raw(undefined, "/party", {
266
+ // the returned object has the type any.
267
+ method: "POST",
268
+ body: { partyType: PartyType.PERSON, lastName: "Mueller" },
269
+ });
270
+
271
+ // to delete a party via service
272
+ await wServices["party"].remove(contact.id);
273
+
274
+ // to delete a party via raw
275
+ if (contactRaw && typeof contactRaw.id === "string") {
276
+ await raw(undefined, `/party/id/${contactRaw.id}`, {
277
+ method: "DELETE",
278
+ });
279
+ }
280
+ ```
281
+
282
+ ## Service request arguments
283
+
284
+ ### Filtering
285
+
286
+ With the some and count functions you can filter the requested data.
287
+
288
+ ```ts
289
+ wServices["article"].some({
290
+ filter: {
291
+ name: { EQ: "toy 1" },
292
+ articleNumber: { EQ: "12345" },
293
+ },
294
+ });
295
+ ```
296
+
297
+ The SDK makes an AND operator between the properties. So this equivalent to the follwing expression:
298
+
299
+ name EQ 'toy 1' AND articleNumber EQ '12345'.
300
+
301
+ If you want an OR operator you have to set an array in the or property:
302
+
303
+ ```ts
304
+ wServices["article"].some({
305
+ or: [
306
+ {
307
+ name: { EQ: "toy 1" },
308
+ articleNumber: { EQ: "12345" },
309
+ },
310
+ ],
311
+ });
312
+ ```
313
+
314
+ The above example is the equivalent of the expression
315
+
316
+ name EQ 'toy 1' OR articleNumber EQ '12345'.
317
+
318
+ To combine OR and AND clauses, you can also group OR expressions by adding several objects to the array:
319
+
320
+ ```ts
321
+ wServices["article"].some({
322
+ or: [
323
+ {
324
+ name: { EQ: "toy 1" },
325
+ articleNumber: { EQ: "12345" },
326
+ },
327
+ {
328
+ batchNumberRequired: { EQ: true },
329
+ },
330
+ ],
331
+ });
332
+ ```
45
333
 
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` |
334
+ This is evaluated to:
335
+ (name EQ 'toy 1' OR articleNumber EQ '12345') AND batchNumberRequired EQ true
336
+
337
+ ### Where filter
338
+
339
+ <strong>Warning: This is still a beta feature.</strong>
340
+
341
+ It is also possible to specify complex filter expressions that can combine multiple conditions and express relations between properties:
342
+
343
+ ```ts
344
+ wServices["article"].some({
345
+ where: {
346
+ AND: [
347
+ {
348
+ OR: [
349
+ { name: { LIKE: "%test%", lower: true } },
350
+ { articleNumber: { LIKE: "%345%" } },
351
+ ],
352
+ },
353
+ { batchNumberRequired: { EQ: true } },
354
+ ],
355
+ },
356
+ });
357
+ ```
358
+
359
+ "where" parameters are ANDed with other filter parameters.
360
+
361
+ ### Sort
362
+
363
+ You can sort your requested data with an array properties.
364
+
365
+ ```ts
366
+ wServices["article"].some({
367
+ sort: [{ name: "asc" }, { minimumPurchaseQuantity: "desc" }],
368
+ });
369
+ ```
370
+
371
+ Sort by name (ascending) and then minimumPurchaseQuantity descending.
372
+
373
+ ### Pagination
374
+
375
+ 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.
376
+
377
+ ```ts
378
+ wServices["article"].some({
379
+ pagination: {
380
+ page: 2,
381
+ pageSize: 10,
382
+ },
383
+ });
384
+ ```
385
+
386
+ This returns the first 10 articles of the second page.
387
+
388
+ ### Select
389
+
390
+ With the select option you can fetch specific subset of properties:
391
+
392
+ ```ts
393
+ wServices["article"].some({
394
+ select: { articleNumber: true },
395
+ });
396
+ ```
397
+
398
+ This only returns the articleNumber property of all articles.
399
+
400
+ # Enums
401
+
402
+ 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:
403
+
404
+ ```ts
405
+ wServices["article"].some({
406
+ filter: {
407
+ articleType: { EQ: ArticleType.STORABLE },
408
+ },
409
+ });
410
+ ```
55
411
 
56
- ### Contributing
412
+ # Contributing
57
413
 
58
414
  Check out the [contributing guidelines](.github/CONTRIBUTING.md).
package/dist/cli.js CHANGED
@@ -65,7 +65,10 @@ const bundle = async (workingDirectory, target) => {
65
65
  const bundles = {
66
66
  [Target.BROWSER_PROMISES]: () => ({
67
67
  input: src("index.ts"),
68
- plugins: [ts({ tsconfig, declarationDir: dist() }), terser()],
68
+ plugins: [
69
+ ts({ tsconfig, declarationDir: dist(), filterRoot: src() }),
70
+ terser(),
71
+ ],
69
72
  output: [
70
73
  generateOutput({
71
74
  file: dist("index.js"),
@@ -75,7 +78,10 @@ const bundle = async (workingDirectory, target) => {
75
78
  }),
76
79
  [Target.BROWSER_RX]: () => ({
77
80
  input: src("index.ts"),
78
- plugins: [ts({ tsconfig, declarationDir: dist() }), terser()],
81
+ plugins: [
82
+ ts({ tsconfig, declarationDir: dist(), filterRoot: src() }),
83
+ terser(),
84
+ ],
79
85
  external: ["rxjs"],
80
86
  output: [
81
87
  generateOutput({
@@ -87,13 +93,19 @@ const bundle = async (workingDirectory, target) => {
87
93
  }),
88
94
  [Target.NODE_PROMISES]: () => ({
89
95
  input: src("index.ts"),
90
- plugins: [ts({ tsconfig, declarationDir: dist() }), terser()],
96
+ plugins: [
97
+ ts({ tsconfig, declarationDir: dist(), filterRoot: src() }),
98
+ terser(),
99
+ ],
91
100
  external: ["node-fetch", "url"],
92
101
  output: generateNodeOutput(),
93
102
  }),
94
103
  [Target.NODE_RX]: () => ({
95
104
  input: src("index.ts"),
96
- plugins: [ts({ tsconfig, declarationDir: dist() }), terser()],
105
+ plugins: [
106
+ ts({ tsconfig, declarationDir: dist(), filterRoot: src() }),
107
+ terser(),
108
+ ],
97
109
  external: ["node-fetch", "url", "rxjs"],
98
110
  output: generateNodeOutput(),
99
111
  }),
@@ -1327,11 +1339,6 @@ const cli = async () => {
1327
1339
  describe: "Specify the target platform",
1328
1340
  type: "string",
1329
1341
  choices: ["browser", "browser.rx", "node", "node.rx"],
1330
- })
1331
- .option("d", {
1332
- alias: "deprecated",
1333
- describe: "Include deprecated functions and services",
1334
- type: "boolean",
1335
1342
  })
1336
1343
  .epilog(`Copyright ${new Date().getFullYear()} weclapp GmbH`);
1337
1344
  if (argv.fromEnv) {
@@ -1413,12 +1420,14 @@ void (async () => {
1413
1420
  // Write swagger.json file
1414
1421
  await writeFile(await workingDirPath("openapi.json"), JSON.stringify(doc, null, 2));
1415
1422
  logger.infoLn(`Generate sdk (target: ${options.target})`);
1416
- // Generate and write SDK
1423
+ // Generate and write SDK (index.ts)
1417
1424
  const sdk = generate(doc, options);
1418
1425
  await writeFile(await workingDirPath("src", "index.ts"), sdk.trim() + "\n");
1419
1426
  // Bundle and write SDK
1420
1427
  logger.infoLn("Bundle... (this may take some time)");
1421
1428
  await bundle(workingDir, options.target);
1429
+ // Remove index.ts (only bundle is required)
1430
+ await rm(await workingDirPath("src"), { recursive: true, force: true });
1422
1431
  if (useCache) {
1423
1432
  // Copy SDK to cache
1424
1433
  logger.successLn(`Caching SDK: (${cachedSdkDir})`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weclapp/sdk",
3
- "version": "2.0.0-dev.25",
3
+ "version": "2.0.0-dev.28",
4
4
  "description": "SDK generator based on a weclapp api swagger file",
5
5
  "author": "weclapp",
6
6
  "sideEffects": false,
@@ -25,14 +25,12 @@
25
25
  "npm": ">=10"
26
26
  },
27
27
  "types": "./sdk/dist/index.d.ts",
28
- "main": "./sdk/dist/index.cjs",
29
28
  "module": "./sdk/dist/index.js",
30
29
  "type": "module",
31
30
  "exports": {
32
31
  ".": {
33
32
  "types": "./sdk/dist/index.d.ts",
34
- "import": "./sdk/dist/index.js",
35
- "require": "./sdk/dist/index.cjs"
33
+ "import": "./sdk/dist/index.js"
36
34
  }
37
35
  },
38
36
  "scripts": {