diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dddb724..6fa7d6e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -47,3 +47,7 @@ jobs: - name: Run test run: pnpm test + + - name: Report coverage + if: always() && matrix.os == 'ubuntu-latest' + uses: davelosert/vitest-coverage-report-action@v2 diff --git a/.gitignore b/.gitignore index cf4419f..a9ecaad 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,4 @@ dist-ssr openapi *.tsbuildinfo +coverage diff --git a/package.json b/package.json index 36aa440..de9921f 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "preview": "npm run build && npm -C examples/react-app run generate:api", "prepublishOnly": "npm run build", "release": "npx git-ensure -a && npx bumpp --commit --tag --push", - "test": "vitest" + "test": "vitest --coverage.enabled true" }, "repository": { "type": "git", @@ -40,6 +40,7 @@ "devDependencies": { "@hey-api/openapi-ts": "0.36.0", "@types/node": "^20.10.6", + "@vitest/coverage-v8": "^1.5.0", "commander": "^12.0.0", "glob": "^10.3.10", "rimraf": "^5.0.5", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fdd1b5e..af3bd4a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: '@types/node': specifier: ^20.10.6 version: 20.12.2 + '@vitest/coverage-v8': + specifier: ^1.5.0 + version: 1.5.0(vitest@1.5.0(@types/node@20.12.2)) commander: specifier: ^12.0.0 version: 12.0.0 @@ -165,6 +168,11 @@ packages: engines: {node: '>=6.0.0'} hasBin: true + '@babel/parser@7.24.4': + resolution: {integrity: sha512-zTvEBcghmeBma9QIGunWevvBAp4/Qu9Bdq+2k0Ot4fVMD6v3dsC9WOcRSKk7tRRyBM/53yKMJko9xOatGQAwSg==} + engines: {node: '>=6.0.0'} + hasBin: true + '@babel/plugin-transform-react-jsx-self@7.24.1': resolution: {integrity: sha512-kDJgnPujTmAZ/9q2CN4m2/lRsUUPDvsG3+tSHWUJIzMGTt5U/b/fwWd3RO3n+5mjLrsBrVa5eKFRVSQbi3dF1w==} engines: {node: '>=6.9.0'} @@ -189,6 +197,9 @@ packages: resolution: {integrity: sha512-+j7a5c253RfKh8iABBhywc8NSfP5LURe7Uh4qpsh6jc+aLJguvmIUBdjSdEMQv2bENrCR5MfRdjGo7vzS/ob7w==} engines: {node: '>=6.9.0'} + '@bcoe/v8-coverage@0.2.3': + resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} + '@esbuild/aix-ppc64@0.20.2': resolution: {integrity: sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==} engines: {node: '>=12'} @@ -345,6 +356,10 @@ packages: resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} engines: {node: '>=12'} + '@istanbuljs/schema@0.1.3': + resolution: {integrity: sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==} + engines: {node: '>=8'} + '@jest/schemas@29.6.3': resolution: {integrity: sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -589,6 +604,11 @@ packages: peerDependencies: vite: ^4.2.0 || ^5.0.0 + '@vitest/coverage-v8@1.5.0': + resolution: {integrity: sha512-1igVwlcqw1QUMdfcMlzzY4coikSIBN944pkueGi0pawrX5I5Z+9hxdTR+w3Sg6Q3eZhvdMAs8ZaF9JuTG1uYOQ==} + peerDependencies: + vitest: 1.5.0 + '@vitest/expect@1.5.0': resolution: {integrity: sha512-0pzuCI6KYi2SIC3LQezmxujU9RK/vwC1U9R0rLuGlNGcOuDWxqWKu6nUdFsX9tH1WU0SXtAxToOsEjeUn1s3hA==} @@ -1035,6 +1055,9 @@ packages: resolution: {integrity: sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==} engines: {node: '>= 8'} + fs.realpath@1.0.0: + resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -1086,6 +1109,9 @@ packages: engines: {node: '>=16 || 14 >=14.17'} hasBin: true + glob@7.2.3: + resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} + globals@11.12.0: resolution: {integrity: sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==} engines: {node: '>=4'} @@ -1141,6 +1167,9 @@ packages: hosted-git-info@2.8.9: resolution: {integrity: sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==} + html-escaper@2.0.2: + resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} + http-proxy-agent@5.0.0: resolution: {integrity: sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==} engines: {node: '>= 6'} @@ -1160,6 +1189,9 @@ packages: resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} engines: {node: '>=0.10.0'} + inflight@1.0.6: + resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} + inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} @@ -1265,6 +1297,22 @@ packages: isomorphic-fetch@3.0.0: resolution: {integrity: sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==} + istanbul-lib-coverage@3.2.2: + resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==} + engines: {node: '>=8'} + + istanbul-lib-report@3.0.1: + resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==} + engines: {node: '>=10'} + + istanbul-lib-source-maps@5.0.4: + resolution: {integrity: sha512-wHOoEsNJTVltaJp8eVkm8w+GVkVNHT2YDYo53YdzQEL2gWm1hBX5cGFR9hQJtuGLebidVX7et3+dmDZrmclduw==} + engines: {node: '>=10'} + + istanbul-reports@3.1.7: + resolution: {integrity: sha512-BewmUXImeuRk2YY0PVbxgKAysvhRPUQE0h5QRM++nVWyubKGV0l8qQ5op8+B2DOmwSe63Jivj0BjkPQVf8fP5g==} + engines: {node: '>=8'} + jackspeak@2.3.6: resolution: {integrity: sha512-N3yCS/NegsOBokc8GAdM8UcmfsKiSS8cipheD/nivzr700H+nsMOxJjQnvwOcRYVuFkdH0wGUvW2WbXGmrZGbQ==} engines: {node: '>=14'} @@ -1373,6 +1421,13 @@ packages: magic-string@0.30.10: resolution: {integrity: sha512-iIRwTIf0QKV3UAnYK4PU8uiEc4SRh5jX0mwpIwETPpHdhVM4f53RSwS/vXvN1JhGX+Cs7B8qIq3d6AH49O5fAQ==} + magicast@0.3.4: + resolution: {integrity: sha512-TyDF/Pn36bBji9rWKHlZe+PZb6Mx5V8IHCSxk7X4aljM4e/vyDvZZYwHewdVaqiA0nb3ghfHU/6AUpDxWoER2Q==} + + make-dir@4.0.0: + resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} + engines: {node: '>=10'} + media-typer@0.3.0: resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==} engines: {node: '>= 0.6'} @@ -1528,6 +1583,9 @@ packages: ohash@1.1.3: resolution: {integrity: sha512-zuHHiGTYTA1sYJ/wZN+t5HKZaH23i4yI1HMwbuXm24Nid7Dv0KcuRlKoNKS9UNfAVSBlnGLcuQrnOKWOZoEGaw==} + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + onetime@6.0.0: resolution: {integrity: sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==} engines: {node: '>=12'} @@ -1571,6 +1629,10 @@ packages: resolution: {integrity: sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==} engines: {node: '>=4'} + path-is-absolute@1.0.1: + resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} + engines: {node: '>=0.10.0'} + path-key@2.0.1: resolution: {integrity: sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==} engines: {node: '>=4'} @@ -1915,6 +1977,10 @@ packages: resolution: {integrity: sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==} engines: {node: '>=10'} + test-exclude@6.0.0: + resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} + engines: {node: '>=8'} + tinybench@2.7.0: resolution: {integrity: sha512-Qgayeb106x2o4hNzNjsZEfFziw8IbKqtbXBjVh7VIZfBxfD5M4gWtpyx5+YTae2gJ6Y6Dz/KLepiv16RFeQWNA==} @@ -2133,6 +2199,9 @@ packages: resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} engines: {node: '>=12'} + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + y18n@5.0.8: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} @@ -2273,6 +2342,10 @@ snapshots: dependencies: '@babel/types': 7.24.0 + '@babel/parser@7.24.4': + dependencies: + '@babel/types': 7.24.0 + '@babel/plugin-transform-react-jsx-self@7.24.1(@babel/core@7.24.3)': dependencies: '@babel/core': 7.24.3 @@ -2310,6 +2383,8 @@ snapshots: '@babel/helper-validator-identifier': 7.22.20 to-fast-properties: 2.0.0 + '@bcoe/v8-coverage@0.2.3': {} + '@esbuild/aix-ppc64@0.20.2': optional: true @@ -2401,6 +2476,8 @@ snapshots: wrap-ansi: 8.1.0 wrap-ansi-cjs: wrap-ansi@7.0.0 + '@istanbuljs/schema@0.1.3': {} + '@jest/schemas@29.6.3': dependencies: '@sinclair/typebox': 0.27.8 @@ -2732,6 +2809,25 @@ snapshots: transitivePeerDependencies: - supports-color + '@vitest/coverage-v8@1.5.0(vitest@1.5.0(@types/node@20.12.2))': + dependencies: + '@ampproject/remapping': 2.3.0 + '@bcoe/v8-coverage': 0.2.3 + debug: 4.3.4 + istanbul-lib-coverage: 3.2.2 + istanbul-lib-report: 3.0.1 + istanbul-lib-source-maps: 5.0.4 + istanbul-reports: 3.1.7 + magic-string: 0.30.10 + magicast: 0.3.4 + picocolors: 1.0.0 + std-env: 3.7.0 + strip-literal: 2.1.0 + test-exclude: 6.0.0 + vitest: 1.5.0(@types/node@20.12.2) + transitivePeerDependencies: + - supports-color + '@vitest/expect@1.5.0': dependencies: '@vitest/spy': 1.5.0 @@ -3275,6 +3371,8 @@ snapshots: dependencies: minipass: 3.3.6 + fs.realpath@1.0.0: {} + fsevents@2.3.3: optional: true @@ -3334,6 +3432,15 @@ snapshots: minipass: 7.0.4 path-scurry: 1.10.2 + glob@7.2.3: + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 3.1.2 + once: 1.4.0 + path-is-absolute: 1.0.1 + globals@11.12.0: {} globalthis@1.0.3: @@ -3381,6 +3488,8 @@ snapshots: hosted-git-info@2.8.9: {} + html-escaper@2.0.2: {} + http-proxy-agent@5.0.0: dependencies: '@tootallnate/once': 2.0.0 @@ -3404,6 +3513,11 @@ snapshots: dependencies: safer-buffer: 2.1.2 + inflight@1.0.6: + dependencies: + once: 1.4.0 + wrappy: 1.0.2 + inherits@2.0.4: {} internal-slot@1.0.7: @@ -3504,6 +3618,27 @@ snapshots: transitivePeerDependencies: - encoding + istanbul-lib-coverage@3.2.2: {} + + istanbul-lib-report@3.0.1: + dependencies: + istanbul-lib-coverage: 3.2.2 + make-dir: 4.0.0 + supports-color: 7.2.0 + + istanbul-lib-source-maps@5.0.4: + dependencies: + '@jridgewell/trace-mapping': 0.3.25 + debug: 4.3.4 + istanbul-lib-coverage: 3.2.2 + transitivePeerDependencies: + - supports-color + + istanbul-reports@3.1.7: + dependencies: + html-escaper: 2.0.2 + istanbul-lib-report: 3.0.1 + jackspeak@2.3.6: dependencies: '@isaacs/cliui': 8.0.2 @@ -3607,6 +3742,16 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.4.15 + magicast@0.3.4: + dependencies: + '@babel/parser': 7.24.4 + '@babel/types': 7.24.0 + source-map-js: 1.2.0 + + make-dir@4.0.0: + dependencies: + semver: 7.5.4 + media-typer@0.3.0: {} memorystream@0.3.1: {} @@ -3742,6 +3887,10 @@ snapshots: ohash@1.1.3: {} + once@1.4.0: + dependencies: + wrappy: 1.0.2 + onetime@6.0.0: dependencies: mimic-fn: 4.0.0 @@ -3783,6 +3932,8 @@ snapshots: path-exists@3.0.0: {} + path-is-absolute@1.0.1: {} + path-key@2.0.1: {} path-key@3.1.1: {} @@ -4157,6 +4308,12 @@ snapshots: mkdirp: 1.0.4 yallist: 4.0.0 + test-exclude@6.0.0: + dependencies: + '@istanbuljs/schema': 0.1.3 + glob: 7.2.3 + minimatch: 3.1.2 + tinybench@2.7.0: {} tinypool@0.8.4: {} @@ -4386,6 +4543,8 @@ snapshots: string-width: 5.1.2 strip-ansi: 7.1.0 + wrappy@1.0.2: {} + y18n@5.0.8: {} yallist@3.1.1: {} diff --git a/src/generate.mts b/src/generate.mts index 35b51eb..1df669d 100644 --- a/src/generate.mts +++ b/src/generate.mts @@ -19,12 +19,12 @@ export async function generate(options: UserConfig, version: string) { const typedKey = key as keyof UserConfig; const typedValue = value as (typeof options)[keyof UserConfig]; const parsedNumber = safeParseNumber(typedValue); - if (!isNaN(parsedNumber)) { - (acc as any)[typedKey] = parsedNumber; - } else if (value === "true") { + if (value === "true" || value === true) { (acc as any)[typedKey] = true; - } else if (value === "false") { + } else if (value === "false" || value === false) { (acc as any)[typedKey] = false; + } else if (!isNaN(parsedNumber)) { + (acc as any)[typedKey] = parsedNumber; } else { (acc as any)[typedKey] = typedValue; } diff --git a/tests/__snapshots__/createSource.test.ts.snap b/tests/__snapshots__/createSource.test.ts.snap new file mode 100644 index 0000000..9df2e05 --- /dev/null +++ b/tests/__snapshots__/createSource.test.ts.snap @@ -0,0 +1,82 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`createSource > createSource 1`] = ` +"// generated with @7nohe/openapi-react-query-codegen@1.0.0 +export * from "./common"; +export * from "./queries"; +" +`; + +exports[`createSource > createSource 2`] = ` +"// generated with @7nohe/openapi-react-query-codegen@1.0.0 +import { useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query"; +import { DefaultService, DefaultData } from "../requests"; +import { Pet, NewPet, Error } from "../requests/models"; +export type DefaultServiceFindPetsDefaultResponse = Awaited>; +export type DefaultServiceFindPetsQueryResult = UseQueryResult; +export const useDefaultServiceFindPetsKey = "DefaultServiceFindPets"; +export type DefaultServiceGetNotDefinedDefaultResponse = Awaited>; +export type DefaultServiceGetNotDefinedQueryResult = UseQueryResult; +export const useDefaultServiceGetNotDefinedKey = "DefaultServiceGetNotDefined"; +export type DefaultServiceFindPetByIdDefaultResponse = Awaited>; +export type DefaultServiceFindPetByIdQueryResult = UseQueryResult; +export const useDefaultServiceFindPetByIdKey = "DefaultServiceFindPetById"; +export type DefaultServiceAddPetMutationResult = Awaited>; +export type DefaultServicePostNotDefinedMutationResult = Awaited>; +export type DefaultServiceDeletePetMutationResult = Awaited>; +" +`; + +exports[`createSource > createSource 3`] = ` +"// generated with @7nohe/openapi-react-query-codegen@1.0.0 +import * as Common from "./common"; +import { useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query"; +import { DefaultService, DefaultData } from "../requests"; +import { Pet, NewPet, Error } from "../requests/models"; +export const useDefaultServiceFindPets = = unknown[]>({ limit, tags }: { + limit?: number; + tags?: string[]; +} = {}, queryKey?: TQueryKey, options?: Omit, "queryKey" | "queryFn">) => useQuery({ queryKey: [Common.useDefaultServiceFindPetsKey, ...(queryKey ?? [{ limit, tags }])], queryFn: () => DefaultService.findPets({ limit, tags }) as TData, ...options }); +/** + * @deprecated + */ +export const useDefaultServiceGetNotDefined = = unknown[]>(queryKey?: TQueryKey, options?: Omit, "queryKey" | "queryFn">) => useQuery({ queryKey: [Common.useDefaultServiceGetNotDefinedKey, ...(queryKey ?? [])], queryFn: () => DefaultService.getNotDefined() as TData, ...options }); +export const useDefaultServiceFindPetById = = unknown[]>({ id }: { + id: number; +}, queryKey?: TQueryKey, options?: Omit, "queryKey" | "queryFn">) => useQuery({ queryKey: [Common.useDefaultServiceFindPetByIdKey, ...(queryKey ?? [{ id }])], queryFn: () => DefaultService.findPetById({ id }) as TData, ...options }); +export const useDefaultServiceAddPet = (options?: Omit, "mutationFn">) => useMutation({ mutationFn: ({ requestBody }) => DefaultService.addPet({ requestBody }) as unknown as Promise, ...options }); +/** + * @deprecated + */ +export const useDefaultServicePostNotDefined = (options?: Omit, "mutationFn">) => useMutation({ mutationFn: () => DefaultService.postNotDefined() as unknown as Promise, ...options }); +export const useDefaultServiceDeletePet = (options?: Omit, "mutationFn">) => useMutation({ mutationFn: ({ id }) => DefaultService.deletePet({ id }) as unknown as Promise, ...options }); +" +`; + +exports[`createSource > createSource 4`] = ` +"// generated with @7nohe/openapi-react-query-codegen@1.0.0 +import * as Common from "./common"; +import { useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query"; +import { DefaultService, DefaultData } from "../requests"; +import { Pet, NewPet, Error } from "../requests/models"; +export const useDefaultServiceFindPetsSuspense = = unknown[]>({ limit, tags }: { + limit?: number; + tags?: string[]; +} = {}, queryKey?: TQueryKey, options?: Omit, "queryKey" | "queryFn">) => useSuspenseQuery({ queryKey: [Common.useDefaultServiceFindPetsKey, ...(queryKey ?? [{ limit, tags }])], queryFn: () => DefaultService.findPets({ limit, tags }) as TData, ...options }); +/** + * @deprecated + */ +export const useDefaultServiceGetNotDefinedSuspense = = unknown[]>(queryKey?: TQueryKey, options?: Omit, "queryKey" | "queryFn">) => useSuspenseQuery({ queryKey: [Common.useDefaultServiceGetNotDefinedKey, ...(queryKey ?? [])], queryFn: () => DefaultService.getNotDefined() as TData, ...options }); +export const useDefaultServiceFindPetByIdSuspense = = unknown[]>({ id }: { + id: number; +}, queryKey?: TQueryKey, options?: Omit, "queryKey" | "queryFn">) => useSuspenseQuery({ queryKey: [Common.useDefaultServiceFindPetByIdKey, ...(queryKey ?? [{ id }])], queryFn: () => DefaultService.findPetById({ id }) as TData, ...options }); +" +`; diff --git a/tests/common.test.ts b/tests/common.test.ts new file mode 100644 index 0000000..36411ed --- /dev/null +++ b/tests/common.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, test } from "vitest"; +import { BuildCommonTypeName, capitalizeFirstLetter, lowercaseFirstLetter, safeParseNumber } from "../src/common.mts"; + +describe("common", () => { + test("safeParseNumber", () => { + const parsed = safeParseNumber("123"); + expect(parsed).toBe(123); + + const nan = safeParseNumber("abc"); + expect(nan).toBeNaN(); + + const trueVal = safeParseNumber(true); + expect(trueVal).toBe(1); + + const falseVal = safeParseNumber(false); + expect(falseVal).toBe(0); + }); + + test("capitalizeFirstLetter", () => { + const capitalized = capitalizeFirstLetter("testTestTest"); + expect(capitalized).toBe("TestTestTest"); + }); + + test("lowercaseFirstLetter", () => { + const lowercased = lowercaseFirstLetter("TestTestTest"); + expect(lowercased).toBe("testTestTest"); + }); + + test('buildCommonTypeName', () => { + const name = 'Name'; + const result = BuildCommonTypeName(name); + expect(result.escapedText).toBe('Common.Name'); + }); +}); diff --git a/tests/createExports.test.ts b/tests/createExports.test.ts new file mode 100644 index 0000000..507b9cb --- /dev/null +++ b/tests/createExports.test.ts @@ -0,0 +1,71 @@ +import { afterAll, beforeAll, describe, expect, test } from "vitest"; +import { cleanOutputs, generateTSClients, outputPath } from "./utils"; +import { Project, SyntaxKind } from "ts-morph"; +import { createExports } from "../src/createExports.mts"; +import { getServices } from "../src/service.mts"; +import path from "path"; + +const fileName = "createExports" + +describe(fileName, () => { + beforeAll(async () => await generateTSClients(fileName)); + afterAll(async () => await cleanOutputs(fileName)); + + test("createExports", async () => { + const project = new Project({ + skipAddingFilesFromTsConfig: true, + }); + project.addSourceFilesAtPaths(path.join(outputPath(fileName), '**', '*')); + const service = await getServices(project); + const exports = createExports(service); + + const commonTypes = exports.allCommon + .filter((c) => c.kind === SyntaxKind.TypeAliasDeclaration) + // @ts-ignore + .map((e) => e.name.escapedText); + expect(commonTypes).toStrictEqual([ + "DefaultServiceFindPetsDefaultResponse", + "DefaultServiceFindPetsQueryResult", + "DefaultServiceGetNotDefinedDefaultResponse", + "DefaultServiceGetNotDefinedQueryResult", + "DefaultServiceFindPetByIdDefaultResponse", + "DefaultServiceFindPetByIdQueryResult", + "DefaultServiceAddPetMutationResult", + "DefaultServicePostNotDefinedMutationResult", + "DefaultServiceDeletePetMutationResult", + ]); + + const constants = exports.allCommon + .filter((c) => c.kind === SyntaxKind.VariableStatement) + // @ts-ignore + .map((c) => c.declarationList.declarations[0].name.escapedText); + expect(constants).toStrictEqual([ + "useDefaultServiceFindPetsKey", + "useDefaultServiceGetNotDefinedKey", + "useDefaultServiceFindPetByIdKey", + ]); + + const mainExports = exports.mainExports.map( + // @ts-ignore + (e) => e.declarationList.declarations[0].name.escapedText + ); + expect(mainExports).toStrictEqual([ + "useDefaultServiceFindPets", + "useDefaultServiceGetNotDefined", + "useDefaultServiceFindPetById", + "useDefaultServiceAddPet", + "useDefaultServicePostNotDefined", + "useDefaultServiceDeletePet", + ]); + + const suspenseExports = exports.suspenseExports.map( + // @ts-ignore + (e) => e.declarationList.declarations[0].name.escapedText + ); + expect(suspenseExports).toStrictEqual([ + "useDefaultServiceFindPetsSuspense", + "useDefaultServiceGetNotDefinedSuspense", + "useDefaultServiceFindPetByIdSuspense", + ]); + }); +}); diff --git a/tests/createImports.test.ts b/tests/createImports.test.ts new file mode 100644 index 0000000..81139ac --- /dev/null +++ b/tests/createImports.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, test } from "vitest"; +import { cleanOutputs, generateTSClients, outputPath } from "./utils"; +import { Project } from "ts-morph"; +import { createImports } from "../src/createImports.mts"; +import path from "path"; + +const fileName = "createImports"; + +describe(fileName, () => { + test("createImports", async () => { + await generateTSClients(fileName); + const project = new Project({ + skipAddingFilesFromTsConfig: true, + }); + project.addSourceFilesAtPaths(path.join(outputPath(fileName), "**", "*")); + const imports = createImports({ + serviceEndName: "Service", + project, + }); + + // @ts-ignore + const moduleNames = imports.map((i) => i.moduleSpecifier.text); + expect(moduleNames).toStrictEqual([ + "@tanstack/react-query", + "../requests", + "../requests/models", + ]); + await cleanOutputs(fileName); + }); + + test("createImports (No models)", async () => { + const fileName = "createImportsNoModels"; + await generateTSClients(fileName, "no-models.yaml"); + const project = new Project({ + skipAddingFilesFromTsConfig: true, + }); + project.addSourceFilesAtPaths(path.join(outputPath(fileName), "**", "*")); + const imports = createImports({ + serviceEndName: "Service", + project, + }); + + // @ts-ignore + const moduleNames = imports.map((i) => i.moduleSpecifier.text); + expect(moduleNames).toStrictEqual(["@tanstack/react-query", "../requests"]); + await cleanOutputs(fileName); + }); +}); diff --git a/tests/createSource.test.ts b/tests/createSource.test.ts new file mode 100644 index 0000000..429b476 --- /dev/null +++ b/tests/createSource.test.ts @@ -0,0 +1,29 @@ +import { afterAll, beforeAll, describe, expect, test } from "vitest"; +import { createSource } from '../src/createSource.mjs' +import { cleanOutputs, generateTSClients, outputPath } from "./utils"; +const fileName = "createSource"; +describe(fileName, () => { + beforeAll(async () => await generateTSClients(fileName)); + afterAll(async () => await cleanOutputs(fileName)); + + + test("createSource", async () => { + const source = await createSource({ + outputPath: outputPath(fileName), + version: "1.0.0", + serviceEndName: "Service", + }); + + const indexTs = source.find((s) => s.name === "index.ts"); + expect(indexTs?.content).toMatchSnapshot(); + + const commonTs = source.find((s) => s.name === "common.ts"); + expect(commonTs?.content).toMatchSnapshot(); + + const queriesTs = source.find((s) => s.name === "queries.ts"); + expect(queriesTs?.content).toMatchSnapshot(); + + const suspenseTs = source.find((s) => s.name === "suspense.ts"); + expect(suspenseTs?.content).toMatchSnapshot(); + }); +}); diff --git a/tests/generate.test.ts b/tests/generate.test.ts index e8bdc0c..5e655be 100644 --- a/tests/generate.test.ts +++ b/tests/generate.test.ts @@ -1,13 +1,14 @@ -import { readFileSync, rmdirSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import type { UserConfig } from "@hey-api/openapi-ts"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; import { generate } from "../src/generate.mjs"; +import { rmdir } from "node:fs/promises"; const readOutput = (fileName: string) => { return readFileSync( path.join(__dirname, "outputs", "queries", fileName), - "utf-8", + "utf-8" ); }; @@ -16,13 +17,16 @@ describe("generate", () => { const options: UserConfig = { input: path.join(__dirname, "inputs", "petstore.yaml"), output: path.join("tests", "outputs"), + lint: true, + format: false, }; await generate(options, "1.0.0"); }); - afterAll(() => { - // cleanup - rmdirSync(path.join(__dirname, "outputs"), { recursive: true }); + afterAll(async () => { + if (existsSync(path.join(__dirname, "outputs"))) { + await rmdir(path.join(__dirname, "outputs"), { recursive: true }); + } }); test("common.ts", () => { diff --git a/tests/inputs/no-models.yaml b/tests/inputs/no-models.yaml new file mode 100644 index 0000000..16e17d6 --- /dev/null +++ b/tests/inputs/no-models.yaml @@ -0,0 +1,105 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: Swagger Petstore + description: A sample API that uses a petstore as an example to demonstrate features in the OpenAPI 3.0 specification + termsOfService: http://swagger.io/terms/ + contact: + name: Swagger API Team + email: apiteam@swagger.io + url: http://swagger.io + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: http://petstore.swagger.io/api +paths: + /pets: + get: + description: | + Returns all pets from the system that the user has access to + Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia. + + Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien. + operationId: findPets + parameters: + - name: tags + in: query + description: tags to filter by + required: false + style: form + schema: + type: array + items: + type: string + - name: limit + in: query + description: maximum number of results to return + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: pet response + default: + description: unexpected error + post: + description: Creates a new pet in the store. Duplicates are allowed + operationId: addPet + requestBody: + description: Pet to add to the store + required: true + content: + application/json: + responses: + '200': + description: pet response + default: + description: unexpected error + /not-defined: + get: + deprecated: true + description: This path is not fully defined. + responses: + default: + description: unexpected error + post: + deprecated: true + description: This path is not defined at all. + responses: + default: + description: unexpected error + /pets/{id}: + get: + description: Returns a user based on a single ID, if the user does not have access to the pet + operationId: find pet by id + parameters: + - name: id + in: path + description: ID of pet to fetch + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: pet response + default: + description: unexpected error + delete: + description: deletes a single pet based on the ID supplied + operationId: deletePet + parameters: + - name: id + in: path + description: ID of pet to delete + required: true + schema: + type: integer + format: int64 + responses: + '204': + description: pet deleted + default: + description: unexpected error diff --git a/tests/service.test.ts b/tests/service.test.ts new file mode 100644 index 0000000..17617b6 --- /dev/null +++ b/tests/service.test.ts @@ -0,0 +1,30 @@ +import { afterAll, beforeAll, describe, expect, test } from "vitest"; +import { getServices } from "../src/service.mjs"; +import { Project } from "ts-morph"; +import { cleanOutputs, generateTSClients } from "./utils"; +import path from "path"; +const fileName = "service" +describe(fileName, () => { + beforeAll(async () => await generateTSClients(fileName)); + afterAll(async () => await cleanOutputs(fileName)); + + test("getServices", async () => { + const project = new Project({ + skipAddingFilesFromTsConfig: true, + }); + project.addSourceFilesAtPaths(path.join('tests', `${fileName}-outputs`, '**', '*')); + const service = await getServices(project); + const klass = service.klasses[0]; + expect(klass.className).toBe('DefaultService'); + const methodNames = klass.methods.map((m) => m.method.getName()); + expect(methodNames).toEqual(['findPets', 'addPet', 'getNotDefined', 'postNotDefined', 'findPetById', 'deletePet']); + }); + + test("getServices (No service node found)", async () => { + const project = new Project({ + skipAddingFilesFromTsConfig: true, + }); + project.addSourceFilesAtPaths(`no/services/**/*`); + await expect(() => getServices(project)).rejects.toThrowError("No service node found"); + }); +}); \ No newline at end of file diff --git a/tests/utils.ts b/tests/utils.ts new file mode 100644 index 0000000..55e518e --- /dev/null +++ b/tests/utils.ts @@ -0,0 +1,21 @@ +import { UserConfig, createClient } from "@hey-api/openapi-ts"; +import { existsSync } from "node:fs"; +import { rm } from "node:fs/promises"; +import path from "node:path"; +export const outputPath = (prefix: string) => + path.join("tests", `${prefix}-outputs`); + +export const generateTSClients = async (prefix: string, inputFile?: string) => { + const options: UserConfig = { + input: path.join(__dirname, "inputs", inputFile ?? "petstore.yaml"), + output: outputPath(prefix), + }; + await createClient(options); +}; + +export const cleanOutputs = async (prefix: string) => { + const output = `${prefix}-outputs`; + if (existsSync(path.join(__dirname, output))) { + await rm(path.join(__dirname, output), { recursive: true }); + } +}; diff --git a/vitest.config.ts b/vitest.config.ts index 77a73cf..e4609ef 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,5 +1,17 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ - test: {}, + test: { + coverage: { + reporter: ['text', 'json-summary', 'json', 'html'], + exclude: ['src/cli.mts', 'examples/**'], + reportOnFailure: true, + thresholds: { + lines: 95, + functions: 95, + statements: 95, + branches: 85, + } + } + }, });