diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 6fa7d6e..7456104 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -45,6 +45,10 @@ jobs:
- name: Run tsc
run: pnpm --filter @7nohe/react-app test:generated
+ - name: Run biome
+ run: pnpm biome check .
+ if: ${{ matrix.os == 'ubuntu-latest' }}
+
- name: Run test
run: pnpm test
diff --git a/biome.json b/biome.json
new file mode 100644
index 0000000..b18a81f
--- /dev/null
+++ b/biome.json
@@ -0,0 +1,26 @@
+{
+ "$schema": "https://biomejs.dev/schemas/1.7.2/schema.json",
+ "organizeImports": {
+ "enabled": true
+ },
+ "files": {
+ "ignore": [
+ "dist",
+ "examples/react-app/openapi",
+ "coverage",
+ "examples/nextjs-app/openapi",
+ "examples/nextjs-app/.next"
+ ]
+ },
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "recommended": true
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "indentStyle": "space",
+ "indentWidth": 2
+ }
+}
diff --git a/examples/nextjs-app/app/layout.tsx b/examples/nextjs-app/app/layout.tsx
index 96ea52e..c85a6e1 100644
--- a/examples/nextjs-app/app/layout.tsx
+++ b/examples/nextjs-app/app/layout.tsx
@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
-import Providers from './providers'
+import Providers from "./providers";
const inter = Inter({ subsets: ["latin"] });
diff --git a/examples/nextjs-app/app/page.tsx b/examples/nextjs-app/app/page.tsx
index 207d45e..fa9e68f 100644
--- a/examples/nextjs-app/app/page.tsx
+++ b/examples/nextjs-app/app/page.tsx
@@ -1,24 +1,24 @@
+import { prefetchUseDefaultServiceFindPets } from "@/openapi/queries/prefetch";
import {
- dehydrate,
HydrationBoundary,
QueryClient,
-} from '@tanstack/react-query'
-import { prefetchUseDefaultServiceFindPets } from "@/openapi/queries/prefetch";
+ dehydrate,
+} from "@tanstack/react-query";
import Pets from "./pets";
export default async function Home() {
- const queryClient = new QueryClient()
+ const queryClient = new QueryClient();
await prefetchUseDefaultServiceFindPets(queryClient, {
limit: 10,
tags: [],
- })
+ });
return (
-
-
+
+
);
}
diff --git a/examples/nextjs-app/app/pets.tsx b/examples/nextjs-app/app/pets.tsx
index 6953abd..e40fa9a 100644
--- a/examples/nextjs-app/app/pets.tsx
+++ b/examples/nextjs-app/app/pets.tsx
@@ -1,7 +1,7 @@
-'use client'
+"use client";
import { useDefaultServiceFindPets } from "@/openapi/queries";
-import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
+import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
export default function Pets() {
const { data } = useDefaultServiceFindPets({
@@ -11,7 +11,7 @@ export default function Pets() {
return (
<>
-
Pet List
+ Pet List
{Array.isArray(data) &&
data?.map((pet, index) => (
@@ -20,5 +20,5 @@ export default function Pets() {
>
- )
+ );
}
diff --git a/examples/nextjs-app/app/providers.tsx b/examples/nextjs-app/app/providers.tsx
index 164fb19..804498c 100644
--- a/examples/nextjs-app/app/providers.tsx
+++ b/examples/nextjs-app/app/providers.tsx
@@ -1,9 +1,9 @@
-'use client'
+"use client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// We can not useState or useRef in a server component, which is why we are
// extracting this part out into it's own file with 'use client' on top
-import { useState } from 'react'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { useState } from "react";
function makeQueryClient() {
return new QueryClient({
@@ -14,23 +14,22 @@ function makeQueryClient() {
staleTime: 60 * 1000,
},
},
- })
+ });
}
-let browserQueryClient: QueryClient | undefined = undefined
+let browserQueryClient: QueryClient | undefined = undefined;
function getQueryClient() {
- if (typeof window === 'undefined') {
+ if (typeof window === "undefined") {
// Server: always make a new query client
- return makeQueryClient()
- } else {
- // Browser: make a new query client if we don't already have one
- // This is very important so we don't re-make a new client if React
- // suspends during the initial render. This may not be needed if we
- // have a suspense boundary BELOW the creation of the query client
- if (!browserQueryClient) browserQueryClient = makeQueryClient()
- return browserQueryClient
+ return makeQueryClient();
}
+ // Browser: make a new query client if we don't already have one
+ // This is very important so we don't re-make a new client if React
+ // suspends during the initial render. This may not be needed if we
+ // have a suspense boundary BELOW the creation of the query client
+ if (!browserQueryClient) browserQueryClient = makeQueryClient();
+ return browserQueryClient;
}
export default function Providers({ children }: { children: React.ReactNode }) {
@@ -38,9 +37,9 @@ export default function Providers({ children }: { children: React.ReactNode }) {
// have a suspense boundary between this and the code that may
// suspend because React will throw away the client on the initial
// render if it suspends and there is no boundary
- const queryClient = getQueryClient()
+ const queryClient = getQueryClient();
return (
{children}
- )
+ );
}
diff --git a/examples/nextjs-app/request.ts b/examples/nextjs-app/request.ts
index 6e46d69..dd12c47 100644
--- a/examples/nextjs-app/request.ts
+++ b/examples/nextjs-app/request.ts
@@ -18,45 +18,48 @@ const axiosInstance = axios.create({
// Add a request interceptor
axiosInstance.interceptors.request.use(
- function (config) {
- // Do something before request is sent
- if (!config.url || !config.params) {
- return config;
- }
-
- Object.entries(config.params).forEach(([key, value]) => {
- const stringToSearch = `{${key}}`;
- if(config.url !== undefined && config.url.search(stringToSearch) !== -1) {
- config.url = config.url.replace(`{${key}}`, encodeURIComponent(value));
- delete config.params[key];
- }
- });
+ (config) => {
+ // Do something before request is sent
+ if (!config.url || !config.params) {
+ return config;
+ }
- return config;
- },
- function (error) {
- // Do something with request error
- return Promise.reject(error);
+ for (const [key, value] of Object.entries(config.params)) {
+ const stringToSearch = `{${key}}`;
+ if (
+ config.url !== undefined &&
+ config.url.search(stringToSearch) !== -1
+ ) {
+ config.url = config.url.replace(`{${key}}`, encodeURIComponent(value));
+ delete config.params[key];
+ }
}
+
+ return config;
+ },
+ (error) => {
+ // Do something with request error
+ return Promise.reject(error);
+ },
);
// Add a response interceptor
axiosInstance.interceptors.response.use(
- function (response) {
+ (response) => {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
},
- function (error) {
+ (error) => {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
- }
+ },
);
export const request = (
config: OpenAPIConfig,
- options: ApiRequestOptions
+ options: ApiRequestOptions,
): CancelablePromise => {
return new CancelablePromise((resolve, reject, onCancel) => {
onCancel(() => source.cancel("The user aborted a request."));
diff --git a/examples/react-app/package.json b/examples/react-app/package.json
index ce60b5f..e9f9755 100644
--- a/examples/react-app/package.json
+++ b/examples/react-app/package.json
@@ -9,18 +9,18 @@
"dev:mock": "prism mock ./petstore.yaml --dynamic",
"build": "tsc && vite build",
"preview": "vite preview",
- "generate:api": "rimraf ./openapi && node ../../dist/cli.mjs -i ./petstore.yaml -c axios --request ./request.ts",
+ "generate:api": "rimraf ./openapi && node ../../dist/cli.mjs -i ./petstore.yaml -c axios --request ./request.ts --format=biome --lint=biome",
"test:generated": "tsc -p ./tsconfig.openapi.json --noEmit"
},
"dependencies": {
"@tanstack/react-query": "^5.18.1",
"axios": "^1.6.7",
"form-data": "~4.0.0",
- "prettier": "^3.2.5",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
+ "@biomejs/biome": "1.7.2",
"@stoplight/prism-cli": "^5.5.2",
"@types/react": "^18.2.52",
"@types/react-dom": "^18.2.18",
diff --git a/examples/react-app/request.ts b/examples/react-app/request.ts
index 6e46d69..dd12c47 100644
--- a/examples/react-app/request.ts
+++ b/examples/react-app/request.ts
@@ -18,45 +18,48 @@ const axiosInstance = axios.create({
// Add a request interceptor
axiosInstance.interceptors.request.use(
- function (config) {
- // Do something before request is sent
- if (!config.url || !config.params) {
- return config;
- }
-
- Object.entries(config.params).forEach(([key, value]) => {
- const stringToSearch = `{${key}}`;
- if(config.url !== undefined && config.url.search(stringToSearch) !== -1) {
- config.url = config.url.replace(`{${key}}`, encodeURIComponent(value));
- delete config.params[key];
- }
- });
+ (config) => {
+ // Do something before request is sent
+ if (!config.url || !config.params) {
+ return config;
+ }
- return config;
- },
- function (error) {
- // Do something with request error
- return Promise.reject(error);
+ for (const [key, value] of Object.entries(config.params)) {
+ const stringToSearch = `{${key}}`;
+ if (
+ config.url !== undefined &&
+ config.url.search(stringToSearch) !== -1
+ ) {
+ config.url = config.url.replace(`{${key}}`, encodeURIComponent(value));
+ delete config.params[key];
+ }
}
+
+ return config;
+ },
+ (error) => {
+ // Do something with request error
+ return Promise.reject(error);
+ },
);
// Add a response interceptor
axiosInstance.interceptors.response.use(
- function (response) {
+ (response) => {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
},
- function (error) {
+ (error) => {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
- }
+ },
);
export const request = (
config: OpenAPIConfig,
- options: ApiRequestOptions
+ options: ApiRequestOptions,
): CancelablePromise => {
return new CancelablePromise((resolve, reject, onCancel) => {
onCancel(() => source.cancel("The user aborted a request."));
diff --git a/examples/react-app/src/App.tsx b/examples/react-app/src/App.tsx
index c0712fc..df58103 100644
--- a/examples/react-app/src/App.tsx
+++ b/examples/react-app/src/App.tsx
@@ -1,14 +1,14 @@
import "./App.css";
+import { useState } from "react";
import {
+ UseDefaultServiceFindPetsKeyFn,
useDefaultServiceAddPet,
useDefaultServiceFindPets,
- UseDefaultServiceFindPetsKeyFn,
useDefaultServiceGetNotDefined,
useDefaultServicePostNotDefined,
} from "../openapi/queries";
-import { useState } from "react";
-import { queryClient } from "./queryClient";
import { SuspenseParent } from "./components/SuspenseParent";
+import { queryClient } from "./queryClient";
function App() {
const [tags, _setTags] = useState([]);
@@ -17,7 +17,7 @@ function App() {
const { data, error, refetch } = useDefaultServiceFindPets({ tags, limit });
// This is an example of using a hook that has all parameters optional;
// Here we do not have to pass in an object
- const {} = useDefaultServiceFindPets();
+ const { data: _ } = useDefaultServiceFindPets();
// This is an example of a query that is not defined in the OpenAPI spec
// this defaults to any - here we are showing how to override the type
@@ -32,7 +32,9 @@ function App() {
return (
Failed to fetch pets
-
refetch()}>Retry
+
refetch()}>
+ Retry
+
);
@@ -40,12 +42,13 @@ function App() {
Pet List
- {data instanceof Array &&
+ {Array.isArray(data) &&
data?.map((pet, index) => (
- {pet.name}
+ {pet.name}
))}
{
addPet(
{
@@ -59,7 +62,7 @@ function App() {
console.log("success");
},
onError: (error) => console.error(error),
- }
+ },
);
}}
>
diff --git a/examples/react-app/src/main.tsx b/examples/react-app/src/main.tsx
index 8069014..947dbff 100644
--- a/examples/react-app/src/main.tsx
+++ b/examples/react-app/src/main.tsx
@@ -3,8 +3,8 @@ import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { QueryClientProvider } from "@tanstack/react-query";
-import { queryClient } from "./queryClient";
import { prefetchUseDefaultServiceFindPets } from "../openapi/queries/prefetch";
+import { queryClient } from "./queryClient";
async function PrefetchData() {
await prefetchUseDefaultServiceFindPets(queryClient);
@@ -16,6 +16,6 @@ PrefetchData().then(() => {
-
+ ,
);
});
diff --git a/examples/react-app/src/queryClient.tsx b/examples/react-app/src/queryClient.tsx
index 6d46de5..6c7b9de 100644
--- a/examples/react-app/src/queryClient.tsx
+++ b/examples/react-app/src/queryClient.tsx
@@ -1,3 +1,3 @@
-import { QueryClient } from '@tanstack/react-query';
+import { QueryClient } from "@tanstack/react-query";
export const queryClient = new QueryClient();
diff --git a/examples/react-app/vite.config.ts b/examples/react-app/vite.config.ts
index b1b5f91..1ff0da0 100644
--- a/examples/react-app/vite.config.ts
+++ b/examples/react-app/vite.config.ts
@@ -1,7 +1,7 @@
-import { defineConfig } from 'vite'
-import react from '@vitejs/plugin-react'
+import react from "@vitejs/plugin-react";
+import { defineConfig } from "vite";
// https://vitejs.dev/config/
export default defineConfig({
- plugins: [react()]
-})
+ plugins: [react()],
+});
diff --git a/lefthook.yml b/lefthook.yml
new file mode 100644
index 0000000..3e5f29e
--- /dev/null
+++ b/lefthook.yml
@@ -0,0 +1,8 @@
+pre-commit:
+ commands:
+ check:
+ glob: "*.{js,ts,cjs,mjs,d.cts,d.mts,jsx,tsx,json,jsonc}"
+ run: npx biome check --apply --no-errors-on-unmatched --files-ignore-unknown=true ./ && git update-index --again
+ test:
+ glob: "*.{js,ts,cjs,mjs,d.cts,d.mts,jsx,tsx,json,jsonc}"
+ run: npx vitest run
diff --git a/package.json b/package.json
index 9d98d4b..e22c704 100644
--- a/package.json
+++ b/package.json
@@ -6,9 +6,7 @@
"openapi-rq": "dist/cli.mjs"
},
"type": "module",
- "workspaces": [
- "examples/*"
- ],
+ "workspaces": ["examples/*"],
"scripts": {
"build": "rimraf dist && tsc -p tsconfig.json",
"preview": "npm run build && npm -C examples/react-app run generate:api",
@@ -22,9 +20,7 @@
},
"homepage": "https://github.com/7nohe/openapi-react-query-codegen",
"bugs": "https://github.com/7nohe/openapi-react-query-codegen/issues",
- "files": [
- "dist"
- ],
+ "files": ["dist"],
"keywords": [
"codegen",
"react-query",
@@ -38,11 +34,13 @@
"author": "Daiki Urata (@7nohe)",
"license": "MIT",
"devDependencies": {
+ "@biomejs/biome": "1.7.2",
"@hey-api/openapi-ts": "0.42.1",
"@types/node": "^20.10.6",
"@vitest/coverage-v8": "^1.5.0",
"commander": "^12.0.0",
"glob": "^10.3.10",
+ "lefthook": "^1.6.10",
"rimraf": "^5.0.5",
"ts-morph": "^22.0.0",
"typescript": "^5.3.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 79aca4c..e9b6a72 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -8,6 +8,9 @@ importers:
.:
devDependencies:
+ '@biomejs/biome':
+ specifier: 1.7.2
+ version: 1.7.2
'@hey-api/openapi-ts':
specifier: 0.42.1
version: 0.42.1(typescript@5.4.5)
@@ -23,6 +26,9 @@ importers:
glob:
specifier: ^10.3.10
version: 10.3.12
+ lefthook:
+ specifier: ^1.6.10
+ version: 1.6.10
rimraf:
specifier: ^5.0.5
version: 5.0.5
@@ -93,9 +99,6 @@ importers:
form-data:
specifier: ~4.0.0
version: 4.0.0
- prettier:
- specifier: ^3.2.5
- version: 3.2.5
react:
specifier: ^18.2.0
version: 18.2.0
@@ -103,6 +106,9 @@ importers:
specifier: ^18.2.0
version: 18.2.0(react@18.2.0)
devDependencies:
+ '@biomejs/biome':
+ specifier: 1.7.2
+ version: 1.7.2
'@stoplight/prism-cli':
specifier: ^5.5.2
version: 5.7.0
@@ -245,6 +251,59 @@ packages:
'@bcoe/v8-coverage@0.2.3':
resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==}
+ '@biomejs/biome@1.7.2':
+ resolution: {integrity: sha512-6Skx9N47inLQzYi9RKgJ7PBnUnaHnMe/imqX43cOcJjZtfMnQLxEvfM2Eyo7gChkwrZlwc+VbA4huFRjw2fsYA==}
+ engines: {node: '>=14.21.3'}
+ hasBin: true
+
+ '@biomejs/cli-darwin-arm64@1.7.2':
+ resolution: {integrity: sha512-CrldIueHivWEWmeTkK8bTXajeX53F8i2Rrkkt8cPZyMtzkrwxf8Riq4a/jz3SQBHkxHFT4TqGbSTNMXe3X1ogA==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@biomejs/cli-darwin-x64@1.7.2':
+ resolution: {integrity: sha512-UELnLJuJOsTL9meArvn8BtiXDURyPil2Ej9me2uVpEvee8UQdqd/bssP5we400OWShlL1AAML4fn6d2WX5332g==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@biomejs/cli-linux-arm64-musl@1.7.2':
+ resolution: {integrity: sha512-kKYZiem7Sj7wI0dpVxJlK7C+TFQwzO/ctufIGXGJAyEmUe9vEKSzV8CXpv+JIRiTWyqaZJ4K+eHz4SPdPCv05w==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@biomejs/cli-linux-arm64@1.7.2':
+ resolution: {integrity: sha512-Z1CSGQE6fHz55gkiFHv9E8wEAaSUd7dHSRaxSCBa7utonHqpIeMbvj3Evm1w0WfGLFDtRXLV1fTfEdM0FMTOhA==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@biomejs/cli-linux-x64-musl@1.7.2':
+ resolution: {integrity: sha512-x10LpGMepDrLS+h2TZ6/T7egpHjGKtiI4GuShNylmBQJWfTotbFf9eseHggrqJ4WZf9yrGoVYrtbxXftuB95sQ==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [linux]
+
+ '@biomejs/cli-linux-x64@1.7.2':
+ resolution: {integrity: sha512-vXXyox8/CQijBxAu0+r8FfSO7JlC4tob3PbaFda8gPJFRz2uFJw39HtxVUwbTV1EcU6wSPh4SiRu5sZfP1VHrQ==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [linux]
+
+ '@biomejs/cli-win32-arm64@1.7.2':
+ resolution: {integrity: sha512-kRXdlKzcU7INf6/ldu0nVmkOgt7bKqmyXRRCUqqaJfA32+9InTbkD8tGrHZEVYIWr+eTuKcg16qZVDsPSDFZ8g==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@biomejs/cli-win32-x64@1.7.2':
+ resolution: {integrity: sha512-qHTtpAs+CNglAAuaTy09htoqUhrQyd3nd0aGTuLNqD10h1llMVi8WFZfoa+e5MuDSfYtMK6nW2Tbf6WgzzR1Qw==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [win32]
+
'@esbuild/aix-ppc64@0.20.2':
resolution: {integrity: sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==}
engines: {node: '>=12'}
@@ -1529,6 +1588,50 @@ packages:
resolution: {integrity: sha512-zBfiUPM5nD0YZSBT/o/fbCUlCcepMIdP0CJZxM1+KgA4f2T206f6VAg9e7mX35+KlMaIc5qXW34f3BnwJ3w+RA==}
engines: {node: '>=12.0.0'}
+ lefthook-darwin-arm64@1.6.10:
+ resolution: {integrity: sha512-Hh11OkoKG7FEOByS1dcgNV7ETq45VmwBbw0VPTiBznyfOG4k+pi0fIdc1qbmbxvYqNE0r420QR/Q3bimaa4Kxg==}
+ cpu: [arm64]
+ os: [darwin]
+
+ lefthook-darwin-x64@1.6.10:
+ resolution: {integrity: sha512-FiOB0t5OBcQ8OnG/LSdfUYj736SJdlLjWuOZ4wTlJ7EUrHditieap6VNAxwMmFVyQN0X2ZwKWytwY35y+Hflhw==}
+ cpu: [x64]
+ os: [darwin]
+
+ lefthook-freebsd-arm64@1.6.10:
+ resolution: {integrity: sha512-IxGgS3RrNwk3Kr83o5SQhGxqppQi7fu2t//nsp6ocgnJeStrTtXZJOrel2VohzrFxpzQdJVXBGgUGLXtY8t8qw==}
+ cpu: [arm64]
+ os: [freebsd]
+
+ lefthook-freebsd-x64@1.6.10:
+ resolution: {integrity: sha512-sFSe+dGLa4iBblWAhAGTP9moarcbFtFAH6aaCeyqSX51O6p9VPdGjqNtcE8aGbGAk4lO6v1ScRjk5ogMSinJwQ==}
+ cpu: [x64]
+ os: [freebsd]
+
+ lefthook-linux-arm64@1.6.10:
+ resolution: {integrity: sha512-fXnKiNdRIW+FRvc1keVrvWX5EqIhVFfPjcy+PbsKdxiWRXgjtidi6LPmQ8eosH0DC9PxZ0mpdCMf40FHEZLbQA==}
+ cpu: [arm64]
+ os: [linux]
+
+ lefthook-linux-x64@1.6.10:
+ resolution: {integrity: sha512-bm6l2GOFnmYreZxmHb47QeOiFAItttOOxvCEX1okIRD7JbUC+lGC9evW5GJv/ltjZBoTDYEtQAUa+BpHTGuY2A==}
+ cpu: [x64]
+ os: [linux]
+
+ lefthook-windows-arm64@1.6.10:
+ resolution: {integrity: sha512-pFxT8KbOMzGxj6cz4glHYwQSNC7XCuy9RDqIO0AxPlpATsCpapkF4ngDxBT1iFv2VhdeweMa7RXUDsMAGQA4Qw==}
+ cpu: [arm64]
+ os: [win32]
+
+ lefthook-windows-x64@1.6.10:
+ resolution: {integrity: sha512-fcDnUSTv95AdLvm0NIrn3jBWXuRq8SlbDDjkkB5OHLiSmjz4eOr6wyD7xceDp33zZgZmWFzHebJngxxcIaUuHw==}
+ cpu: [x64]
+ os: [win32]
+
+ lefthook@1.6.10:
+ resolution: {integrity: sha512-HeVjsDCrHLe9htQHbLuQJu2YdLK6Tl5bh36fOpmXqckEXTI0BDR0Y5JYc7G5Inj4YXQsc51a9dUDZMeniSnSag==}
+ hasBin: true
+
lilconfig@2.1.0:
resolution: {integrity: sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==}
engines: {node: '>=10'}
@@ -1951,11 +2054,6 @@ packages:
resolution: {integrity: sha512-jOrdVvzUXBC7C+9gkIkpDJ3HIxOHTIqjpQ4C1EMt1ZGeMvSEpbFCKq23DEfgsj46vMnDgyQf+1ZLp2Wm+bKSsA==}
engines: {node: '>=10'}
- prettier@3.2.5:
- resolution: {integrity: sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==}
- engines: {node: '>=14'}
- hasBin: true
-
pretty-data@0.40.0:
resolution: {integrity: sha512-YFLnEdDEDnkt/GEhet5CYZHCvALw6+Elyb/tp8kQG03ZSIuzeaDWpZYndCXwgqu4NAjh1PI534dhDS1mHarRnQ==}
@@ -2673,6 +2771,41 @@ snapshots:
'@bcoe/v8-coverage@0.2.3': {}
+ '@biomejs/biome@1.7.2':
+ optionalDependencies:
+ '@biomejs/cli-darwin-arm64': 1.7.2
+ '@biomejs/cli-darwin-x64': 1.7.2
+ '@biomejs/cli-linux-arm64': 1.7.2
+ '@biomejs/cli-linux-arm64-musl': 1.7.2
+ '@biomejs/cli-linux-x64': 1.7.2
+ '@biomejs/cli-linux-x64-musl': 1.7.2
+ '@biomejs/cli-win32-arm64': 1.7.2
+ '@biomejs/cli-win32-x64': 1.7.2
+
+ '@biomejs/cli-darwin-arm64@1.7.2':
+ optional: true
+
+ '@biomejs/cli-darwin-x64@1.7.2':
+ optional: true
+
+ '@biomejs/cli-linux-arm64-musl@1.7.2':
+ optional: true
+
+ '@biomejs/cli-linux-arm64@1.7.2':
+ optional: true
+
+ '@biomejs/cli-linux-x64-musl@1.7.2':
+ optional: true
+
+ '@biomejs/cli-linux-x64@1.7.2':
+ optional: true
+
+ '@biomejs/cli-win32-arm64@1.7.2':
+ optional: true
+
+ '@biomejs/cli-win32-x64@1.7.2':
+ optional: true
+
'@esbuild/aix-ppc64@0.20.2':
optional: true
@@ -4052,6 +4185,41 @@ snapshots:
jsonpath-plus@7.2.0: {}
+ lefthook-darwin-arm64@1.6.10:
+ optional: true
+
+ lefthook-darwin-x64@1.6.10:
+ optional: true
+
+ lefthook-freebsd-arm64@1.6.10:
+ optional: true
+
+ lefthook-freebsd-x64@1.6.10:
+ optional: true
+
+ lefthook-linux-arm64@1.6.10:
+ optional: true
+
+ lefthook-linux-x64@1.6.10:
+ optional: true
+
+ lefthook-windows-arm64@1.6.10:
+ optional: true
+
+ lefthook-windows-x64@1.6.10:
+ optional: true
+
+ lefthook@1.6.10:
+ optionalDependencies:
+ lefthook-darwin-arm64: 1.6.10
+ lefthook-darwin-x64: 1.6.10
+ lefthook-freebsd-arm64: 1.6.10
+ lefthook-freebsd-x64: 1.6.10
+ lefthook-linux-arm64: 1.6.10
+ lefthook-linux-x64: 1.6.10
+ lefthook-windows-arm64: 1.6.10
+ lefthook-windows-x64: 1.6.10
+
lilconfig@2.1.0: {}
lilconfig@3.1.1: {}
@@ -4451,8 +4619,6 @@ snapshots:
dependencies:
punycode: 2.3.1
- prettier@3.2.5: {}
-
pretty-data@0.40.0: {}
pretty-format@29.7.0:
diff --git a/src/cli.mts b/src/cli.mts
index 9120cce..d5e5946 100644
--- a/src/cli.mts
+++ b/src/cli.mts
@@ -1,10 +1,10 @@
#!/usr/bin/env node
-import { generate } from "./generate.mjs";
-import { Command, Option } from "commander";
-import { readFile } from "fs/promises";
-import { dirname, join } from "path";
+import { readFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
+import { Command, Option } from "commander";
import { defaultOutputPath } from "./constants.mjs";
+import { generate } from "./generate.mjs";
const program = new Command();
@@ -38,57 +38,57 @@ async function setupProgram() {
.description("Generate React Query code based on OpenAPI")
.requiredOption(
"-i, --input ",
- "OpenAPI specification, can be a path, url or string content (required)"
+ "OpenAPI specification, can be a path, url or string content (required)",
)
.option("-o, --output ", "Output directory", defaultOutputPath)
.addOption(
new Option("-c, --client ", "HTTP client to generate")
.choices(["angular", "axios", "fetch", "node", "xhr"])
- .default("fetch")
+ .default("fetch"),
)
.option("--request ", "Path to custom request file")
.addOption(
new Option(
"--format ",
- "Process output folder with formatter?"
- ).choices(["biome", "prettier"])
+ "Process output folder with formatter?",
+ ).choices(["biome", "prettier"]),
)
.addOption(
new Option(
"--lint ",
- "Process output folder with linter?"
- ).choices(["biome", "eslint"])
+ "Process output folder with linter?",
+ ).choices(["biome", "eslint"]),
)
.option("--operationId", "Use operation ID to generate operation names?")
.addOption(
new Option(
"--serviceResponse ",
- "Define shape of returned value from service calls"
+ "Define shape of returned value from service calls",
)
.choices(["body", "response"])
- .default("body")
+ .default("body"),
)
.option(
"--base ",
- "Manually set base in OpenAPI config instead of inferring from server value"
+ "Manually set base in OpenAPI config instead of inferring from server value",
)
.addOption(
new Option(
"--enums ",
- "Generate JavaScript objects from enum definitions?"
- ).choices(["javascript", "typescript"])
+ "Generate JavaScript objects from enum definitions?",
+ ).choices(["javascript", "typescript"]),
)
.option(
"--useDateType",
- "Use Date type instead of string for date types for models, this will not convert the data to a Date object"
+ "Use Date type instead of string for date types for models, this will not convert the data to a Date object",
)
.option("--debug", "Run in debug mode?")
.option("--noSchemas", "Disable generating JSON schemas")
.addOption(
new Option(
"--schemaType ",
- "Type of JSON schema [Default: 'json']"
- ).choices(["form", "json"])
+ "Type of JSON schema [Default: 'json']",
+ ).choices(["form", "json"]),
)
.parse();
diff --git a/src/common.mts b/src/common.mts
index 9ea2709..6182a86 100644
--- a/src/common.mts
+++ b/src/common.mts
@@ -1,14 +1,15 @@
-import { type PathLike } from "fs";
-import { stat } from "fs/promises";
-import ts from "typescript";
-import path from "path";
-import {
+import type { PathLike } from "node:fs";
+import { stat } from "node:fs/promises";
+import path from "node:path";
+import type {
+ ClassDeclaration,
MethodDeclaration,
- SourceFile,
ParameterDeclaration,
- ClassDeclaration,
+ SourceFile,
+ Type,
} from "ts-morph";
-import { LimitedUserConfig } from "./cli.mjs";
+import ts from "typescript";
+import type { LimitedUserConfig } from "./cli.mjs";
import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";
export const TData = ts.factory.createIdentifier("TData");
@@ -16,11 +17,11 @@ export const TError = ts.factory.createIdentifier("TError");
export const TContext = ts.factory.createIdentifier("TContext");
export const EqualsOrGreaterThanToken = ts.factory.createToken(
- ts.SyntaxKind.EqualsGreaterThanToken
+ ts.SyntaxKind.EqualsGreaterThanToken,
);
export const QuestionToken = ts.factory.createToken(
- ts.SyntaxKind.QuestionToken
+ ts.SyntaxKind.QuestionToken,
);
export const queryKeyGenericType =
@@ -84,10 +85,10 @@ export function BuildCommonTypeName(name: string | ts.Identifier) {
*/
export function safeParseNumber(value: unknown): number {
const parsed = Number(value);
- if (!isNaN(parsed) && isFinite(parsed)) {
+ if (!Number.isNaN(parsed) && Number.isFinite(parsed)) {
return parsed;
}
- return NaN;
+ return Number.NaN;
}
export function extractPropertiesFromObjectParam(param: ParameterDeclaration) {
@@ -100,7 +101,7 @@ export function extractPropertiesFromObjectParam(param: ParameterDeclaration) {
.map((prop) => ({
name: prop.getName(),
optional: prop.isOptional(),
- type: prop.getValueDeclaration()?.getType()!,
+ type: prop.getValueDeclaration()?.getType() as Type,
}));
return paramNodes;
}
@@ -156,17 +157,19 @@ export function formatOptions(options: LimitedUserConfig) {
const typedValue = value as (typeof options)[keyof LimitedUserConfig];
const parsedNumber = safeParseNumber(typedValue);
if (value === "true" || value === true) {
- (acc as any)[typedKey] = true;
+ (acc as unknown as Record)[typedKey] = true;
} else if (value === "false" || value === false) {
- (acc as any)[typedKey] = false;
- } else if (!isNaN(parsedNumber)) {
- (acc as any)[typedKey] = parsedNumber;
+ (acc as unknown as Record)[typedKey] = false;
+ } else if (!Number.isNaN(parsedNumber)) {
+ (acc as unknown as Record)[typedKey] = parsedNumber;
} else {
- (acc as any)[typedKey] = typedValue;
+ (acc as unknown as Record)[
+ typedKey
+ ] = typedValue;
}
return acc;
},
- options
+ options,
);
return formattedOptions;
}
diff --git a/src/createExports.mts b/src/createExports.mts
index 5d9bf1f..75166a0 100644
--- a/src/createExports.mts
+++ b/src/createExports.mts
@@ -1,26 +1,26 @@
-import { createUseQuery } from "./createUseQuery.mjs";
-import { createUseMutation } from "./createUseMutation.mjs";
-import { Service } from "./service.mjs";
import { createPrefetch } from "./createPrefetch.mjs";
+import { createUseMutation } from "./createUseMutation.mjs";
+import { createUseQuery } from "./createUseQuery.mjs";
+import type { Service } from "./service.mjs";
export const createExports = (service: Service) => {
const { klasses } = service;
- const methods = klasses.map((k) => k.methods).flat();
+ const methods = klasses.flatMap((k) => k.methods);
const allGet = methods.filter((m) =>
- m.httpMethodName.toUpperCase().includes("GET")
+ m.httpMethodName.toUpperCase().includes("GET"),
);
const allPost = methods.filter((m) =>
- m.httpMethodName.toUpperCase().includes("POST")
+ m.httpMethodName.toUpperCase().includes("POST"),
);
const allPut = methods.filter((m) =>
- m.httpMethodName.toUpperCase().includes("PUT")
+ m.httpMethodName.toUpperCase().includes("PUT"),
);
const allPatch = methods.filter((m) =>
- m.httpMethodName.toUpperCase().includes("PATCH")
+ m.httpMethodName.toUpperCase().includes("PATCH"),
);
const allDelete = methods.filter((m) =>
- m.httpMethodName.toUpperCase().includes("DELETE")
+ m.httpMethodName.toUpperCase().includes("DELETE"),
);
const allGetQueries = allGet.map((m) => createUseQuery(m));
@@ -39,36 +39,36 @@ export const createExports = (service: Service) => {
...allDeleteMutations,
];
- const commonInQueries = allQueries
- .map(({ apiResponse, returnType, key, queryKeyFn }) => [
+ const commonInQueries = allQueries.flatMap(
+ ({ apiResponse, returnType, key, queryKeyFn }) => [
apiResponse,
returnType,
key,
queryKeyFn,
- ])
- .flat();
- const commonInMutations = allMutations
- .map(({ mutationResult }) => [mutationResult])
- .flat();
+ ],
+ );
+ const commonInMutations = allMutations.flatMap(({ mutationResult }) => [
+ mutationResult,
+ ]);
const allCommon = [...commonInQueries, ...commonInMutations];
- const mainQueries = allQueries.map(({ queryHook }) => [queryHook]).flat();
- const mainMutations = allMutations
- .map(({ mutationHook }) => [mutationHook])
- .flat();
+ const mainQueries = allQueries.flatMap(({ queryHook }) => [queryHook]);
+ const mainMutations = allMutations.flatMap(({ mutationHook }) => [
+ mutationHook,
+ ]);
const mainExports = [...mainQueries, ...mainMutations];
- const suspenseQueries = allQueries
- .map(({ suspenseQueryHook }) => [suspenseQueryHook])
- .flat();
+ const suspenseQueries = allQueries.flatMap(({ suspenseQueryHook }) => [
+ suspenseQueryHook,
+ ]);
const suspenseExports = [...suspenseQueries];
- const allPrefetches = allPrefetchQueries
- .map(({ prefetchHook }) => [prefetchHook])
- .flat();
+ const allPrefetches = allPrefetchQueries.flatMap(({ prefetchHook }) => [
+ prefetchHook,
+ ]);
const allPrefetchExports = [...allPrefetches];
diff --git a/src/createImports.mts b/src/createImports.mts
index 62fa92a..8f9bcff 100644
--- a/src/createImports.mts
+++ b/src/createImports.mts
@@ -1,6 +1,6 @@
+import { posix } from "node:path";
+import type { Project } from "ts-morph";
import ts from "typescript";
-import { posix } from "path";
-import { Project } from "ts-morph";
import { modalsFileName, serviceFileName } from "./constants.mjs";
const { join } = posix;
@@ -29,11 +29,11 @@ export const createImports = ({
: [];
const serviceExports = Array.from(
- serviceFile.getExportedDeclarations().keys()
+ serviceFile.getExportedDeclarations().keys(),
);
const serviceNames = serviceExports.filter((name) =>
- name.endsWith(serviceEndName)
+ name.endsWith(serviceEndName),
);
const imports = [
@@ -43,45 +43,50 @@ export const createImports = ({
false,
undefined,
ts.factory.createNamedImports([
+ ts.factory.createImportSpecifier(
+ true,
+ undefined,
+ ts.factory.createIdentifier("QueryClient"),
+ ),
ts.factory.createImportSpecifier(
false,
undefined,
- ts.factory.createIdentifier("useQuery")
+ ts.factory.createIdentifier("useQuery"),
),
ts.factory.createImportSpecifier(
false,
undefined,
- ts.factory.createIdentifier("useSuspenseQuery")
+ ts.factory.createIdentifier("useSuspenseQuery"),
),
ts.factory.createImportSpecifier(
false,
undefined,
- ts.factory.createIdentifier("useMutation")
+ ts.factory.createIdentifier("useMutation"),
),
ts.factory.createImportSpecifier(
false,
undefined,
- ts.factory.createIdentifier("UseQueryResult")
+ ts.factory.createIdentifier("UseQueryResult"),
),
ts.factory.createImportSpecifier(
false,
undefined,
- ts.factory.createIdentifier("UseQueryOptions")
+ ts.factory.createIdentifier("UseQueryOptions"),
),
ts.factory.createImportSpecifier(
false,
undefined,
- ts.factory.createIdentifier("UseMutationOptions")
+ ts.factory.createIdentifier("UseMutationOptions"),
),
ts.factory.createImportSpecifier(
false,
undefined,
- ts.factory.createIdentifier("UseMutationResult")
+ ts.factory.createIdentifier("UseMutationResult"),
),
- ])
+ ]),
),
ts.factory.createStringLiteral("@tanstack/react-query"),
- undefined
+ undefined,
),
ts.factory.createImportDeclaration(
undefined,
@@ -94,13 +99,13 @@ export const createImports = ({
ts.factory.createImportSpecifier(
false,
undefined,
- ts.factory.createIdentifier(serviceName)
- )
+ ts.factory.createIdentifier(serviceName),
+ ),
),
- ])
+ ]),
),
ts.factory.createStringLiteral(join("../requests", serviceFileName)),
- undefined
+ undefined,
),
];
if (modelsFile) {
@@ -116,14 +121,14 @@ export const createImports = ({
ts.factory.createImportSpecifier(
false,
undefined,
- ts.factory.createIdentifier(modelName)
- )
+ ts.factory.createIdentifier(modelName),
+ ),
),
- ])
+ ]),
),
ts.factory.createStringLiteral(join("../requests/", modalsFileName)),
- undefined
- )
+ undefined,
+ ),
);
}
return imports;
diff --git a/src/createPrefetch.mts b/src/createPrefetch.mts
index 71266a2..70729ee 100644
--- a/src/createPrefetch.mts
+++ b/src/createPrefetch.mts
@@ -1,11 +1,11 @@
+import type { MethodDeclaration } from "ts-morph";
import ts from "typescript";
-import { MethodDeclaration } from "ts-morph";
import {
BuildCommonTypeName,
extractPropertiesFromObjectParam,
getNameFromMethod,
} from "./common.mjs";
-import { type MethodDescription } from "./common.mjs";
+import type { MethodDescription } from "./common.mjs";
import {
createQueryKeyFromMethod,
getRequestParamFromMethod,
@@ -27,7 +27,9 @@ function createPrefetchHook({
}) {
const methodName = getNameFromMethod(method);
const queryName = hookNameFromMethod({ method, className });
- const customHookName = `prefetch${queryName.charAt(0).toUpperCase() + queryName.slice(1)}`;
+ const customHookName = `prefetch${
+ queryName.charAt(0).toUpperCase() + queryName.slice(1)
+ }`;
const queryKey = createQueryKeyFromMethod({ method, className });
// const
@@ -50,8 +52,8 @@ function createPrefetchHook({
"queryClient",
undefined,
ts.factory.createTypeReferenceNode(
- ts.factory.createIdentifier("QueryClient")
- )
+ ts.factory.createIdentifier("QueryClient"),
+ ),
),
...requestParams,
],
@@ -72,21 +74,20 @@ function createPrefetchHook({
ts.factory.createObjectLiteralExpression(
method
.getParameters()
- .map((param) =>
+ .flatMap((param) =>
extractPropertiesFromObjectParam(param).map(
(p) =>
ts.factory.createShorthandPropertyAssignment(
- ts.factory.createIdentifier(p.name)
- )
- )
- )
- .flat()
+ ts.factory.createIdentifier(p.name),
+ ),
+ ),
+ ),
),
])
: ts.factory.createArrayLiteralExpression([]),
],
- false
- )
+ false,
+ ),
),
ts.factory.createPropertyAssignment(
ts.factory.createIdentifier("queryFn"),
@@ -96,12 +97,12 @@ function createPrefetchHook({
[],
undefined,
ts.factory.createToken(
- ts.SyntaxKind.EqualsGreaterThanToken
+ ts.SyntaxKind.EqualsGreaterThanToken,
),
ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier(className),
- ts.factory.createIdentifier(methodName)
+ ts.factory.createIdentifier(methodName),
),
undefined,
method.getParameters().length
@@ -109,29 +110,28 @@ function createPrefetchHook({
ts.factory.createObjectLiteralExpression(
method
.getParameters()
- .map((param) =>
+ .flatMap((param) =>
extractPropertiesFromObjectParam(param).map(
(p) =>
ts.factory.createShorthandPropertyAssignment(
- ts.factory.createIdentifier(p.name)
- )
- )
- )
- .flat()
+ ts.factory.createIdentifier(p.name),
+ ),
+ ),
+ ),
),
]
- : undefined
- )
- )
+ : undefined,
+ ),
+ ),
),
]),
- ]
- )
- )
+ ],
+ ),
+ ),
),
],
- ts.NodeFlags.Const
- )
+ ts.NodeFlags.Const,
+ ),
);
return hookExport;
}
diff --git a/src/createSource.mts b/src/createSource.mts
index 385c131..2c4b9cf 100644
--- a/src/createSource.mts
+++ b/src/createSource.mts
@@ -1,9 +1,9 @@
-import ts from "typescript";
+import { join } from "node:path";
import { Project } from "ts-morph";
-import { join } from "path";
+import ts from "typescript";
import { OpenApiRqFiles } from "./constants.mjs";
-import { createImports } from "./createImports.mjs";
import { createExports } from "./createExports.mjs";
+import { createImports } from "./createImports.mjs";
import { getServices } from "./service.mjs";
const createSourceFile = async (outputPath: string, serviceEndName: string) => {
@@ -30,7 +30,7 @@ const createSourceFile = async (outputPath: string, serviceEndName: string) => {
const commonSource = ts.factory.createSourceFile(
[...imports, ...exports.allCommon],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
- ts.NodeFlags.None
+ ts.NodeFlags.None,
);
const commonImport = ts.factory.createImportDeclaration(
@@ -38,10 +38,10 @@ const createSourceFile = async (outputPath: string, serviceEndName: string) => {
ts.factory.createImportClause(
false,
ts.factory.createIdentifier("* as Common"),
- undefined
+ undefined,
),
ts.factory.createStringLiteral(`./${OpenApiRqFiles.common}`),
- undefined
+ undefined,
);
const commonExport = ts.factory.createExportDeclaration(
@@ -49,7 +49,7 @@ const createSourceFile = async (outputPath: string, serviceEndName: string) => {
false,
undefined,
ts.factory.createStringLiteral(`./${OpenApiRqFiles.common}`),
- undefined
+ undefined,
);
const queriesExport = ts.factory.createExportDeclaration(
@@ -57,31 +57,31 @@ const createSourceFile = async (outputPath: string, serviceEndName: string) => {
false,
undefined,
ts.factory.createStringLiteral(`./${OpenApiRqFiles.queries}`),
- undefined
+ undefined,
);
const mainSource = ts.factory.createSourceFile(
[commonImport, ...imports, ...exports.mainExports],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
- ts.NodeFlags.None
+ ts.NodeFlags.None,
);
const suspenseSource = ts.factory.createSourceFile(
[commonImport, ...imports, ...exports.suspenseExports],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
- ts.NodeFlags.None
+ ts.NodeFlags.None,
);
const indexSource = ts.factory.createSourceFile(
[commonExport, queriesExport],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
- ts.NodeFlags.None
+ ts.NodeFlags.None,
);
const prefetchSource = ts.factory.createSourceFile(
[commonImport, ...imports, ...exports.allPrefetchExports],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
- ts.NodeFlags.None
+ ts.NodeFlags.None,
);
return {
@@ -107,21 +107,21 @@ export const createSource = async ({
"",
ts.ScriptTarget.Latest,
false,
- ts.ScriptKind.TS
+ ts.ScriptKind.TS,
);
const commonFile = ts.createSourceFile(
`${OpenApiRqFiles.common}.ts`,
"",
ts.ScriptTarget.Latest,
false,
- ts.ScriptKind.TS
+ ts.ScriptKind.TS,
);
const suspenseFile = ts.createSourceFile(
`${OpenApiRqFiles.suspense}.ts`,
"",
ts.ScriptTarget.Latest,
false,
- ts.ScriptKind.TS
+ ts.ScriptKind.TS,
);
const indexFile = ts.createSourceFile(
@@ -129,7 +129,7 @@ export const createSource = async ({
"",
ts.ScriptTarget.Latest,
false,
- ts.ScriptKind.TS
+ ts.ScriptKind.TS,
);
const prefetchFile = ts.createSourceFile(
@@ -137,7 +137,7 @@ export const createSource = async ({
"",
ts.ScriptTarget.Latest,
false,
- ts.ScriptKind.TS
+ ts.ScriptKind.TS,
);
const printer = ts.createPrinter({
diff --git a/src/createUseMutation.mts b/src/createUseMutation.mts
index e8deea0..ad7eaca 100644
--- a/src/createUseMutation.mts
+++ b/src/createUseMutation.mts
@@ -1,7 +1,7 @@
import ts from "typescript";
import {
BuildCommonTypeName,
- MethodDescription,
+ type MethodDescription,
TContext,
TData,
TError,
@@ -31,13 +31,13 @@ function generateAwaitedReturnType({
ts.factory.createTypeQueryNode(
ts.factory.createQualifiedName(
ts.factory.createIdentifier(className),
- ts.factory.createIdentifier(methodName)
+ ts.factory.createIdentifier(methodName),
),
- undefined
+ undefined,
),
- ]
+ ],
),
- ]
+ ],
);
}
@@ -55,40 +55,39 @@ export const createUseMutation = ({
const mutationResult = ts.factory.createTypeAliasDeclaration(
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
ts.factory.createIdentifier(
- `${className}${capitalizeFirstLetter(methodName)}MutationResult`
+ `${className}${capitalizeFirstLetter(methodName)}MutationResult`,
),
undefined,
- awaitedResponseDataType
+ awaitedResponseDataType,
);
const responseDataType = ts.factory.createTypeParameterDeclaration(
undefined,
TData,
undefined,
- ts.factory.createTypeReferenceNode(BuildCommonTypeName(mutationResult.name))
+ ts.factory.createTypeReferenceNode(
+ BuildCommonTypeName(mutationResult.name),
+ ),
);
const methodParameters =
method.getParameters().length !== 0
? ts.factory.createTypeLiteralNode(
- method
- .getParameters()
- .map((param) => {
- const paramNodes = extractPropertiesFromObjectParam(param);
- return paramNodes.map((refParam) =>
- ts.factory.createPropertySignature(
- undefined,
- ts.factory.createIdentifier(refParam.name),
- refParam.optional
- ? ts.factory.createToken(ts.SyntaxKind.QuestionToken)
- : undefined,
- ts.factory.createTypeReferenceNode(
- getShortType(refParam.type.getText(param))
- )
- )
- );
- })
- .flat()
+ method.getParameters().flatMap((param) => {
+ const paramNodes = extractPropertiesFromObjectParam(param);
+ return paramNodes.map((refParam) =>
+ ts.factory.createPropertySignature(
+ undefined,
+ ts.factory.createIdentifier(refParam.name),
+ refParam.optional
+ ? ts.factory.createToken(ts.SyntaxKind.QuestionToken)
+ : undefined,
+ ts.factory.createTypeReferenceNode(
+ getShortType(refParam.type.getText(param)),
+ ),
+ ),
+ );
+ }),
)
: ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword);
@@ -98,7 +97,7 @@ export const createUseMutation = ({
[
ts.factory.createVariableDeclaration(
ts.factory.createIdentifier(
- `use${className}${capitalizeFirstLetter(methodName)}`
+ `use${className}${capitalizeFirstLetter(methodName)}`,
),
undefined,
undefined,
@@ -110,13 +109,13 @@ export const createUseMutation = ({
undefined,
TError,
undefined,
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
),
ts.factory.createTypeParameterDeclaration(
undefined,
TContext,
undefined,
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
),
]),
[
@@ -135,14 +134,14 @@ export const createUseMutation = ({
ts.factory.createTypeReferenceNode(TError),
methodParameters,
ts.factory.createTypeReferenceNode(TContext),
- ]
+ ],
),
ts.factory.createLiteralTypeNode(
- ts.factory.createStringLiteral("mutationFn")
+ ts.factory.createStringLiteral("mutationFn"),
),
- ]
+ ],
),
- undefined
+ undefined,
),
],
undefined,
@@ -168,86 +167,80 @@ export const createUseMutation = ({
undefined,
undefined,
ts.factory.createObjectBindingPattern(
- method
- .getParameters()
- .map((param) => {
- const paramNodes =
- extractPropertiesFromObjectParam(param);
- return paramNodes.map((refParam) =>
- ts.factory.createBindingElement(
- undefined,
- undefined,
- ts.factory.createIdentifier(
- refParam.name
- ),
- undefined
- )
- );
- })
- .flat()
+ method.getParameters().flatMap((param) => {
+ const paramNodes =
+ extractPropertiesFromObjectParam(param);
+ return paramNodes.map((refParam) =>
+ ts.factory.createBindingElement(
+ undefined,
+ undefined,
+ ts.factory.createIdentifier(
+ refParam.name,
+ ),
+ undefined,
+ ),
+ );
+ }),
),
undefined,
undefined,
- undefined
+ undefined,
),
]
: [],
undefined,
ts.factory.createToken(
- ts.SyntaxKind.EqualsGreaterThanToken
+ ts.SyntaxKind.EqualsGreaterThanToken,
),
ts.factory.createAsExpression(
ts.factory.createAsExpression(
ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier(className),
- ts.factory.createIdentifier(methodName)
+ ts.factory.createIdentifier(methodName),
),
undefined,
method.getParameters().length !== 0
? [
ts.factory.createObjectLiteralExpression(
- method
- .getParameters()
- .map((params) => {
- const paramNodes =
- extractPropertiesFromObjectParam(
- params
- );
- return paramNodes.map((refParam) =>
- ts.factory.createShorthandPropertyAssignment(
- refParam.name
- )
+ method.getParameters().flatMap((params) => {
+ const paramNodes =
+ extractPropertiesFromObjectParam(
+ params,
);
- })
- .flat()
+ return paramNodes.map((refParam) =>
+ ts.factory.createShorthandPropertyAssignment(
+ refParam.name,
+ ),
+ );
+ }),
),
]
- : []
+ : [],
),
ts.factory.createKeywordTypeNode(
- ts.SyntaxKind.UnknownKeyword
- )
+ ts.SyntaxKind.UnknownKeyword,
+ ),
),
ts.factory.createTypeReferenceNode(
ts.factory.createIdentifier("Promise"),
- [ts.factory.createTypeReferenceNode(TData)]
- )
- )
- )
+ [ts.factory.createTypeReferenceNode(TData)],
+ ),
+ ),
+ ),
),
ts.factory.createSpreadAssignment(
- ts.factory.createIdentifier("options")
+ ts.factory.createIdentifier("options"),
),
]),
- ]
- )
- )
+ ],
+ ),
+ ),
),
],
- ts.NodeFlags.Const
- )
+ ts.NodeFlags.Const,
+ ),
);
const hookWithJsDoc = addJSDocToNode(exportHook, jsDoc);
diff --git a/src/createUseQuery.mts b/src/createUseQuery.mts
index 34554a3..ea91907 100644
--- a/src/createUseQuery.mts
+++ b/src/createUseQuery.mts
@@ -1,20 +1,20 @@
+import type { MethodDeclaration } from "ts-morph";
import ts from "typescript";
-import { MethodDeclaration } from "ts-morph";
import {
BuildCommonTypeName,
- capitalizeFirstLetter,
EqualsOrGreaterThanToken,
+ QuestionToken,
+ TData,
+ TError,
+ capitalizeFirstLetter,
extractPropertiesFromObjectParam,
getNameFromMethod,
getShortType,
queryKeyConstraint,
queryKeyGenericType,
- QuestionToken,
- TData,
- TError,
} from "./common.mjs";
+import type { MethodDescription } from "./common.mjs";
import { addJSDocToNode } from "./util.mjs";
-import { type MethodDescription } from "./common.mjs";
export const createApiResponseType = ({
className,
@@ -33,13 +33,13 @@ export const createApiResponseType = ({
ts.factory.createTypeQueryNode(
ts.factory.createQualifiedName(
ts.factory.createIdentifier(className),
- ts.factory.createIdentifier(methodName)
+ ts.factory.createIdentifier(methodName),
),
- undefined
+ undefined,
),
- ]
+ ],
),
- ]
+ ],
);
/** DefaultResponseDataType
* export type MyClassMethodDefaultResponse = Awaited>
@@ -48,18 +48,18 @@ export const createApiResponseType = ({
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
ts.factory.createIdentifier(
`${capitalizeFirstLetter(className)}${capitalizeFirstLetter(
- methodName
- )}DefaultResponse`
+ methodName,
+ )}DefaultResponse`,
),
undefined,
- awaitedResponseDataType
+ awaitedResponseDataType,
);
const responseDataType = ts.factory.createTypeParameterDeclaration(
undefined,
TData.text,
undefined,
- ts.factory.createTypeReferenceNode(BuildCommonTypeName(apiResponse.name))
+ ts.factory.createTypeReferenceNode(BuildCommonTypeName(apiResponse.name)),
);
return {
@@ -83,17 +83,14 @@ export function getRequestParamFromMethod(method: MethodDeclaration) {
return null;
}
- const params = method
- .getParameters()
- .map((param) => {
- const paramNodes = extractPropertiesFromObjectParam(param);
- return paramNodes.map((refParam) => ({
- name: refParam.name,
- typeName: getShortType(refParam.type.getText()),
- optional: refParam.optional,
- }));
- })
- .flat();
+ const params = method.getParameters().flatMap((param) => {
+ const paramNodes = extractPropertiesFromObjectParam(param);
+ return paramNodes.map((refParam) => ({
+ name: refParam.name,
+ typeName: getShortType(refParam.type.getText()),
+ optional: refParam.optional,
+ }));
+ });
const areAllPropertiesOptional = params.every((param) => param.optional);
@@ -106,9 +103,9 @@ export function getRequestParamFromMethod(method: MethodDeclaration) {
undefined,
undefined,
ts.factory.createIdentifier(refParam.name),
- undefined
- )
- )
+ undefined,
+ ),
+ ),
),
undefined,
ts.factory.createTypeLiteralNode(
@@ -119,15 +116,15 @@ export function getRequestParamFromMethod(method: MethodDeclaration) {
refParam.optional
? ts.factory.createToken(ts.SyntaxKind.QuestionToken)
: undefined,
- ts.factory.createTypeReferenceNode(refParam.typeName)
+ ts.factory.createTypeReferenceNode(refParam.typeName),
);
- })
+ }),
),
// if all params are optional, we create an empty object literal
// so the hook can be called without any parameters
areAllPropertiesOptional
? ts.factory.createObjectLiteralExpression()
- : undefined
+ : undefined,
);
}
@@ -149,21 +146,21 @@ export function createReturnTypeExport({
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
ts.factory.createIdentifier(
`${capitalizeFirstLetter(className)}${capitalizeFirstLetter(
- methodName
- )}QueryResult`
+ methodName,
+ )}QueryResult`,
),
[
ts.factory.createTypeParameterDeclaration(
undefined,
TData,
undefined,
- ts.factory.createTypeReferenceNode(defaultApiResponse.name)
+ ts.factory.createTypeReferenceNode(defaultApiResponse.name),
),
ts.factory.createTypeParameterDeclaration(
undefined,
TError,
undefined,
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
),
],
ts.factory.createTypeReferenceNode(
@@ -171,8 +168,8 @@ export function createReturnTypeExport({
[
ts.factory.createTypeReferenceNode(TData),
ts.factory.createTypeReferenceNode(TError),
- ]
- )
+ ],
+ ),
);
}
@@ -197,12 +194,12 @@ export function createQueryKeyExport({
undefined,
undefined,
ts.factory.createStringLiteral(
- `${className}${capitalizeFirstLetter(methodName)}`
- )
+ `${className}${capitalizeFirstLetter(methodName)}`,
+ ),
),
],
- ts.NodeFlags.Const
- )
+ ts.NodeFlags.Const,
+ ),
);
}
@@ -269,15 +266,17 @@ export function createQueryHook({
undefined,
TError,
undefined,
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
),
ts.factory.createTypeParameterDeclaration(
undefined,
"TQueryKey",
queryKeyConstraint,
ts.factory.createArrayTypeNode(
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)
- )
+ ts.factory.createKeywordTypeNode(
+ ts.SyntaxKind.UnknownKeyword,
+ ),
+ ),
),
]),
[
@@ -287,7 +286,7 @@ export function createQueryHook({
undefined,
ts.factory.createIdentifier("queryKey"),
ts.factory.createToken(ts.SyntaxKind.QuestionToken),
- queryKeyGenericType
+ queryKeyGenericType,
),
ts.factory.createParameterDeclaration(
undefined,
@@ -302,18 +301,18 @@ export function createQueryHook({
[
ts.factory.createTypeReferenceNode(TData),
ts.factory.createTypeReferenceNode(TError),
- ]
+ ],
),
ts.factory.createUnionTypeNode([
ts.factory.createLiteralTypeNode(
- ts.factory.createStringLiteral("queryKey")
+ ts.factory.createStringLiteral("queryKey"),
),
ts.factory.createLiteralTypeNode(
- ts.factory.createStringLiteral("queryFn")
+ ts.factory.createStringLiteral("queryFn"),
),
]),
- ]
- )
+ ],
+ ),
),
],
undefined,
@@ -337,20 +336,19 @@ export function createQueryHook({
ts.factory.createObjectLiteralExpression(
method
.getParameters()
- .map((param) =>
+ .flatMap((param) =>
extractPropertiesFromObjectParam(param).map(
(p) =>
ts.factory.createShorthandPropertyAssignment(
- ts.factory.createIdentifier(p.name)
- )
- )
- )
- .flat()
+ ts.factory.createIdentifier(p.name),
+ ),
+ ),
+ ),
),
ts.factory.createIdentifier("queryKey"),
]
- : []
- )
+ : [],
+ ),
),
ts.factory.createPropertyAssignment(
ts.factory.createIdentifier("queryFn"),
@@ -364,7 +362,7 @@ export function createQueryHook({
ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier(className),
- ts.factory.createIdentifier(methodName)
+ ts.factory.createIdentifier(methodName),
),
undefined,
method.getParameters().length
@@ -372,35 +370,34 @@ export function createQueryHook({
ts.factory.createObjectLiteralExpression(
method
.getParameters()
- .map((param) =>
+ .flatMap((param) =>
extractPropertiesFromObjectParam(
- param
+ param,
).map((p) =>
ts.factory.createShorthandPropertyAssignment(
- ts.factory.createIdentifier(p.name)
- )
- )
- )
- .flat()
+ ts.factory.createIdentifier(p.name),
+ ),
+ ),
+ ),
),
]
- : undefined
+ : undefined,
),
- ts.factory.createTypeReferenceNode(TData)
- )
- )
+ ts.factory.createTypeReferenceNode(TData),
+ ),
+ ),
),
ts.factory.createSpreadAssignment(
- ts.factory.createIdentifier("options")
+ ts.factory.createIdentifier("options"),
),
]),
- ]
- )
- )
+ ],
+ ),
+ ),
),
],
- ts.NodeFlags.Const
- )
+ ts.NodeFlags.Const,
+ ),
);
return hookExport;
}
@@ -479,7 +476,7 @@ function createQueryKeyFnExport(queryKey: string, method: MethodDeclaration) {
undefined,
ts.factory.createIdentifier("queryKey"),
QuestionToken,
- ts.factory.createTypeReferenceNode("Array", [])
+ ts.factory.createTypeReferenceNode("Array", []),
);
return ts.factory.createVariableStatement(
@@ -496,18 +493,18 @@ function createQueryKeyFnExport(queryKey: string, method: MethodDeclaration) {
params ? [params, overrideKey] : [],
undefined,
EqualsOrGreaterThanToken,
- queryKeyFn(queryKey, method)
- )
+ queryKeyFn(queryKey, method),
+ ),
),
],
- ts.NodeFlags.Const
- )
+ ts.NodeFlags.Const,
+ ),
);
}
function queryKeyFn(
queryKey: string,
- method: MethodDeclaration
+ method: MethodDeclaration,
): ts.Expression {
const params = getRequestParamFromMethod(method);
@@ -530,21 +527,20 @@ function queryKeyFn(
ts.factory.createObjectLiteralExpression(
method
.getParameters()
- .map((param) =>
+ .flatMap((param) =>
extractPropertiesFromObjectParam(param).map((p) =>
ts.factory.createShorthandPropertyAssignment(
- ts.factory.createIdentifier(p.name)
- )
- )
- )
- .flat()
+ ts.factory.createIdentifier(p.name),
+ ),
+ ),
+ ),
),
])
- : ts.factory.createArrayLiteralExpression([])
- )
- )
+ : ts.factory.createArrayLiteralExpression([]),
+ ),
+ ),
),
],
- false
+ false,
);
}
diff --git a/src/generate.mts b/src/generate.mts
index 0a19ed1..01ebb11 100644
--- a/src/generate.mts
+++ b/src/generate.mts
@@ -1,13 +1,13 @@
-import { createClient, UserConfig } from "@hey-api/openapi-ts";
-import { print } from "./print.mjs";
-import { createSource } from "./createSource.mjs";
+import { type UserConfig, createClient } from "@hey-api/openapi-ts";
+import type { LimitedUserConfig } from "./cli.mjs";
import {
buildQueriesOutputPath,
buildRequestsOutputPath,
formatOptions,
} from "./common.mjs";
-import { LimitedUserConfig } from "./cli.mjs";
+import { createSource } from "./createSource.mjs";
import { formatOutput } from "./format.mjs";
+import { print } from "./print.mjs";
export async function generate(options: LimitedUserConfig, version: string) {
const openApiOutputPath = buildRequestsOutputPath(options.output);
diff --git a/src/print.mts b/src/print.mts
index cc2f4c8..da77282 100644
--- a/src/print.mts
+++ b/src/print.mts
@@ -1,7 +1,6 @@
-import { mkdir, writeFile } from "fs/promises";
-import path from "path";
-import { queriesOutputPath } from "./constants.mjs";
-import { LimitedUserConfig } from "./cli.mjs";
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import type { LimitedUserConfig } from "./cli.mjs";
import { buildQueriesOutputPath, exists } from "./common.mjs";
async function printGeneratedTS(
@@ -9,7 +8,7 @@ async function printGeneratedTS(
name: string;
content: string;
},
- options: Pick
+ options: Pick,
) {
const dir = buildQueriesOutputPath(options.output);
const dirExists = await exists(dir);
@@ -24,7 +23,7 @@ export async function print(
name: string;
content: string;
}[],
- options: Pick
+ options: Pick,
) {
const outputPath = options.output;
const dirExists = await exists(outputPath);
diff --git a/src/service.mts b/src/service.mts
index c99c874..e3fb546 100644
--- a/src/service.mts
+++ b/src/service.mts
@@ -1,7 +1,7 @@
+import type { ClassDeclaration, Project, SourceFile } from "ts-morph";
import ts from "typescript";
-import { ClassDeclaration, Project, SourceFile } from "ts-morph";
import {
- MethodDescription,
+ type MethodDescription,
getClassNameFromClassNode,
getClassesFromService,
} from "./common.mjs";
@@ -51,7 +51,7 @@ function getMethodsFromService(node: SourceFile, klass: ClassDeclaration) {
}
const methodBlock = methodBlockNode as ts.Block;
const foundReturnStatement = methodBlock.statements.find(
- (s) => s.kind === ts.SyntaxKind.ReturnStatement
+ (s) => s.kind === ts.SyntaxKind.ReturnStatement,
);
if (!foundReturnStatement) {
throw new Error("Return statement not found");
@@ -91,7 +91,7 @@ function getMethodsFromService(node: SourceFile, klass: ClassDeclaration) {
// get the first JSDoc comment
const jsDoc = jsDocs?.[0];
const isDeprecated = children.some(
- (c) => c.kind === ts.SyntaxKind.JSDocDeprecatedTag
+ (c) => c.kind === ts.SyntaxKind.JSDocDeprecatedTag,
);
const className = getClassNameFromClassNode(klass);
diff --git a/src/util.mts b/src/util.mts
index 8961d96..b2e2c8b 100644
--- a/src/util.mts
+++ b/src/util.mts
@@ -2,7 +2,7 @@ import ts from "typescript";
export function addJSDocToNode(
node: T,
- jsDoc: string | undefined
+ jsDoc: string | undefined,
): T {
if (!jsDoc) {
return node;
@@ -21,7 +21,7 @@ export function addJSDocToNode(
node,
ts.SyntaxKind.MultiLineCommentTrivia,
joined,
- true
+ true,
);
return nodeWithJSDoc;
diff --git a/tests/__snapshots__/createSource.test.ts.snap b/tests/__snapshots__/createSource.test.ts.snap
index c482300..afea9f7 100644
--- a/tests/__snapshots__/createSource.test.ts.snap
+++ b/tests/__snapshots__/createSource.test.ts.snap
@@ -11,7 +11,7 @@ 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 { type QueryClient, useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
export type DefaultServiceFindPetsDefaultResponse = Awaited>;
@@ -41,7 +41,7 @@ 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 { type QueryClient, useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
/**
@@ -119,7 +119,7 @@ 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 { type QueryClient, useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
/**
@@ -164,7 +164,7 @@ exports[`createSource > createSource 5`] = `
"// 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 { type QueryClient, useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
/**
diff --git a/tests/__snapshots__/generate.test.ts.snap b/tests/__snapshots__/generate.test.ts.snap
index d08bee3..4ed7d5d 100644
--- a/tests/__snapshots__/generate.test.ts.snap
+++ b/tests/__snapshots__/generate.test.ts.snap
@@ -39,6 +39,7 @@ export * from "./queries";
exports[`generate > prefetch.ts 1`] = `
"// generated with @7nohe/openapi-react-query-codegen@1.0.0
+import { type QueryClient } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
import * as Common from "./common";
/**
diff --git a/tests/common.test.ts b/tests/common.test.ts
index 74e9642..f502240 100644
--- a/tests/common.test.ts
+++ b/tests/common.test.ts
@@ -1,16 +1,17 @@
+import type { ClassDeclaration, MethodDeclaration, SourceFile } from "ts-morph";
import { describe, expect, test, vi } from "vitest";
+import type { LimitedUserConfig } from "../src/cli.mts";
import {
BuildCommonTypeName,
capitalizeFirstLetter,
- lowercaseFirstLetter,
- safeParseNumber,
- getShortType,
formatOptions,
getClassNameFromClassNode,
getClassesFromService,
getNameFromMethod,
+ getShortType,
+ lowercaseFirstLetter,
+ safeParseNumber,
} from "../src/common.mts";
-import { LimitedUserConfig } from "../src/cli.mts";
describe("common", () => {
test("safeParseNumber", () => {
@@ -85,6 +86,7 @@ describe("common", () => {
const options: LimitedUserConfig = {
input: "input",
output: "output",
+ // biome-ignore lint: test
debug: "false" as any,
};
const formatted = formatOptions(options);
@@ -96,6 +98,7 @@ describe("common", () => {
const options: LimitedUserConfig = {
input: "input",
output: "output",
+ // biome-ignore lint: test
debug: "true" as any,
};
const formatted = formatOptions(options);
@@ -117,6 +120,7 @@ describe("common", () => {
const options: LimitedUserConfig = {
input: "input",
output: "output",
+ // biome-ignore lint: test
debug: "123" as any,
};
const formatted = formatOptions(options);
@@ -128,6 +132,7 @@ describe("common", () => {
const options: LimitedUserConfig = {
input: "input",
output: "output",
+ // biome-ignore lint: test
debug: "123" as any,
lint: "eslint",
};
@@ -140,6 +145,7 @@ describe("common", () => {
const options: LimitedUserConfig = {
input: "input",
output: "output",
+ // biome-ignore lint: test
debug: Number.NaN as any,
};
const formatted = formatOptions(options);
@@ -172,7 +178,7 @@ describe("common", () => {
test("getClassNameFromClassNode - get's name", () => {
const klass = {
getName: () => "Test",
- } as any;
+ } as unknown as ClassDeclaration;
const result = getClassNameFromClassNode(klass);
expect(result).toBe("Test");
});
@@ -180,9 +186,9 @@ describe("common", () => {
test("getClassNameFromClassNode - no name", () => {
const klass = {
getName: () => undefined,
- } as any;
+ } as unknown as ClassDeclaration;
expect(() => getClassNameFromClassNode(klass)).toThrowError(
- "Class name not found"
+ "Class name not found",
);
});
@@ -192,7 +198,7 @@ describe("common", () => {
};
const node = {
getClasses: vi.fn(() => [klass]),
- } as any;
+ } as unknown as SourceFile;
const result = getClassesFromService(node);
expect(result).toStrictEqual([
{
@@ -205,7 +211,7 @@ describe("common", () => {
test("getClassesFromService - no classes", () => {
const node = {
getClasses: vi.fn(() => []),
- } as any;
+ } as unknown as SourceFile;
expect(() => getClassesFromService(node)).toThrowError("No classes found");
});
@@ -215,16 +221,16 @@ describe("common", () => {
};
const node = {
getClasses: vi.fn(() => [klass]),
- } as any;
+ } as unknown as SourceFile;
expect(() => getClassesFromService(node)).toThrowError(
- "Class name not found"
+ "Class name not found",
);
});
test("getNameFromMethod - get method name", () => {
const method = {
getName: vi.fn(() => "test"),
- } as any;
+ } as unknown as MethodDeclaration;
const result = getNameFromMethod(method);
expect(result).toBe("test");
});
@@ -232,9 +238,9 @@ describe("common", () => {
test("getNameFromMethod - no method name", () => {
const method = {
getName: vi.fn(() => undefined),
- } as any;
+ } as unknown as MethodDeclaration;
expect(() => getNameFromMethod(method)).toThrowError(
- "Method name not found"
+ "Method name not found",
);
});
});
diff --git a/tests/createExports.test.ts b/tests/createExports.test.ts
index 65b42d6..cc1826e 100644
--- a/tests/createExports.test.ts
+++ b/tests/createExports.test.ts
@@ -1,9 +1,9 @@
-import { afterAll, beforeAll, describe, expect, test } from "vitest";
-import { cleanOutputs, generateTSClients, outputPath } from "./utils";
+import path from "node:path";
import { Project, SyntaxKind } from "ts-morph";
+import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { createExports } from "../src/createExports.mts";
import { getServices } from "../src/service.mts";
-import path from "path";
+import { cleanOutputs, generateTSClients, outputPath } from "./utils";
const fileName = "createExports";
@@ -50,7 +50,7 @@ describe(fileName, () => {
const mainExports = exports.mainExports.map(
// @ts-ignore
- (e) => e.declarationList.declarations[0].name.escapedText
+ (e) => e.declarationList.declarations[0].name.escapedText,
);
expect(mainExports).toStrictEqual([
"useDefaultServiceFindPets",
@@ -63,7 +63,7 @@ describe(fileName, () => {
const suspenseExports = exports.suspenseExports.map(
// @ts-ignore
- (e) => e.declarationList.declarations[0].name.escapedText
+ (e) => e.declarationList.declarations[0].name.escapedText,
);
expect(suspenseExports).toStrictEqual([
"useDefaultServiceFindPetsSuspense",
diff --git a/tests/createImports.test.ts b/tests/createImports.test.ts
index b496693..c0d707e 100644
--- a/tests/createImports.test.ts
+++ b/tests/createImports.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from "vitest";
-import { cleanOutputs, generateTSClients, outputPath } from "./utils";
+import path from "node:path";
import { Project } from "ts-morph";
+import { describe, expect, test } from "vitest";
import { createImports } from "../src/createImports.mts";
-import path from "path";
+import { cleanOutputs, generateTSClients, outputPath } from "./utils";
const fileName = "createImports";
diff --git a/tests/generate.test.ts b/tests/generate.test.ts
index 25b8d84..0f6ccc8 100644
--- a/tests/generate.test.ts
+++ b/tests/generate.test.ts
@@ -1,14 +1,14 @@
import { existsSync, readFileSync } from "node:fs";
+import { rm } from "node:fs/promises";
import path from "node:path";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
+import type { LimitedUserConfig } from "../src/cli.mts";
import { generate } from "../src/generate.mjs";
-import { rm } from "node:fs/promises";
-import { LimitedUserConfig } from "../src/cli.mts";
const readOutput = (fileName: string) => {
return readFileSync(
path.join(__dirname, "outputs", "queries", fileName),
- "utf-8"
+ "utf-8",
);
};
diff --git a/tests/print.test.ts b/tests/print.test.ts
index e4b4d7f..547a0b5 100644
--- a/tests/print.test.ts
+++ b/tests/print.test.ts
@@ -1,7 +1,7 @@
-import { describe, test, expect, vi, beforeEach } from "vitest";
-import { print } from "../src/print.mjs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { beforeEach, describe, expect, test, vi } from "vitest";
import * as common from "../src/common.mjs";
-import { mkdir, writeFile } from "fs/promises";
+import { print } from "../src/print.mjs";
vi.mock("fs/promises", () => {
return {
@@ -26,7 +26,7 @@ describe("print", () => {
],
{
output: "dist",
- }
+ },
);
expect(exists).toBeCalledTimes(2);
expect(result).toBeUndefined();
@@ -46,7 +46,7 @@ describe("print", () => {
],
{
output: "dist",
- }
+ },
);
expect(exists).toBeCalledTimes(2);
expect(result).toBeUndefined();
diff --git a/tests/service.test.ts b/tests/service.test.ts
index 17617b6..91a9501 100644
--- a/tests/service.test.ts
+++ b/tests/service.test.ts
@@ -1,9 +1,9 @@
+import path from "node:path";
+import { Project } from "ts-morph";
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"
+const fileName = "service";
describe(fileName, () => {
beforeAll(async () => await generateTSClients(fileName));
afterAll(async () => await cleanOutputs(fileName));
@@ -12,19 +12,30 @@ describe(fileName, () => {
const project = new Project({
skipAddingFilesFromTsConfig: true,
});
- project.addSourceFilesAtPaths(path.join('tests', `${fileName}-outputs`, '**', '*'));
+ project.addSourceFilesAtPaths(
+ path.join("tests", `${fileName}-outputs`, "**", "*"),
+ );
const service = await getServices(project);
const klass = service.klasses[0];
- expect(klass.className).toBe('DefaultService');
+ expect(klass.className).toBe("DefaultService");
const methodNames = klass.methods.map((m) => m.method.getName());
- expect(methodNames).toEqual(['findPets', 'addPet', 'getNotDefined', 'postNotDefined', 'findPetById', 'deletePet']);
+ 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");
+ 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.test.ts b/tests/utils.test.ts
index e85401e..47e8d92 100644
--- a/tests/utils.test.ts
+++ b/tests/utils.test.ts
@@ -1,7 +1,7 @@
+import { Project } from "ts-morph";
import ts from "typescript";
import { describe, expect, test } from "vitest";
import { addJSDocToNode } from "../src/util.mts";
-import { Project } from "ts-morph";
describe("utils", () => {
test("addJSDocToNode - deprecated", () => {
@@ -15,7 +15,7 @@ describe("utils", () => {
"TestClass",
undefined,
undefined,
- []
+ [],
);
// create file source
const tsFile = ts.createSourceFile(
@@ -23,14 +23,14 @@ describe("utils", () => {
"",
ts.ScriptTarget.Latest,
false,
- ts.ScriptKind.TS
+ ts.ScriptKind.TS,
);
// create source file
const tsSource = ts.factory.createSourceFile(
[node],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
- ts.NodeFlags.None
+ ts.NodeFlags.None,
);
// print source file
@@ -55,7 +55,7 @@ describe("utils", () => {
const deprecated = true;
// find class node
- const foundNode = sourceFile.getClasses()[0]!;
+ const foundNode = sourceFile.getClasses()[0];
// add jsdoc to node
const nodeWithJSDoc = addJSDocToNode(foundNode.compilerNode, jsDoc);
@@ -87,7 +87,7 @@ export class TestClass {
"TestClass",
undefined,
undefined,
- []
+ [],
);
// create file source
const tsFile = ts.createSourceFile(
@@ -95,14 +95,14 @@ export class TestClass {
"",
ts.ScriptTarget.Latest,
false,
- ts.ScriptKind.TS
+ ts.ScriptKind.TS,
);
// create source file
const tsSource = ts.factory.createSourceFile(
[node],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
- ts.NodeFlags.None
+ ts.NodeFlags.None,
);
// print source file
@@ -124,7 +124,7 @@ export class TestClass {
*/`;
// find class node
- const foundNode = sourceFile.getClasses()[0]!;
+ const foundNode = sourceFile.getClasses()[0];
// add jsdoc to node
const nodeWithJSDoc = addJSDocToNode(foundNode.compilerNode, jsDoc);
@@ -155,7 +155,7 @@ export class TestClass {
"TestClass",
undefined,
undefined,
- []
+ [],
);
// create file source
const tsFile = ts.createSourceFile(
@@ -163,14 +163,14 @@ export class TestClass {
"",
ts.ScriptTarget.Latest,
false,
- ts.ScriptKind.TS
+ ts.ScriptKind.TS,
);
// create source file
const tsSource = ts.factory.createSourceFile(
[node],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
- ts.NodeFlags.None
+ ts.NodeFlags.None,
);
// print source file
@@ -189,7 +189,7 @@ export class TestClass {
const jsDoc = undefined;
// find class node
- const foundNode = sourceFile.getClasses()[0]!;
+ const foundNode = sourceFile.getClasses()[0];
// add jsdoc to node
const nodeWithJSDoc = addJSDocToNode(foundNode.compilerNode, jsDoc);
@@ -216,7 +216,7 @@ export class TestClass {
"TestClass",
undefined,
undefined,
- []
+ [],
);
// create file source
const tsFile = ts.createSourceFile(
@@ -224,14 +224,14 @@ export class TestClass {
"",
ts.ScriptTarget.Latest,
false,
- ts.ScriptKind.TS
+ ts.ScriptKind.TS,
);
// create source file
const tsSource = ts.factory.createSourceFile(
[node],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
- ts.NodeFlags.None
+ ts.NodeFlags.None,
);
// print source file
@@ -250,7 +250,7 @@ export class TestClass {
const jsDoc = undefined;
// find class node
- const foundNode = sourceFile.getClasses()[0]!;
+ const foundNode = sourceFile.getClasses()[0];
// add jsdoc to node
const nodeWithJSDoc = addJSDocToNode(foundNode.compilerNode, jsDoc);
diff --git a/tests/utils.ts b/tests/utils.ts
index 55e518e..52a31a3 100644
--- a/tests/utils.ts
+++ b/tests/utils.ts
@@ -1,7 +1,7 @@
-import { UserConfig, createClient } from "@hey-api/openapi-ts";
import { existsSync } from "node:fs";
import { rm } from "node:fs/promises";
import path from "node:path";
+import { type UserConfig, createClient } from "@hey-api/openapi-ts";
export const outputPath = (prefix: string) =>
path.join("tests", `${prefix}-outputs`);
diff --git a/tsconfig.json b/tsconfig.json
index 37a52d6..864319e 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -14,7 +14,5 @@
"baseUrl": ".",
"rootDir": "src"
},
- "include": [
- "src"
- ],
-}
\ No newline at end of file
+ "include": ["src"]
+}