oip-common 0.0.33 → 0.0.36

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/index.d.ts CHANGED
@@ -695,6 +695,12 @@ interface FullRequestParams extends Omit<RequestInit, "body"> {
695
695
  cancelToken?: CancelToken;
696
696
  }
697
697
  type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
698
+ interface ApiConfig<SecurityDataType = unknown> {
699
+ baseUrl?: string;
700
+ baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
701
+ securityWorker?: (securityData: SecurityDataType | null) => Promise<RequestParams | void> | RequestParams | void;
702
+ customFetch?: typeof fetch;
703
+ }
698
704
  type CancelToken = Symbol | string | number;
699
705
  declare enum ContentType {
700
706
  Json = "application/json",
@@ -704,15 +710,13 @@ declare enum ContentType {
704
710
  Text = "text/plain"
705
711
  }
706
712
  declare class HttpClient<SecurityDataType = unknown> {
707
- protected securityService: SecurityService;
708
- protected layoutService: LayoutService;
709
713
  baseUrl: string;
710
714
  private securityData;
711
715
  private securityWorker?;
712
716
  private abortControllers;
713
717
  private customFetch;
714
718
  private baseApiParams;
715
- constructor();
719
+ constructor(apiConfig?: ApiConfig<SecurityDataType>);
716
720
  setSecurityData: (data: SecurityDataType | null) => void;
717
721
  protected encodeQueryParam(key: string, value: any): string;
718
722
  protected addQueryParam(query: QueryParamsType, key: string): string;
package/package.json CHANGED
@@ -1,15 +1,12 @@
1
1
  {
2
2
  "name": "oip-common",
3
- "version": "0.0.33",
3
+ "version": "0.0.36",
4
4
  "description": "A template for cross-platform web applications based on sakai-ng and primeNG",
5
5
  "main": "index.js",
6
6
  "keywords": [
7
7
  "oip",
8
8
  "template"
9
9
  ],
10
- "bin": {
11
- "oip-generate-api": "./dist/oip-common/scripts/generate-api.mjs"
12
- },
13
10
  "author": "Igor Tyulyakov aka g101k",
14
11
  "license": "MIT",
15
12
  "repository": {
@@ -1,163 +1,147 @@
1
- #!/usr/bin/env node
2
-
3
- import fs from "node:fs";
4
- import path from "node:path";
5
- import {generateApi, generateTemplates} from "swagger-typescript-api";
6
- import {ArgumentParser} from 'argparse';
7
-
8
- const parser = new ArgumentParser({
9
- description: 'Argparse example'
10
- });
11
-
12
- parser.add_argument('-o', '--output', {help: 'Output path'});
13
- parser.add_argument('-i', '--input', {help: 'Input swagger file path'});
14
- parser.add_argument('-t', '--templates', {help: 'Templates'});
15
- parser.add_argument('-d', '--data-contract-prefix', {help: 'Data Contract Prefix'});
16
- parser.add_argument('-c', '--use-common-client', {action: 'store_true', help: 'Use common http client'});
17
-
18
- let a = parser.parse_args();
19
- a.data_contract_prefix ??= "";
20
-
21
- console.log(a);
22
- /* NOTE: all fields are optional expect one of `input`, `url`, `spec` */
23
-
24
- let config = {
25
- input: path.resolve(process.cwd(), a.input),
26
- templates: path.resolve(process.cwd(), a.templates),
27
- httpClientType: "fetch", // or "fetch"
28
- defaultResponseAsSuccess: false,
29
- generateClient: true,
30
- useCommonClient: a.use_common_client,
31
- generateRouteTypes: false,
32
- generateResponses: true,
33
- toJS: false,
34
- extractRequestParams: true,
35
- extractRequestBody: true,
36
- extractEnums: true,
37
- unwrapResponseData: true,
38
- modular: true,
39
- prettier: {
40
- printWidth: 120,
41
- tabWidth: 2,
42
- trailingComma: "all",
43
- parser: "typescript",
44
- },
45
- defaultResponseType: "void",
46
- singleHttpClient: false,
47
- cleanOutput: false,
48
- enumNamesAsValues: false,
49
- moduleNameFirstTag: true,
50
- generateUnionEnums: false,
51
- dataContractPrefix: a.data_contract_prefix,
52
- typePrefix: "",
53
- typeSuffix: "",
54
- enumKeyPrefix: "",
55
- enumKeySuffix: "",
56
- addReadonly: false,
57
- sortTypes: false,
58
- sortRouters: false,
59
- extractingOptions: {
60
- requestBodySuffix: ["Payload", "Body", "Input"],
61
- requestParamsSuffix: ["Params"],
62
- responseBodySuffix: ["Data", "Result", "Output"],
63
- responseErrorSuffix: [
64
- "Error",
65
- "Fail",
66
- "Fails",
67
- "ErrorData",
68
- "HttpError",
69
- "BadResponse",
70
- ],
71
- },
72
- /** allow to generate extra files based with this extra templates, see more below */
73
- extraTemplates: [],
74
- anotherArrayType: false,
75
- fixInvalidTypeNamePrefix: "Type",
76
- fixInvalidEnumKeyPrefix: "Value",
77
- codeGenConstructs: (constructs) => ({
78
- ...constructs,
79
- RecordType: (key, value) => `MyRecord<key, value>`,
80
- }),
81
- primitiveTypeConstructs: (constructs) => ({
82
- ...constructs,
83
- string: {
84
- "date-time": "Date",
85
- },
86
- }),
87
- hooks: {
88
- onCreateComponent: (component) => {
89
- },
90
- onCreateRequestParams: (rawType) => {
91
- },
92
- onCreateRoute: (routeData) => {
93
- },
94
- onCreateRouteName: (routeNameInfo, rawRouteInfo) => {
95
- if (routeNameInfo.usage.startsWith(rawRouteInfo.moduleName)) {
96
- const str = routeNameInfo.usage.substring(rawRouteInfo.moduleName.length);
97
- routeNameInfo.usage = str[0].toLowerCase() + str.slice(1);
98
- routeNameInfo.original = routeNameInfo.usage;
99
- }
100
- return routeNameInfo;
101
- },
102
- onFormatRouteName: (routeInfo, templateRouteName) => {
103
- },
104
- onFormatTypeName: (typeName, rawTypeName, schemaType) => {
105
- },
106
- onInit: (configuration) => {
107
- },
108
- onPreParseSchema: (originalSchema, typeName, schemaType) => {
109
- },
110
- onParseSchema: (originalSchema, parsedSchema) => {
111
- },
112
- onPrepareConfig: (currentConfiguration) => {
113
- },
114
- },
115
- }
116
- const toKebabCase = (str) =>
117
- str &&
118
- str
119
- .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
120
- .map(x => x.toLowerCase())
121
- .join('-');
122
-
123
- generateApi(config)
124
- .then(async ({files, configuration}) => {
125
- for (const f of files) {
126
- if (f.fileContent) {
127
- if (f.fileName === 'http-client')
128
- continue;
129
- let dir = path.join(process.cwd(), a.output);
130
- if (!fs.existsSync(dir))
131
- fs.mkdirSync(dir);
132
-
133
- if (f.fileName === 'data-contracts') {
134
- f.fileName = config.dataContractPrefix + f.fileName;
135
- } else if (f.fileName.endsWith('http-client')) {
136
- // do nothing
137
- } else {
138
- f.fileName = `${toKebabCase(f.fileName)}.api`;
139
- }
140
-
141
- const absolutePath = path.join(dir, `${f.fileName}${f.fileExtension}`);
142
- fs.writeFile(absolutePath, f.fileContent, (err) => {
143
- if (err) {
144
- console.log(err);
145
- } else {
146
- console.log(`File create: ${f.fileName}${f.fileExtension}`);
147
- }
148
- });
149
- }
150
- }
151
- })
152
- .catch((e) => console.error(e));
153
-
154
- /*
155
- generateTemplates({
156
- cleanOutput: false,
157
- output: './output/',
158
- httpClientType: "fetch",
159
- modular: true,
160
- silent: false,
161
- rewrite: false,
162
- });
163
- */
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { generateApi, generateTemplates } from "swagger-typescript-api";
4
+ import { ArgumentParser } from "argparse";
5
+
6
+ const parser = new ArgumentParser({
7
+ description: "Argparse example"
8
+ });
9
+
10
+ parser.add_argument("-o", "--output", { help: "Output path" });
11
+ parser.add_argument("-i", "--input", { help: "Input swagger file path" });
12
+ parser.add_argument("-t", "--templates", { help: "Templates" });
13
+ parser.add_argument("-d", "--data-contract-prefix", { help: "Data Contract Prefix" });
14
+ parser.add_argument("-c", "--use-common-client", { action: "store_true", help: "Use common http client" });
15
+
16
+ let a = parser.parse_args();
17
+ a.data_contract_prefix ??= "";
18
+
19
+ console.log(a);
20
+ /* NOTE: all fields are optional expect one of `input`, `url`, `spec` */
21
+
22
+ let config = {
23
+ input: path.resolve(process.cwd(), a.input),
24
+ templates: path.resolve(process.cwd(), a.templates),
25
+ httpClientType: "fetch", // or "fetch"
26
+ defaultResponseAsSuccess: false,
27
+ generateClient: true,
28
+ useCommonClient: a.use_common_client,
29
+ generateRouteTypes: false,
30
+ generateResponses: true,
31
+ toJS: false,
32
+ extractRequestParams: true,
33
+ extractRequestBody: true,
34
+ extractEnums: true,
35
+ unwrapResponseData: true,
36
+ modular: true,
37
+ prettier: {
38
+ printWidth: 120,
39
+ tabWidth: 2,
40
+ trailingComma: "all",
41
+ parser: "typescript"
42
+ },
43
+ defaultResponseType: "void",
44
+ singleHttpClient: false,
45
+ cleanOutput: false,
46
+ enumNamesAsValues: false,
47
+ moduleNameFirstTag: true,
48
+ generateUnionEnums: false,
49
+ dataContractPrefix: a.data_contract_prefix,
50
+ typePrefix: "",
51
+ typeSuffix: "",
52
+ enumKeyPrefix: "",
53
+ enumKeySuffix: "",
54
+ addReadonly: false,
55
+ sortTypes: false,
56
+ sortRouters: false,
57
+ extractingOptions: {
58
+ requestBodySuffix: ["Payload", "Body", "Input"],
59
+ requestParamsSuffix: ["Params"],
60
+ responseBodySuffix: ["Data", "Result", "Output"],
61
+ responseErrorSuffix: ["Error", "Fail", "Fails", "ErrorData", "HttpError", "BadResponse"]
62
+ },
63
+ /** allow to generate extra files based with this extra templates, see more below */
64
+ extraTemplates: [],
65
+ anotherArrayType: false,
66
+ fixInvalidTypeNamePrefix: "Type",
67
+ fixInvalidEnumKeyPrefix: "Value",
68
+ codeGenConstructs: (constructs) => ({
69
+ ...constructs,
70
+ RecordType: (key, value) => `MyRecord<key, value>`
71
+ }),
72
+ primitiveTypeConstructs: (constructs) => ({
73
+ ...constructs,
74
+ string: {
75
+ "date-time": "Date"
76
+ }
77
+ }),
78
+ hooks: {
79
+ onCreateComponent: (component) => {},
80
+ onCreateRequestParams: (rawType) => {},
81
+ onCreateRoute: (routeData) => {},
82
+ onCreateRouteName: (routeNameInfo, rawRouteInfo) => {
83
+ if (routeNameInfo.usage.startsWith(rawRouteInfo.moduleName)) {
84
+ const str = routeNameInfo.usage.substring(rawRouteInfo.moduleName.length);
85
+ routeNameInfo.usage = str[0].toLowerCase() + str.slice(1);
86
+ routeNameInfo.original = routeNameInfo.usage;
87
+ }
88
+ return routeNameInfo;
89
+ },
90
+ onFormatRouteName: (routeInfo, templateRouteName) => {},
91
+ onFormatTypeName: (typeName, rawTypeName, schemaType) => {},
92
+ onInit: (configuration) => {},
93
+ onPreParseSchema: (originalSchema, typeName, schemaType) => {},
94
+ onParseSchema: (originalSchema, parsedSchema) => {},
95
+ onPrepareConfig: (currentConfiguration) => {}
96
+ }
97
+ };
98
+ const toKebabCase = (str) =>
99
+ str &&
100
+ str
101
+ .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
102
+ .map((x) => x.toLowerCase())
103
+ .join("-");
104
+
105
+ generateApi(config)
106
+ .then(async ({ files, configuration }) => {
107
+ let dir = path.join(process.cwd(), a.output);
108
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir);
109
+
110
+ for (const f of files) {
111
+ if (f.fileContent) {
112
+ if (a.use_common_client && f.fileName === "http-client") {
113
+ console.log("Use common http client from oip, skip generate http-client.ts");
114
+ continue;
115
+ }
116
+
117
+ if (f.fileName === "data-contracts") {
118
+ f.fileName = config.dataContractPrefix + f.fileName;
119
+ } else if (f.fileName.endsWith("http-client")) {
120
+ // do nothing
121
+ } else {
122
+ f.fileName = `${toKebabCase(f.fileName)}.api`;
123
+ }
124
+
125
+ const absolutePath = path.join(dir, `${f.fileName}${f.fileExtension}`);
126
+ fs.writeFile(absolutePath, f.fileContent, (err) => {
127
+ if (err) {
128
+ console.log(err);
129
+ } else {
130
+ console.log(`File create: ${f.fileName}${f.fileExtension}`);
131
+ }
132
+ });
133
+ }
134
+ }
135
+ })
136
+ .catch((e) => console.error(e));
137
+
138
+ /*
139
+ generateTemplates({
140
+ cleanOutput: false,
141
+ output: './output/',
142
+ httpClientType: "fetch",
143
+ modular: true,
144
+ silent: false,
145
+ rewrite: false,
146
+ });
147
+ */
package/templates/api.ejs CHANGED
@@ -1,3 +1,7 @@
1
+ /* eslint-disable */
2
+ /* tslint:disable */
3
+ // @ts-nocheck
4
+
1
5
  <%
2
6
  const { utils, route, config, modelTypes } = it;
3
7
  const { _, pascalCase, require } = utils;
@@ -1,3 +1,7 @@
1
+ /* eslint-disable */
2
+ /* tslint:disable */
3
+ // @ts-nocheck
4
+
1
5
  <%
2
6
  const { apiConfig, generateResponses, config } = it;
3
7
  %>