swaggie 1.9.0-alpha.3 → 1.9.0-dev.1

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
@@ -179,7 +179,7 @@ import Axios, { AxiosPromise } from 'axios';
179
179
 
180
180
  const axios = Axios.create({
181
181
  baseURL: '/api',
182
- paramsSerializer: (params: any) =>
182
+ paramsSerializer: (params) =>
183
183
  encodeParams(params, null, {
184
184
  allowDots: true,
185
185
  arrayFormat: 'repeat',
@@ -58,8 +58,9 @@ function renderSchema(
58
58
  if ('x-ts-type' in schema) {
59
59
  const result = [];
60
60
  const s = schema ;
61
- if (_nullishCoalesce(s.description, () => ( s.title))) {
62
- result.push(_jsDocs.renderComment.call(void 0, _nullishCoalesce(s.description, () => ( s.title))));
61
+ const xTsComment = _jsDocs.buildSchemaComment.call(void 0, s);
62
+ if (xTsComment) {
63
+ result.push(xTsComment);
63
64
  }
64
65
  result.push(`export type ${safeName} = ${schema['x-ts-type']};`);
65
66
  return result.join('\n');
@@ -74,8 +75,9 @@ function renderSchema(
74
75
 
75
76
  const result = [];
76
77
  const schemaContext = `components.schemas.${safeName}`;
77
- if (_nullishCoalesce(schema.description, () => ( schema.title))) {
78
- result.push(_jsDocs.renderComment.call(void 0, _nullishCoalesce(schema.description, () => ( schema.title))));
78
+ const schemaComment = _jsDocs.buildSchemaComment.call(void 0, schema);
79
+ if (schemaComment) {
80
+ result.push(schemaComment);
79
81
  }
80
82
 
81
83
  if ('x-enumNames' in schema || 'x-enum-varnames' in schema) {
@@ -138,7 +140,10 @@ function renderSchema(
138
140
  return result.join('\n');
139
141
  } else {
140
142
  const objectType = _swagger.getTypeFromSchema.call(void 0, schema, options, schemaContext);
141
- const hasAdditionalProperties = !!schema.additionalProperties;
143
+ // A bare `type: object` with no properties is a free-form object per the OpenAPI spec
144
+ const isFreeFormObject =
145
+ schema.type === 'object' && !schema.properties && !schema.additionalProperties;
146
+ const hasAdditionalProperties = !!schema.additionalProperties || isFreeFormObject;
142
147
 
143
148
  const objectContents = generateObjectTypeContents(schema, options, schemaContext);
144
149
  if (hasAdditionalProperties) {
@@ -288,8 +293,13 @@ function renderTypeProp(
288
293
  const lines = [];
289
294
  const type = _swagger.getTypeFromSchema.call(void 0, definition, options, `${schemaContext}.properties.${propName}`);
290
295
 
291
- if ('description' in definition || 'title' in definition) {
292
- const renderedComment = _jsDocs.renderComment.call(void 0, _nullishCoalesce(definition.description, () => ( definition.title)));
296
+ if (
297
+ 'description' in definition ||
298
+ 'title' in definition ||
299
+ 'format' in definition ||
300
+ 'default' in definition
301
+ ) {
302
+ const renderedComment = _jsDocs.buildSchemaComment.call(void 0, definition );
293
303
  if (renderedComment) {
294
304
  lines.push(indentComment(renderedComment, ' '));
295
305
  }
@@ -3,6 +3,7 @@
3
3
  * regardless of generation mode.
4
4
  */
5
5
  const FILE_HEADER =
6
+ '/* istanbul ignore file -- auto-generated code */\n' +
6
7
  '/* tslint:disable */\n' +
7
8
  '/* eslint-disable */\n' +
8
9
  '//----------------------\n' +
@@ -12,5 +13,5 @@
12
13
  '// </auto-generated>\n' +
13
14
  '//----------------------\n' +
14
15
  '// ReSharper disable InconsistentNaming\n' +
15
- '// deno-lint-ignore-file\n' +
16
- '// biome-ignore-all lint: auto-generated code\n\n'; exports.FILE_HEADER = FILE_HEADER;
16
+ '// biome-ignore-all lint: auto-generated code\n' +
17
+ '// deno-lint-ignore-file\n\n'; exports.FILE_HEADER = FILE_HEADER;
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
 
4
4
  /**
@@ -80,6 +80,40 @@ function stripSpecificHtmlTags(str) {
80
80
  return renderComment(result.join('\n'));
81
81
  } exports.prepareJsDocsForOperation = prepareJsDocsForOperation;
82
82
 
83
+ /**
84
+ * Builds a JSDoc comment string from schema metadata, including optional
85
+ * `@default` and `@format` tags when those fields are present on the schema.
86
+ */
87
+ function buildSchemaComment(schema
88
+
89
+
90
+
91
+
92
+ ) {
93
+ const lines = [];
94
+
95
+ const text = _nullishCoalesce(schema.description, () => ( schema.title));
96
+ if (text) {
97
+ lines.push(text);
98
+ }
99
+
100
+ if (schema.default !== undefined) {
101
+ const val =
102
+ typeof schema.default === 'string'
103
+ ? `"${schema.default}"`
104
+ : typeof schema.default === 'object'
105
+ ? JSON.stringify(schema.default)
106
+ : String(schema.default);
107
+ lines.push(`@default ${val}`);
108
+ }
109
+
110
+ if (schema.format !== undefined) {
111
+ lines.push(`@format ${schema.format}`);
112
+ }
113
+
114
+ return renderComment(lines.join('\n'));
115
+ } exports.buildSchemaComment = buildSchemaComment;
116
+
83
117
  function renderComment(comment) {
84
118
  if (!comment) {
85
119
  return '';
@@ -22,25 +22,23 @@
22
22
  },
23
23
  "ng2": {
24
24
  "barrel.ejs": "\n/**\n * Serializes a params object into a query string that is compatible with different REST APIs.\n * Implementation from: https://github.com/suhaotian/xior/blob/main/src/utils.ts\n * Kudos to @suhaotian for the original implementation\n */\nfunction encodeParams<T = any>(\n params: T,\n parentKey: string | null = null,\n options?: {\n allowDots?: boolean;\n serializeDate?: (value: Date) => string;\n arrayFormat?: 'indices' | 'repeat' | 'brackets';\n }\n): string {\n if (params === undefined || params === null) return '';\n const encodedParams: string[] = [];\n const paramsIsArray = Array.isArray(params);\n const { arrayFormat, allowDots, serializeDate } = options || {};\n\n const getKey = (key: string) => {\n if (allowDots && !paramsIsArray) return `.${key}`;\n if (paramsIsArray) {\n if (arrayFormat === 'brackets') {\n return '[]';\n }\n if (arrayFormat === 'repeat') {\n return '';\n }\n }\n return `[${key}]`;\n };\n\n for (const key in params) {\n if (Object.prototype.hasOwnProperty.call(params, key)) {\n let value = (params as any)[key];\n if (value !== undefined) {\n const encodedKey = parentKey ? `${parentKey}${getKey(key)}` : (key as string);\n\n // biome-ignore lint/suspicious/noGlobalIsNan: <explanation>\n if (!isNaN(value) && value instanceof Date) {\n value = serializeDate ? serializeDate(value) : value.toISOString();\n }\n if (typeof value === 'object') {\n // If the value is an object or array, recursively encode its contents\n const result = encodeParams(value, encodedKey, options);\n if (result !== '') encodedParams.push(result);\n } else {\n // Otherwise, encode the key-value pair\n encodedParams.push(`${encodeURIComponent(encodedKey)}=${encodeURIComponent(value)}`);\n }\n }\n }\n }\n\n return encodedParams.join('&');\n}\n\n",
25
- "baseClient.ejs": "import type { Observable } from \"rxjs\";\nimport { Injectable, InjectionToken, inject } from \"@angular/core\";\nimport { HttpClient } from \"@angular/common/http\";\n\nexport const <%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL = new InjectionToken<string>(\"<%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL\");\n\nfunction paramsSerializer(params: any) {\n return encodeParams(params, null, {\n allowDots: <%= it.allowDots %>,\n arrayFormat: '<%= it.arrayFormat %>',\n });\n}\n\n",
26
- "client.ejs": "@Injectable({\n providedIn: 'root'\n})\nexport class <%= it.clientName.charAt(0).toUpperCase() + it.clientName.slice(1) -%>Service {\n private http = inject(HttpClient);\n private baseUrl = inject(<%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL, { optional: true }) ?? '';\n\n <% it.operations.forEach((operation) => { %>\n<%~ include('operation.ejs', operation); %>\n\n<% }); %>\n}\n\n",
27
- "operation.ejs": "<%~ it.jsDocs %>\n\n <%= it.name %>(\n <% it.parameters.forEach((parameter) => { %>\n<%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %> <%= parameter.optional ? (parameter.skippable ? '| null' : '| null | undefined') : '' %>,\n <% }); %>\nconfig?: any\n ): Observable<<%~ it.returnType %>> {\n<% if(it.query && it.query.length > 0) { -%>\n const params = paramsSerializer({<%\n it.query.forEach((parameter) => { %>\n '<%= parameter.originalName %>': <%= parameter.name %>,\n <% }); %>});\n const url = `<%= it.url %>${params ? '?' + params : ''}`;\n<% } else { -%>\n const url = `<%= it.url %>`;\n<% } -%>\n<% if(it.method === 'GET') { %>\n return this.http.get<<%~ it.returnType %>>(this.baseUrl + url, config);\n<% } else if(it.method === 'DELETE') { %>\n return this.http.delete<<%~ it.returnType %>>(this.baseUrl + url, config);\n<% } else if(['POST', 'PUT', 'PATCH'].includes(it.method)) {\n const bodyArg = it.body\n ? (it.body.contentType === 'urlencoded' ? 'new URLSearchParams(' + it.body.name + ' as any)' : it.body.name)\n : 'null';\n%>\n return this.http.<%= it.method.toLowerCase() %><%~ '<' + it.returnType + '>' %>(this.baseUrl + url, <%~ bodyArg %>, config);\n<% } %>\n }\n"
25
+ "baseClient.ejs": "import type { Observable } from \"rxjs\";\nimport { Injectable, Inject, Optional, InjectionToken } from \"@angular/core\";\nimport { HttpClient } from \"@angular/common/http\";\n\nexport const <%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL = new InjectionToken<string>(\"<%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL\");\n\nabstract class BaseService {\n private httpClient: HttpClient;\n private baseUrl: string;\n\n constructor(\n @Inject(HttpClient) httpClient: HttpClient,\n @Optional() @Inject(<%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL) baseUrl?: string\n ) {\n this.httpClient = httpClient;\n this.baseUrl = baseUrl ? baseUrl : '';\n }\n\n protected $get<T>(url: string, options?: any): Observable<T> {\n return this.httpClient\n .get<T>(this.baseUrl + url, options)\n .pipe((response: any) => response);\n }\n\n protected $getAll<T>(url: string, options?: any): Observable<T[]> {\n return this.httpClient\n .get<T[]>(this.baseUrl + url, options)\n .pipe((response: any) => response);\n }\n\n protected $delete<T>(url: string, options?: any): Observable<T> {\n return this.httpClient\n .delete(this.baseUrl + url, options)\n .pipe((response: any) => response);\n }\n\n protected $post(url: string, data: any, options?: any): Observable<any> {\n return this.httpClient\n .post(this.baseUrl + url, data, options)\n .pipe((response: any) => response);\n }\n\n protected $patch<T>(url: string, data: any, options?: any): Observable<T> {\n return this.httpClient\n .patch(this.baseUrl + url, data, options)\n .pipe((response: any) => response);\n }\n\n protected $put(url: string, data: any, options?: any): Observable<any> {\n return this.httpClient\n .put(this.baseUrl + url, data, options)\n .pipe((response: any) => response);\n }\n}\n\nfunction paramsSerializer(params: any) {\n return encodeParams(params, null, {\n allowDots: <%= it.allowDots %>,\n arrayFormat: '<%= it.arrayFormat %>',\n });\n}\n\n",
26
+ "client.ejs": "@Injectable({\n providedIn: 'root'\n})\nexport class <%= it.clientName -%>Service extends BaseService {\n constructor(\n @Inject(HttpClient) httpClient: HttpClient,\n @Optional() @Inject(<%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL) baseUrl?: string\n ) {\n super(httpClient, baseUrl);\n }\n\n <% it.operations.forEach((operation) => { %>\n<%~ include('operation.ejs', operation); %>\n\n<% }); %>\n}\n\n",
27
+ "operation.ejs": "<%~ it.jsDocs %>\n\n <%= it.name %>(\n <% it.parameters.forEach((parameter) => { %>\n<%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %> <%= parameter.optional ? (parameter.skippable ? '| null' : '| null | undefined') : '' %>,\n <% }); %>\nconfig?: any\n ): Observable<<%~ it.returnType %>> {\n const url = `<%= it.url %>?<%\n if(it.query && it.query.length > 0) { %>${paramsSerializer({<%\n it.query.forEach((parameter) => { %>\n'<%= parameter.originalName %>': <%= parameter.name %>,\n <% }); %>})}<% } %>`;\n\n return this.$<%= it.method.toLowerCase() %>(\n url,\n<% if(['POST', 'PUT', 'PATCH'].includes(it.method)) { %>\n<% if(it.body) { %>\n <%= it.body.contentType === 'urlencoded' ? 'new URLSearchParams(' + it.body.name + ' as any)' : it.body.name %>,\n<% } else { %>\n null,\n<% } %>\n<% } %>\n config\n );\n }\n"
28
28
  },
29
29
  "swr-axios": {
30
30
  "barrel.ejs": "\n/**\n * Serializes a params object into a query string that is compatible with different REST APIs.\n * Implementation from: https://github.com/suhaotian/xior/blob/main/src/utils.ts\n * Kudos to @suhaotian for the original implementation\n */\nfunction encodeParams<T = any>(\n params: T,\n parentKey: string | null = null,\n options?: {\n allowDots?: boolean;\n serializeDate?: (value: Date) => string;\n arrayFormat?: 'indices' | 'repeat' | 'brackets';\n }\n): string {\n if (params === undefined || params === null) return '';\n const encodedParams: string[] = [];\n const paramsIsArray = Array.isArray(params);\n const { arrayFormat, allowDots, serializeDate } = options || {};\n\n const getKey = (key: string) => {\n if (allowDots && !paramsIsArray) return `.${key}`;\n if (paramsIsArray) {\n if (arrayFormat === 'brackets') {\n return '[]';\n }\n if (arrayFormat === 'repeat') {\n return '';\n }\n }\n return `[${key}]`;\n };\n\n for (const key in params) {\n if (Object.prototype.hasOwnProperty.call(params, key)) {\n let value = (params as any)[key];\n if (value !== undefined) {\n const encodedKey = parentKey ? `${parentKey}${getKey(key)}` : (key as string);\n\n // biome-ignore lint/suspicious/noGlobalIsNan: <explanation>\n if (!isNaN(value) && value instanceof Date) {\n value = serializeDate ? serializeDate(value) : value.toISOString();\n }\n if (typeof value === 'object') {\n // If the value is an object or array, recursively encode its contents\n const result = encodeParams(value, encodedKey, options);\n if (result !== '') encodedParams.push(result);\n } else {\n // Otherwise, encode the key-value pair\n encodedParams.push(`${encodeURIComponent(encodedKey)}=${encodeURIComponent(value)}`);\n }\n }\n }\n }\n\n return encodedParams.join('&');\n}\n\n",
31
- "baseClient.ejs": "import Axios, { type AxiosPromise, type AxiosRequestConfig } from \"axios\";\nimport useSWR, { type SWRConfiguration, type Key } from 'swr';\nimport useSWRMutation, { type SWRMutationConfiguration } from 'swr/mutation';\n\nexport const axios = Axios.create({\n baseURL: '<%= it.baseUrl || '' -%>',\n paramsSerializer: (params: any) =>\n encodeParams(params, null, {\n allowDots: <%= it.allowDots %>,\n arrayFormat: '<%= it.arrayFormat %>',\n }),\n});\n\ninterface SwrConfig extends SWRConfiguration {\n /* Custom key for SWR. You don't have to worry about this as by default it's the URL. You can use standard SWR Key here if you need more flexibility. */\n key?: Key;\n}\n\n",
32
- "client.ejs": "export const <%= it.camelCaseName -%>Client = {\n <% it.operations.forEach((operation) => { %>\n<%~ include('operation.ejs', operation); %>\n\n <% }); %>\n};\n\n<%\nvar getOperations = it.operations.filter((o) => o.method === 'GET');\nvar mutationOperations = it.operations.filter((o) => o.method !== 'GET');\n\nfunction toOpName(name) {\n var n = name.toLowerCase().startsWith('get') ? name.substring(3) : name;\n return n.charAt(0).toUpperCase() + n.slice(1);\n}\n\nfunction safeOperation(operation, clientName) {\n var safeParams = operation.parameters.map(function(p) {\n return p.name === clientName ? Object.assign({}, p, { name: '_' + p.name }) : p;\n });\n return Object.assign({}, operation, { parameters: safeParams });\n}\n%>\n\nexport const <%= it.camelCaseName %> = {\n queries: {\n<% getOperations.forEach((operation) => {\n var opName = toOpName(operation.name);\n var swrOperation = Object.assign({\n swrOpName: 'use' + opName,\n clientName: it.camelCaseName,\n }, safeOperation(operation, it.camelCaseName));\n%>\n<%~ include('swrOperation.ejs', swrOperation); %>\n\n<% }); %>\n },\n\n mutations: {\n<% mutationOperations.forEach((operation) => {\n var opName = operation.name.charAt(0).toUpperCase() + operation.name.slice(1);\n var swrMutationOperation = Object.assign({\n mutOpName: 'use' + opName,\n clientName: it.camelCaseName,\n }, safeOperation(operation, it.camelCaseName));\n%>\n<%~ include('swrMutationOperation.ejs', swrMutationOperation); %>\n\n<% }); %>\n },\n\n queryKeys: {\n<% getOperations.forEach((operation) => {\n var opName = toOpName(operation.name);\n var keyName = opName.charAt(0).toLowerCase() + opName.slice(1);\n var safeOp = safeOperation(operation, it.camelCaseName);\n%>\n <%= keyName %>: (<% safeOp.parameters.forEach((parameter) => { %><%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %><%= parameter.optional ? ' | null' : '' %>, <% }); %>) => `<%= operation.url %><% if(safeOp.query && safeOp.query.length > 0) { %>?${encodeParams({<% safeOp.query.forEach((parameter) => { %>'<%= parameter.originalName %>': <%= parameter.name %>, <% }); %>})}<% } %>`,\n<% }); %>\n },\n};\n",
31
+ "baseClient.ejs": "import Axios, { type AxiosPromise, type AxiosRequestConfig } from \"axios\";\nimport useSWR, { type SWRConfiguration, type Key } from 'swr';\n\nexport const axios = Axios.create({\n baseURL: '<%= it.baseUrl || '' -%>',\n paramsSerializer: (params: any) =>\n encodeParams(params, null, {\n allowDots: <%= it.allowDots %>,\n arrayFormat: '<%= it.arrayFormat %>',\n }),\n});\n\ninterface SwrConfig extends SWRConfiguration {\n /* Custom key for SWR. You don't have to worry about this as by default it's the URL. You can use standard SWR Key here if you need more flexibility. */\n key?: Key;\n\n /* Configuration for axios fetcher */\n axios?: AxiosRequestConfig;\n}\n\n",
32
+ "client.ejs": "export const <%= it.camelCaseName -%>Client = {\n <% it.operations.forEach((operation) => { %>\n<%~ include('operation.ejs', operation); %>\n\n <% }); %>\n};\n\n<% var getOperations = it.operations.filter((o) => o.method === 'GET');\nif(getOperations.length > 0) { %>\n <% getOperations.forEach((operation) => {\n var opName = operation.name;\n if(opName.toLowerCase().startsWith(\"get\")) {\n opName = opName.substring(3);\n }\n opName[0] = opName[0].toUpperCase();\n var customName = \"use\" + it.clientName + opName;\n var swrOperation = Object.assign({ swrOpName: customName }, operation); %>\n<%~ include('swrOperation.ejs', swrOperation); %>\n\n <% }); %>\n<% } %>\n",
33
33
  "operation.ejs": "<%~ it.jsDocs %>\n\n <%= it.name %>(<% it.parameters.forEach((parameter) => { %>\n<%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %> <%= parameter.optional ? (parameter.skippable ? '| null' : '| null | undefined') : '' %>,\n <% }); %>\n $config?: AxiosRequestConfig\n ): AxiosPromise<<%~ it.returnType %>> {\n const url = `<%= it.url %>`;\n\n return axios.request<<%~ it.returnType %>>({\n url: url,\n method: '<%= it.method %>',\n<% if(it.body) { %>\n<% if(it.body.contentType === 'urlencoded') { %>\n data: new URLSearchParams(<%= it.body.name %> as any),\n<% } else { %>\n data: <%= it.body.name %>,\n<% } %>\n<% } %>\n<% if(it.query && it.query.length > 0) { %>\n params: {\n <% it.query.forEach((parameter) => { %>\n '<%= parameter.originalName %>': <%= parameter.name %>,\n <% }); %>\n },\n<% } %>\n<% if(it.headers && it.headers.length > 0) { %>\n headers: {\n <% it.headers.forEach((parameter) => { %>\n <% if (parameter.value) { %>\n '<%= parameter.originalName %>': '<%= parameter.value %>',\n <% } else { %>\n '<%= parameter.originalName %>': <%= parameter.name %>,\n <% } %>\n <% }); %>\n},\n<% } %>\n ...$config,\n });\n },\n",
34
- "swrMutationOperation.ejs": "<%\nvar hasParams = it.parameters.length > 0;\n\nvar variablesType;\nif (!hasParams) {\n variablesType = 'void';\n} else {\n var parts = it.parameters.map(function(p) {\n return p.name + (p.skippable ? '?' : '') + ': ' + p.type + (p.optional ? ' | null' : '');\n });\n variablesType = '{ ' + parts.join('; ') + ' }';\n}\n\nvar callArgs = it.parameters.map(function(p) { return 'arg.' + p.name; });\n\n// Stable SWR key: replace all ${...} path expressions with *\nvar swrKey = it.url.replace(/\\$\\{(?:[^{}]|\\{[^{}]*\\})*\\}/g, '*');\n\nvar docs = it.jsDocs ? it.jsDocs.replace(/^/gm, ' ') + '\\n' : '';\n%>\n<%~ docs %>\n <%= it.mutOpName %>(\n $config?: SWRMutationConfiguration<<%~ it.returnType %>, Error, string, <%~ variablesType %>>,\n $httpConfig?: AxiosRequestConfig\n ) {\n return useSWRMutation<<%~ it.returnType %>, Error, string, <%~ variablesType %>>(\n '<%= swrKey %>',\n (_key: string, { arg }<%= hasParams ? ': { arg: ' + variablesType + ' }' : '' %>) =>\n <%= it.clientName %>Client.<%= it.name %>(<%= callArgs.join(', ') %><%= callArgs.length > 0 ? ', ' : '' %>$httpConfig).then((resp) => resp.data),\n $config\n );\n },\n",
35
- "swrOperation.ejs": "<% var docs = it.jsDocs ? it.jsDocs.replace(/^/gm, ' ') + '\\n' : ''; %>\n<%~ docs %>\n <%= it.swrOpName %>(\n<% it.parameters.forEach((parameter) => { %> <%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %><%= parameter.optional ? (parameter.skippable ? ' | null' : ' | null | undefined') : '' %>,\n<% }); %> $config?: Omit<SwrConfig, 'key'> & { key?: Key },\n $httpConfig?: AxiosRequestConfig\n ) {\n const { key, ...config } = $config || {};\n const cacheUrl = key ?? <%= it.clientName %>.queryKeys.<%= it.swrOpName.charAt(3).toLowerCase() + it.swrOpName.slice(4) %>(<% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>);\n\n const { data, error, isLoading, mutate } = useSWR<<%~ it.returnType %>>(\n cacheUrl,\n () => <%= it.clientName %>Client.<%= it.name %>(<% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>$httpConfig).then((resp) => resp.data),\n config\n );\n\n return { data, isLoading, error, mutate };\n },\n"
34
+ "swrOperation.ejs": "<%~ it.jsDocs %>\n\nexport function <%= it.swrOpName %>(<% it.parameters.forEach((parameter) => { %>\n <%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %> <%= parameter.optional ? (parameter.skippable ? '| null' : '| null | undefined') : '' %>,\n <% }); %>\n $config?: SwrConfig\n ) {\n const url = `<%= it.url %>`;\n const { axios: $axiosConf, key, ...config } = $config || {};\n\n const cacheUrl = `${url}?<%\n if(it.query && it.query.length > 0) { %>${encodeParams({<%\n it.query.forEach((parameter) => { %>\n'<%= parameter.originalName %>': <%= parameter.name %>,\n <% }); %>})}<% } %>`;\n\nconst { data, error, mutate } = useSWR<<%~ it.returnType %>>(\n key ?? cacheUrl,\n () => axios.request({\n url: url,\n method: '<%= it.method %>',\n<% if(it.query && it.query.length > 0) { %>\n params: {\n <% it.query.forEach((parameter) => { %>\n '<%= parameter.originalName %>': <%= parameter.name %>,\n <% }); %>\n},\n<% } %>\n<% if(it.headers && it.headers.length > 0) { %>\n headers: {\n <% it.headers.forEach((parameter) => { %>\n <% if (parameter.value) { %>\n '<%= parameter.originalName %>': '<%= parameter.value %>',\n <% } else { %>\n '<%= parameter.originalName %>': <%= parameter.name %>,\n <% } %>\n <% }); %>\n },\n<% } %>\n ...$axiosConf})\n .then((resp) => resp.data),\n config);\n\n return {\n data,\n isLoading: !error && !data,\n error: error,\n mutate,\n };\n}\n"
36
35
  },
37
36
  "tsq-xior": {
38
37
  "barrel.ejs": "",
39
- "baseClient.ejs": "import xior, { type XiorResponse, type XiorRequestConfig, encodeParams } from \"xior\";\nimport { type UseQueryOptions, type UseMutationOptions, useQuery, useMutation } from '@tanstack/react-query';\n\nexport const http = xior.create({\n baseURL: '<%= it.baseUrl || '' %>',\n paramsSerializer: (params: any) =>\n encodeParams(params, true, null, {\n allowDots: <%= it.allowDots %>,\n arrayFormat: '<%= it.arrayFormat %>',\n }),\n});\n\n",
40
- "client.ejs": "export const <%= it.camelCaseName %>Client = {\n <% it.operations.forEach((operation) => { %>\n<%~ include('operation.ejs', operation); %>\n\n<% }); %>\n};\n\n<%\nvar getOperations = it.operations.filter((o) => o.method === 'GET');\nvar mutationOperations = it.operations.filter((o) => o.method !== 'GET');\n\n// Helper: strip leading \"get\" and capitalise\nfunction toOpName(name) {\n var n = name.toLowerCase().startsWith('get') ? name.substring(3) : name;\n return n.charAt(0).toUpperCase() + n.slice(1);\n}\n\n// Returns a deep copy of operation with any parameter whose name collides with\n// the group object name (clientName) renamed to _<name> to avoid TS shadowing.\nfunction safeOperation(operation, clientName) {\n var safeParams = operation.parameters.map(function(p) {\n return p.name === clientName ? Object.assign({}, p, { name: '_' + p.name }) : p;\n });\n return Object.assign({}, operation, { parameters: safeParams });\n}\n%>\n\nexport const <%= it.camelCaseName %> = {\n queries: {\n<% getOperations.forEach((operation) => {\n var opName = toOpName(operation.name);\n var queryOperation = Object.assign({\n rqOpName: 'use' + opName,\n opKey: it.camelCaseName + opName,\n clientName: it.camelCaseName,\n }, safeOperation(operation, it.camelCaseName));\n%>\n<%~ include('queryOperation.ejs', queryOperation); %>\n\n<% }); %>\n },\n\n mutations: {\n<% mutationOperations.forEach((operation) => {\n var opName = operation.name.charAt(0).toUpperCase() + operation.name.slice(1);\n var mutationOperation = Object.assign({\n mutOpName: 'use' + opName,\n clientName: it.camelCaseName,\n }, safeOperation(operation, it.camelCaseName));\n%>\n<%~ include('mutationOperation.ejs', mutationOperation); %>\n\n<% }); %>\n },\n\n queryKeys: {\n<% getOperations.forEach((operation) => {\n var opName = toOpName(operation.name);\n var keyName = opName.charAt(0).toLowerCase() + opName.slice(1);\n var safeOp = safeOperation(operation, it.camelCaseName);\n%>\n <%= keyName %>: (<% safeOp.parameters.forEach((parameter) => { %><%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %><%= parameter.optional ? ' | null' : '' %>, <% }); %>) => ['<%= it.camelCaseName %>', '<%= it.camelCaseName + opName %>'<% safeOp.parameters.forEach((parameter) => { %>, <%= parameter.name %><% }); %>] as const,\n<% }); %>\n },\n};\n",
41
- "mutationOperation.ejs": "<%\nvar hasParams = it.parameters.length > 0;\n\nvar variablesType;\nif (!hasParams) {\n variablesType = 'void';\n} else {\n var parts = it.parameters.map(function(p) {\n return p.name + (p.skippable ? '?' : '') + ': ' + p.type + (p.optional ? ' | null' : '');\n });\n variablesType = '{ ' + parts.join('; ') + ' }';\n}\n\nvar callArgs = it.parameters.map(function(p) { return 'vars.' + p.name; });\n\nvar baseAdditionalParams = ' * @param $config (optional) Additional configuration for TanStack Query\\n * @param $httpConfig (optional) Additional configuration for xior request (actually executes the request)';\nvar rawDocs = it.jsDocs\n ? it.jsDocs.replace(/(\\s*)\\*\\/\\s*$/, '\\n' + baseAdditionalParams + '\\n */')\n : '';\nvar docs = rawDocs ? rawDocs.replace(/^/gm, ' ') + '\\n' : '';\n%>\n<%~ docs %>\n <%= it.mutOpName %><TData = <%~ it.returnType %>, TError = Error>(\n $config?: UseMutationOptions<<%~ it.returnType %>, TError, <%~ variablesType %>>,\n $httpConfig?: XiorRequestConfig\n ) {\n return useMutation<<%~ it.returnType %>, TError, <%~ variablesType %>>({\n mutationFn: (<%= hasParams ? 'vars' : '' %>) => <%= it.clientName %>Client.<%= it.name %>(<%= callArgs.join(', ') %><%= callArgs.length > 0 ? ', ' : '' %>$httpConfig).then(res => res.data),\n ...$config\n });\n },\n",
38
+ "baseClient.ejs": "import xior, { type XiorResponse, type XiorRequestConfig, encodeParams } from \"xior\";\nimport { QueryClient, type UseQueryOptions, useQuery } from '@tanstack/react-query';\n\nexport const queryClient = new QueryClient();\n\nexport const http = xior.create({\n baseURL: '<%= it.baseUrl || '' %>',\n paramsSerializer: (params: any) =>\n encodeParams(params, true, null, {\n allowDots: <%= it.allowDots %>,\n arrayFormat: '<%= it.arrayFormat %>',\n }),\n});\n\n",
39
+ "client.ejs": "export const <%= it.camelCaseName %>Client = {\n <% it.operations.forEach((operation) => { %>\n<%~ include('operation.ejs', operation); %>\n\n<% }); %>\n};\n\n\n<% var getOperations = it.operations.filter((o) => o.method === 'GET');\nif(getOperations.length > 0) { %>\n <% getOperations.forEach((operation) => {\n var opName = operation.name;\n if(opName.toLowerCase().startsWith(\"get\")) {\n opName = opName.substring(3);\n }\n opName[0] = opName[0].toUpperCase();\n var customName = \"use\" + it.clientName + opName;\n var queryOperation = Object.assign({ rqOpName: customName, opKey: it.clientName + opName, clientName: it.camelCaseName }, operation); %>\n<%~ include('queryOperation.ejs', queryOperation); %>\n\n <% }); %>\n<% } %>\n",
42
40
  "operation.ejs": "<%~ it.jsDocs %>\n\n <%= it.name %>(<% it.parameters.forEach((parameter) => { %>\n<%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %> <%= parameter.optional ? (parameter.skippable ? '| null' : '| null | undefined') : '' %>,\n <% }); %>\n$config?: XiorRequestConfig\n ): Promise<XiorResponse<<%~ it.returnType %>>> {\n const url = `<%= it.url %>`;\n\n return http.request<<%~ it.returnType %>>({\n url: url,\n method: '<%= it.method %>',\n<% if(it.body) { %>\n<% if(it.body.contentType === 'urlencoded') { %>\n data: new URLSearchParams(<%= it.body.name %> as any),\n<% } else { %>\n data: <%= it.body.name %>,\n<% } %>\n<% } %>\n<% if(it.query && it.query.length > 0) { %>\n params: {\n <% it.query.forEach((parameter) => { %>\n '<%= parameter.originalName %>': <%= parameter.name %>,\n <% }); %>\n },\n<% } %>\n<% if(it.headers && it.headers.length > 0) { %>\n headers: {\n <% it.headers.forEach((parameter) => { %>\n <% if (parameter.value) { %>\n '<%= parameter.originalName %>': '<%= parameter.value %>',\n <% } else { %>\n '<%= parameter.originalName %>': <%= parameter.name %>,\n <% } %>\n <% }); %>\n},\n<% } %>\n ...$config,\n });\n },\n",
43
- "queryOperation.ejs": "<%\nvar baseAdditionalParams = ' * @param $config (optional) Additional configuration for TanStack Query\\n * @param $httpConfig (optional) Additional configuration for xior request (actually executes the request)';\nvar rawDocs = it.jsDocs\n ? it.jsDocs.replace(/(\\s*)\\*\\/\\s*$/, '\\n' + baseAdditionalParams + '\\n */')\n : '';\nvar docs = rawDocs ? rawDocs.replace(/^/gm, ' ') + '\\n' : '';\n%>\n<%~ docs %>\n <%= it.rqOpName %><TData = <%~ it.returnType %>, TError = Error>(\n<% it.parameters.forEach((parameter) => { %> <%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %><%= parameter.optional ? (parameter.skippable ? ' | null' : ' | null | undefined') : '' %>,\n<% }); %> $config?: Omit<UseQueryOptions<<%~ it.returnType %>, TError, TData>, 'queryKey' | 'queryFn'>,\n $httpConfig?: XiorRequestConfig\n ) {\n return useQuery<<%~ it.returnType %>, TError, TData>({\n queryKey: <%= it.clientName %>.queryKeys.<%= it.rqOpName.charAt(3).toLowerCase() + it.rqOpName.slice(4) %>(<% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>),\n queryFn: () => <%= it.clientName %>Client.<%= it.name %>(<% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>$httpConfig).then(res => res.data),\n ...$config\n });\n },\n"
41
+ "queryOperation.ejs": "<%\nif (it.jsDocs) {\n const additionalParams = ` * @param $config (optional) Additional configuration for TanStack Query\n * @param $httpConfig (optional) Additional configuration for xior request (actually executes the request)`;\n\n // Replace the closing */ with newline + additional params + closing */\n const modifiedDocs = it.jsDocs.replace(/(\\s*)\\*\\/\\s*$/, `\\n${additionalParams}\\n */`);\n-%>\n<%~ modifiedDocs %>\n<% } else { -%>\n<%~ it.jsDocs %>\n<% } %>\n\nexport function <%= it.rqOpName %><TData = <%~ it.returnType %>, TError = Error>(<% it.parameters.forEach((parameter) => { %>\n <%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %> <%= parameter.optional ? (parameter.skippable ? '| null' : '| null | undefined') : '' %>,\n <% }); %>\n$config?: Omit<\n UseQueryOptions<<%~ it.returnType %>, TError, TData>,\n 'queryKey' | 'queryFn'\n>,\n $httpConfig?: XiorRequestConfig\n ) {\n return useQuery<<%~ it.returnType %>, TError, TData>({\n queryKey: ['<%= it.clientName %>', '<%= it.opKey %>', <% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>],\n queryFn: () => <%= it.clientName %>Client.<%= it.name %>(<% it.parameters.forEach((parameter) => { %>\n<%= parameter.name %>, <% }); %>$httpConfig).then(res => res.data),\n ...$config\n });\n}\n<%= it.rqOpName %>.queryKeys = ['<%= it.clientName %>', '<%= it.opKey %>'];\n"
44
42
  },
45
43
  "xior": {
46
44
  "barrel.ejs": "",
@@ -249,11 +249,11 @@ function getTypeFromObject(
249
249
 
250
250
  if (schema.additionalProperties) {
251
251
  const extraProps = schema.additionalProperties;
252
- objectWithIndexSignatureType = `{ [key: string]: ${
252
+ objectWithIndexSignatureType = `Record<string, ${
253
253
  extraProps === true
254
- ? 'any'
254
+ ? unknownType
255
255
  : getTypeFromSchemaResolved(extraProps, options, `${context}.additionalProperties`)
256
- } }`;
256
+ }>`;
257
257
  }
258
258
 
259
259
  if (objectWithNamedPropsType && objectWithIndexSignatureType) {
@@ -268,6 +268,12 @@ function getTypeFromObject(
268
268
  return objectWithIndexSignatureType;
269
269
  }
270
270
 
271
+ // A bare `type: object` with no properties and no additionalProperties is a
272
+ // free-form object per the OpenAPI spec (equivalent to additionalProperties: true).
273
+ if (schema.type === 'object') {
274
+ return `Record<string, ${unknownType}>`;
275
+ }
276
+
271
277
  return unknownType;
272
278
  }
273
279
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swaggie",
3
- "version": "1.9.0-alpha.3",
3
+ "version": "1.9.0-dev.1",
4
4
  "description": "Generate a fully typed TypeScript API client from your OpenAPI 3 spec",
5
5
  "author": {
6
6
  "name": "Piotr Dabrowski",
@@ -1,9 +1,58 @@
1
1
  import type { Observable } from "rxjs";
2
- import { Injectable, InjectionToken, inject } from "@angular/core";
2
+ import { Injectable, Inject, Optional, InjectionToken } from "@angular/core";
3
3
  import { HttpClient } from "@angular/common/http";
4
4
 
5
5
  export const <%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL = new InjectionToken<string>("<%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL");
6
6
 
7
+ abstract class BaseService {
8
+ private httpClient: HttpClient;
9
+ private baseUrl: string;
10
+
11
+ constructor(
12
+ @Inject(HttpClient) httpClient: HttpClient,
13
+ @Optional() @Inject(<%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL) baseUrl?: string
14
+ ) {
15
+ this.httpClient = httpClient;
16
+ this.baseUrl = baseUrl ? baseUrl : '';
17
+ }
18
+
19
+ protected $get<T>(url: string, options?: any): Observable<T> {
20
+ return this.httpClient
21
+ .get<T>(this.baseUrl + url, options)
22
+ .pipe((response: any) => response);
23
+ }
24
+
25
+ protected $getAll<T>(url: string, options?: any): Observable<T[]> {
26
+ return this.httpClient
27
+ .get<T[]>(this.baseUrl + url, options)
28
+ .pipe((response: any) => response);
29
+ }
30
+
31
+ protected $delete<T>(url: string, options?: any): Observable<T> {
32
+ return this.httpClient
33
+ .delete(this.baseUrl + url, options)
34
+ .pipe((response: any) => response);
35
+ }
36
+
37
+ protected $post(url: string, data: any, options?: any): Observable<any> {
38
+ return this.httpClient
39
+ .post(this.baseUrl + url, data, options)
40
+ .pipe((response: any) => response);
41
+ }
42
+
43
+ protected $patch<T>(url: string, data: any, options?: any): Observable<T> {
44
+ return this.httpClient
45
+ .patch(this.baseUrl + url, data, options)
46
+ .pipe((response: any) => response);
47
+ }
48
+
49
+ protected $put(url: string, data: any, options?: any): Observable<any> {
50
+ return this.httpClient
51
+ .put(this.baseUrl + url, data, options)
52
+ .pipe((response: any) => response);
53
+ }
54
+ }
55
+
7
56
  function paramsSerializer(params: any) {
8
57
  return encodeParams(params, null, {
9
58
  allowDots: <%= it.allowDots %>,
@@ -1,9 +1,13 @@
1
1
  @Injectable({
2
2
  providedIn: 'root'
3
3
  })
4
- export class <%= it.clientName.charAt(0).toUpperCase() + it.clientName.slice(1) -%>Service {
5
- private http = inject(HttpClient);
6
- private baseUrl = inject(<%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL, { optional: true }) ?? '';
4
+ export class <%= it.clientName -%>Service extends BaseService {
5
+ constructor(
6
+ @Inject(HttpClient) httpClient: HttpClient,
7
+ @Optional() @Inject(<%= (it.servicePrefix || 'API').toUpperCase() -%>_BASE_URL) baseUrl?: string
8
+ ) {
9
+ super(httpClient, baseUrl);
10
+ }
7
11
 
8
12
  <% it.operations.forEach((operation) => { %>
9
13
  <%~ include('operation.ejs', operation); %>
@@ -6,24 +6,21 @@
6
6
  <% }); %>
7
7
  config?: any
8
8
  ): Observable<<%~ it.returnType %>> {
9
- <% if(it.query && it.query.length > 0) { -%>
10
- const params = paramsSerializer({<%
9
+ const url = `<%= it.url %>?<%
10
+ if(it.query && it.query.length > 0) { %>${paramsSerializer({<%
11
11
  it.query.forEach((parameter) => { %>
12
- '<%= parameter.originalName %>': <%= parameter.name %>,
13
- <% }); %>});
14
- const url = `<%= it.url %>${params ? '?' + params : ''}`;
15
- <% } else { -%>
16
- const url = `<%= it.url %>`;
17
- <% } -%>
18
- <% if(it.method === 'GET') { %>
19
- return this.http.get<<%~ it.returnType %>>(this.baseUrl + url, config);
20
- <% } else if(it.method === 'DELETE') { %>
21
- return this.http.delete<<%~ it.returnType %>>(this.baseUrl + url, config);
22
- <% } else if(['POST', 'PUT', 'PATCH'].includes(it.method)) {
23
- const bodyArg = it.body
24
- ? (it.body.contentType === 'urlencoded' ? 'new URLSearchParams(' + it.body.name + ' as any)' : it.body.name)
25
- : 'null';
26
- %>
27
- return this.http.<%= it.method.toLowerCase() %><%~ '<' + it.returnType + '>' %>(this.baseUrl + url, <%~ bodyArg %>, config);
12
+ '<%= parameter.originalName %>': <%= parameter.name %>,
13
+ <% }); %>})}<% } %>`;
14
+
15
+ return this.$<%= it.method.toLowerCase() %>(
16
+ url,
17
+ <% if(['POST', 'PUT', 'PATCH'].includes(it.method)) { %>
18
+ <% if(it.body) { %>
19
+ <%= it.body.contentType === 'urlencoded' ? 'new URLSearchParams(' + it.body.name + ' as any)' : it.body.name %>,
20
+ <% } else { %>
21
+ null,
22
+ <% } %>
28
23
  <% } %>
24
+ config
25
+ );
29
26
  }
@@ -1,6 +1,5 @@
1
1
  import Axios, { type AxiosPromise, type AxiosRequestConfig } from "axios";
2
2
  import useSWR, { type SWRConfiguration, type Key } from 'swr';
3
- import useSWRMutation, { type SWRMutationConfiguration } from 'swr/mutation';
4
3
 
5
4
  export const axios = Axios.create({
6
5
  baseURL: '<%= it.baseUrl || '' -%>',
@@ -14,5 +13,8 @@ export const axios = Axios.create({
14
13
  interface SwrConfig extends SWRConfiguration {
15
14
  /* Custom key for SWR. You don't have to worry about this as by default it's the URL. You can use standard SWR Key here if you need more flexibility. */
16
15
  key?: Key;
16
+
17
+ /* Configuration for axios fetcher */
18
+ axios?: AxiosRequestConfig;
17
19
  }
18
20
 
@@ -5,57 +5,17 @@ export const <%= it.camelCaseName -%>Client = {
5
5
  <% }); %>
6
6
  };
7
7
 
8
- <%
9
- var getOperations = it.operations.filter((o) => o.method === 'GET');
10
- var mutationOperations = it.operations.filter((o) => o.method !== 'GET');
11
-
12
- function toOpName(name) {
13
- var n = name.toLowerCase().startsWith('get') ? name.substring(3) : name;
14
- return n.charAt(0).toUpperCase() + n.slice(1);
15
- }
16
-
17
- function safeOperation(operation, clientName) {
18
- var safeParams = operation.parameters.map(function(p) {
19
- return p.name === clientName ? Object.assign({}, p, { name: '_' + p.name }) : p;
20
- });
21
- return Object.assign({}, operation, { parameters: safeParams });
22
- }
23
- %>
24
-
25
- export const <%= it.camelCaseName %> = {
26
- queries: {
27
- <% getOperations.forEach((operation) => {
28
- var opName = toOpName(operation.name);
29
- var swrOperation = Object.assign({
30
- swrOpName: 'use' + opName,
31
- clientName: it.camelCaseName,
32
- }, safeOperation(operation, it.camelCaseName));
33
- %>
8
+ <% var getOperations = it.operations.filter((o) => o.method === 'GET');
9
+ if(getOperations.length > 0) { %>
10
+ <% getOperations.forEach((operation) => {
11
+ var opName = operation.name;
12
+ if(opName.toLowerCase().startsWith("get")) {
13
+ opName = opName.substring(3);
14
+ }
15
+ opName[0] = opName[0].toUpperCase();
16
+ var customName = "use" + it.clientName + opName;
17
+ var swrOperation = Object.assign({ swrOpName: customName }, operation); %>
34
18
  <%~ include('swrOperation.ejs', swrOperation); %>
35
19
 
36
- <% }); %>
37
- },
38
-
39
- mutations: {
40
- <% mutationOperations.forEach((operation) => {
41
- var opName = operation.name.charAt(0).toUpperCase() + operation.name.slice(1);
42
- var swrMutationOperation = Object.assign({
43
- mutOpName: 'use' + opName,
44
- clientName: it.camelCaseName,
45
- }, safeOperation(operation, it.camelCaseName));
46
- %>
47
- <%~ include('swrMutationOperation.ejs', swrMutationOperation); %>
48
-
49
- <% }); %>
50
- },
51
-
52
- queryKeys: {
53
- <% getOperations.forEach((operation) => {
54
- var opName = toOpName(operation.name);
55
- var keyName = opName.charAt(0).toLowerCase() + opName.slice(1);
56
- var safeOp = safeOperation(operation, it.camelCaseName);
57
- %>
58
- <%= keyName %>: (<% safeOp.parameters.forEach((parameter) => { %><%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %><%= parameter.optional ? ' | null' : '' %>, <% }); %>) => `<%= operation.url %><% if(safeOp.query && safeOp.query.length > 0) { %>?${encodeParams({<% safeOp.query.forEach((parameter) => { %>'<%= parameter.originalName %>': <%= parameter.name %>, <% }); %>})}<% } %>`,
59
- <% }); %>
60
- },
61
- };
20
+ <% }); %>
21
+ <% } %>
@@ -1,18 +1,50 @@
1
- <% var docs = it.jsDocs ? it.jsDocs.replace(/^/gm, ' ') + '\n' : ''; %>
2
- <%~ docs %>
3
- <%= it.swrOpName %>(
4
- <% it.parameters.forEach((parameter) => { %> <%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %><%= parameter.optional ? (parameter.skippable ? ' | null' : ' | null | undefined') : '' %>,
5
- <% }); %> $config?: Omit<SwrConfig, 'key'> & { key?: Key },
6
- $httpConfig?: AxiosRequestConfig
7
- ) {
8
- const { key, ...config } = $config || {};
9
- const cacheUrl = key ?? <%= it.clientName %>.queryKeys.<%= it.swrOpName.charAt(3).toLowerCase() + it.swrOpName.slice(4) %>(<% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>);
1
+ <%~ it.jsDocs %>
10
2
 
11
- const { data, error, isLoading, mutate } = useSWR<<%~ it.returnType %>>(
12
- cacheUrl,
13
- () => <%= it.clientName %>Client.<%= it.name %>(<% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>$httpConfig).then((resp) => resp.data),
14
- config
15
- );
3
+ export function <%= it.swrOpName %>(<% it.parameters.forEach((parameter) => { %>
4
+ <%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %> <%= parameter.optional ? (parameter.skippable ? '| null' : '| null | undefined') : '' %>,
5
+ <% }); %>
6
+ $config?: SwrConfig
7
+ ) {
8
+ const url = `<%= it.url %>`;
9
+ const { axios: $axiosConf, key, ...config } = $config || {};
16
10
 
17
- return { data, isLoading, error, mutate };
18
- },
11
+ const cacheUrl = `${url}?<%
12
+ if(it.query && it.query.length > 0) { %>${encodeParams({<%
13
+ it.query.forEach((parameter) => { %>
14
+ '<%= parameter.originalName %>': <%= parameter.name %>,
15
+ <% }); %>})}<% } %>`;
16
+
17
+ const { data, error, mutate } = useSWR<<%~ it.returnType %>>(
18
+ key ?? cacheUrl,
19
+ () => axios.request({
20
+ url: url,
21
+ method: '<%= it.method %>',
22
+ <% if(it.query && it.query.length > 0) { %>
23
+ params: {
24
+ <% it.query.forEach((parameter) => { %>
25
+ '<%= parameter.originalName %>': <%= parameter.name %>,
26
+ <% }); %>
27
+ },
28
+ <% } %>
29
+ <% if(it.headers && it.headers.length > 0) { %>
30
+ headers: {
31
+ <% it.headers.forEach((parameter) => { %>
32
+ <% if (parameter.value) { %>
33
+ '<%= parameter.originalName %>': '<%= parameter.value %>',
34
+ <% } else { %>
35
+ '<%= parameter.originalName %>': <%= parameter.name %>,
36
+ <% } %>
37
+ <% }); %>
38
+ },
39
+ <% } %>
40
+ ...$axiosConf})
41
+ .then((resp) => resp.data),
42
+ config);
43
+
44
+ return {
45
+ data,
46
+ isLoading: !error && !data,
47
+ error: error,
48
+ mutate,
49
+ };
50
+ }
@@ -1,5 +1,7 @@
1
1
  import xior, { type XiorResponse, type XiorRequestConfig, encodeParams } from "xior";
2
- import { type UseQueryOptions, type UseMutationOptions, useQuery, useMutation } from '@tanstack/react-query';
2
+ import { QueryClient, type UseQueryOptions, useQuery } from '@tanstack/react-query';
3
+
4
+ export const queryClient = new QueryClient();
3
5
 
4
6
  export const http = xior.create({
5
7
  baseURL: '<%= it.baseUrl || '' %>',
@@ -5,61 +5,18 @@ export const <%= it.camelCaseName %>Client = {
5
5
  <% }); %>
6
6
  };
7
7
 
8
- <%
9
- var getOperations = it.operations.filter((o) => o.method === 'GET');
10
- var mutationOperations = it.operations.filter((o) => o.method !== 'GET');
11
8
 
12
- // Helper: strip leading "get" and capitalise
13
- function toOpName(name) {
14
- var n = name.toLowerCase().startsWith('get') ? name.substring(3) : name;
15
- return n.charAt(0).toUpperCase() + n.slice(1);
16
- }
17
-
18
- // Returns a deep copy of operation with any parameter whose name collides with
19
- // the group object name (clientName) renamed to _<name> to avoid TS shadowing.
20
- function safeOperation(operation, clientName) {
21
- var safeParams = operation.parameters.map(function(p) {
22
- return p.name === clientName ? Object.assign({}, p, { name: '_' + p.name }) : p;
23
- });
24
- return Object.assign({}, operation, { parameters: safeParams });
25
- }
26
- %>
27
-
28
- export const <%= it.camelCaseName %> = {
29
- queries: {
30
- <% getOperations.forEach((operation) => {
31
- var opName = toOpName(operation.name);
32
- var queryOperation = Object.assign({
33
- rqOpName: 'use' + opName,
34
- opKey: it.camelCaseName + opName,
35
- clientName: it.camelCaseName,
36
- }, safeOperation(operation, it.camelCaseName));
37
- %>
9
+ <% var getOperations = it.operations.filter((o) => o.method === 'GET');
10
+ if(getOperations.length > 0) { %>
11
+ <% getOperations.forEach((operation) => {
12
+ var opName = operation.name;
13
+ if(opName.toLowerCase().startsWith("get")) {
14
+ opName = opName.substring(3);
15
+ }
16
+ opName[0] = opName[0].toUpperCase();
17
+ var customName = "use" + it.clientName + opName;
18
+ var queryOperation = Object.assign({ rqOpName: customName, opKey: it.clientName + opName, clientName: it.camelCaseName }, operation); %>
38
19
  <%~ include('queryOperation.ejs', queryOperation); %>
39
20
 
40
- <% }); %>
41
- },
42
-
43
- mutations: {
44
- <% mutationOperations.forEach((operation) => {
45
- var opName = operation.name.charAt(0).toUpperCase() + operation.name.slice(1);
46
- var mutationOperation = Object.assign({
47
- mutOpName: 'use' + opName,
48
- clientName: it.camelCaseName,
49
- }, safeOperation(operation, it.camelCaseName));
50
- %>
51
- <%~ include('mutationOperation.ejs', mutationOperation); %>
52
-
53
- <% }); %>
54
- },
55
-
56
- queryKeys: {
57
- <% getOperations.forEach((operation) => {
58
- var opName = toOpName(operation.name);
59
- var keyName = opName.charAt(0).toLowerCase() + opName.slice(1);
60
- var safeOp = safeOperation(operation, it.camelCaseName);
61
- %>
62
- <%= keyName %>: (<% safeOp.parameters.forEach((parameter) => { %><%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %><%= parameter.optional ? ' | null' : '' %>, <% }); %>) => ['<%= it.camelCaseName %>', '<%= it.camelCaseName + opName %>'<% safeOp.parameters.forEach((parameter) => { %>, <%= parameter.name %><% }); %>] as const,
63
- <% }); %>
64
- },
65
- };
21
+ <% }); %>
22
+ <% } %>
@@ -1,19 +1,30 @@
1
1
  <%
2
- var baseAdditionalParams = ' * @param $config (optional) Additional configuration for TanStack Query\n * @param $httpConfig (optional) Additional configuration for xior request (actually executes the request)';
3
- var rawDocs = it.jsDocs
4
- ? it.jsDocs.replace(/(\s*)\*\/\s*$/, '\n' + baseAdditionalParams + '\n */')
5
- : '';
6
- var docs = rawDocs ? rawDocs.replace(/^/gm, ' ') + '\n' : '';
7
- %>
8
- <%~ docs %>
9
- <%= it.rqOpName %><TData = <%~ it.returnType %>, TError = Error>(
10
- <% it.parameters.forEach((parameter) => { %> <%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %><%= parameter.optional ? (parameter.skippable ? ' | null' : ' | null | undefined') : '' %>,
11
- <% }); %> $config?: Omit<UseQueryOptions<<%~ it.returnType %>, TError, TData>, 'queryKey' | 'queryFn'>,
12
- $httpConfig?: XiorRequestConfig
13
- ) {
14
- return useQuery<<%~ it.returnType %>, TError, TData>({
15
- queryKey: <%= it.clientName %>.queryKeys.<%= it.rqOpName.charAt(3).toLowerCase() + it.rqOpName.slice(4) %>(<% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>),
16
- queryFn: () => <%= it.clientName %>Client.<%= it.name %>(<% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>$httpConfig).then(res => res.data),
17
- ...$config
18
- });
19
- },
2
+ if (it.jsDocs) {
3
+ const additionalParams = ` * @param $config (optional) Additional configuration for TanStack Query
4
+ * @param $httpConfig (optional) Additional configuration for xior request (actually executes the request)`;
5
+
6
+ // Replace the closing */ with newline + additional params + closing */
7
+ const modifiedDocs = it.jsDocs.replace(/(\s*)\*\/\s*$/, `\n${additionalParams}\n */`);
8
+ -%>
9
+ <%~ modifiedDocs %>
10
+ <% } else { -%>
11
+ <%~ it.jsDocs %>
12
+ <% } %>
13
+
14
+ export function <%= it.rqOpName %><TData = <%~ it.returnType %>, TError = Error>(<% it.parameters.forEach((parameter) => { %>
15
+ <%= parameter.name %><%= parameter.skippable ? '?' : '' %>: <%~ parameter.type %> <%= parameter.optional ? (parameter.skippable ? '| null' : '| null | undefined') : '' %>,
16
+ <% }); %>
17
+ $config?: Omit<
18
+ UseQueryOptions<<%~ it.returnType %>, TError, TData>,
19
+ 'queryKey' | 'queryFn'
20
+ >,
21
+ $httpConfig?: XiorRequestConfig
22
+ ) {
23
+ return useQuery<<%~ it.returnType %>, TError, TData>({
24
+ queryKey: ['<%= it.clientName %>', '<%= it.opKey %>', <% it.parameters.forEach((parameter) => { %><%= parameter.name %>, <% }); %>],
25
+ queryFn: () => <%= it.clientName %>Client.<%= it.name %>(<% it.parameters.forEach((parameter) => { %>
26
+ <%= parameter.name %>, <% }); %>$httpConfig).then(res => res.data),
27
+ ...$config
28
+ });
29
+ }
30
+ <%= it.rqOpName %>.queryKeys = ['<%= it.clientName %>', '<%= it.opKey %>'];
@@ -1,32 +0,0 @@
1
- <%
2
- var hasParams = it.parameters.length > 0;
3
-
4
- var variablesType;
5
- if (!hasParams) {
6
- variablesType = 'void';
7
- } else {
8
- var parts = it.parameters.map(function(p) {
9
- return p.name + (p.skippable ? '?' : '') + ': ' + p.type + (p.optional ? ' | null' : '');
10
- });
11
- variablesType = '{ ' + parts.join('; ') + ' }';
12
- }
13
-
14
- var callArgs = it.parameters.map(function(p) { return 'arg.' + p.name; });
15
-
16
- // Stable SWR key: replace all ${...} path expressions with *
17
- var swrKey = it.url.replace(/\$\{(?:[^{}]|\{[^{}]*\})*\}/g, '*');
18
-
19
- var docs = it.jsDocs ? it.jsDocs.replace(/^/gm, ' ') + '\n' : '';
20
- %>
21
- <%~ docs %>
22
- <%= it.mutOpName %>(
23
- $config?: SWRMutationConfiguration<<%~ it.returnType %>, Error, string, <%~ variablesType %>>,
24
- $httpConfig?: AxiosRequestConfig
25
- ) {
26
- return useSWRMutation<<%~ it.returnType %>, Error, string, <%~ variablesType %>>(
27
- '<%= swrKey %>',
28
- (_key: string, { arg }<%= hasParams ? ': { arg: ' + variablesType + ' }' : '' %>) =>
29
- <%= it.clientName %>Client.<%= it.name %>(<%= callArgs.join(', ') %><%= callArgs.length > 0 ? ', ' : '' %>$httpConfig).then((resp) => resp.data),
30
- $config
31
- );
32
- },
@@ -1,31 +0,0 @@
1
- <%
2
- var hasParams = it.parameters.length > 0;
3
-
4
- var variablesType;
5
- if (!hasParams) {
6
- variablesType = 'void';
7
- } else {
8
- var parts = it.parameters.map(function(p) {
9
- return p.name + (p.skippable ? '?' : '') + ': ' + p.type + (p.optional ? ' | null' : '');
10
- });
11
- variablesType = '{ ' + parts.join('; ') + ' }';
12
- }
13
-
14
- var callArgs = it.parameters.map(function(p) { return 'vars.' + p.name; });
15
-
16
- var baseAdditionalParams = ' * @param $config (optional) Additional configuration for TanStack Query\n * @param $httpConfig (optional) Additional configuration for xior request (actually executes the request)';
17
- var rawDocs = it.jsDocs
18
- ? it.jsDocs.replace(/(\s*)\*\/\s*$/, '\n' + baseAdditionalParams + '\n */')
19
- : '';
20
- var docs = rawDocs ? rawDocs.replace(/^/gm, ' ') + '\n' : '';
21
- %>
22
- <%~ docs %>
23
- <%= it.mutOpName %><TData = <%~ it.returnType %>, TError = Error>(
24
- $config?: UseMutationOptions<<%~ it.returnType %>, TError, <%~ variablesType %>>,
25
- $httpConfig?: XiorRequestConfig
26
- ) {
27
- return useMutation<<%~ it.returnType %>, TError, <%~ variablesType %>>({
28
- mutationFn: (<%= hasParams ? 'vars' : '' %>) => <%= it.clientName %>Client.<%= it.name %>(<%= callArgs.join(', ') %><%= callArgs.length > 0 ? ', ' : '' %>$httpConfig).then(res => res.data),
29
- ...$config
30
- });
31
- },