Skip to content

feat!: changing openapi generator #50

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,19 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'
cache: "pnpm"

- name: Install dependencies
run: pnpm -w install
run: pnpm install --frozen-lockfile

- name: Build
run: pnpm -w build

- name: Install dependencies in example app
run: pnpm --filter @7nohe/react-app install --no-frozen-lockfile

- name: Run codegen
run: pnpm --filter @7nohe/react-app generate:api

- name: Archive generated query file
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: generated-query-file-${{ matrix.os }}
path: examples/react-app/openapi/queries/index.ts
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ dist-ssr
*.sw?

openapi
*.tsbuildinfo
25 changes: 18 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

- Supports generation of custom react hooks that use React Query's `useQuery` and `useMutation` hooks
- Supports generation of query keys for query caching
- Supports the option to use pure TypeScript clients generated by [OpenAPI Typescript Codegen](https://github.com/ferdikoomen/openapi-typescript-codegen)
- Supports the option to use pure TypeScript clients generated by [@hey-api/openapi-ts](https://github.com/hey-api/openapi-ts)

## Install

Expand Down Expand Up @@ -44,12 +44,14 @@ Options:
-i, --input <value> OpenAPI specification, can be a path, url or string content (required)
-o, --output <value> Output directory (default: "openapi")
-c, --client <value> HTTP client to generate [fetch, xhr, node, axios, angular] (default: "fetch")
--useUnionTypes Use union types (default: false)
--exportSchemas <value> Write schemas to disk (default: false)
--indent <value> Indentation options [4, 2, tabs] (default: "4")
--postfixServices <value> Service name postfix (default: "Service")
--postfixModels <value> Modal name postfix
--request <value> Path to custom request file
--useDateType Use Date type instead of string for date types for models, this will not convert the data to a Date object
--enums Generate JavaScript objects from enum definitions?
--base <value> Manually set base in OpenAPI config instead of inferring from server value
--serviceResponse <value> Define shape of returned value from service calls ['body', 'generics', 'response']
--operationId Use operation ID to generate operation names?
--lint Process output folder with linter?
--format Process output folder with formatter?
-h, --help display help for command
```

Expand All @@ -70,7 +72,7 @@ $ openapi-rq -i ./petstore.yaml
- common.ts <- common types
- queries.ts <- generated query hooks
- suspenses.ts <- generated suspense hooks
- requests <- output code generated by OpenAPI Typescript Codegen
- requests <- output code generated by @hey-api/openapi-ts
```

### In your app
Expand Down Expand Up @@ -146,6 +148,15 @@ function ParentComponent() {
);
}

function App() {
return (
<div className="App">
<h1>Pet List</h1>
<ParentComponent />
</div>
);
}

export default App;
```

Expand Down
6 changes: 3 additions & 3 deletions examples/react-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"dev:mock": "prism mock ./petstore.yaml --dynamic",
"build": "tsc && vite build",
"preview": "vite preview",
"generate:api": "node ../../dist/src/cli.js -i ./petstore.yaml -c axios --exportSchemas=true --postfixServices=Client --request ./request.ts",
"test:generated": "tsc ./openapi/queries/index.ts --noEmit --target esnext --moduleResolution node"
"generate:api": "node ../../dist/cli.mjs -i ./petstore.yaml -c axios --request ./request.ts",
"test:generated": "tsc -p ./tsconfig.openapi.json --noEmit"
},
"dependencies": {
"@tanstack/react-query": "^5.18.1",
Expand All @@ -28,4 +28,4 @@
"typescript": "^5.3.3",
"vite": "^5.0.12"
}
}
}
10 changes: 5 additions & 5 deletions examples/react-app/request.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import axios from "axios";
import type { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import type { RawAxiosRequestHeaders } from "axios";

import type { ApiRequestOptions } from "./ApiRequestOptions";
import { CancelablePromise } from "./CancelablePromise";
Expand All @@ -13,7 +13,7 @@ const axiosInstance = axios.create({
baseURL: "http://localhost:4010",
headers: {
// Your custom headers
},
} satisfies RawAxiosRequestHeaders,
});

// Add a request interceptor
Expand Down Expand Up @@ -49,12 +49,12 @@ export const request = <T>(
return new CancelablePromise((resolve, reject, onCancel) => {
onCancel(() => source.cancel("The user aborted a request."));

let formattedHeaders = options.headers;
if(options.mediaType) {
let formattedHeaders = options.headers as RawAxiosRequestHeaders;
if (options.mediaType) {
formattedHeaders = {
...options.headers,
"Content-Type": options.mediaType,
};
} satisfies RawAxiosRequestHeaders;
}

return axiosInstance
Expand Down
20 changes: 10 additions & 10 deletions examples/react-app/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import "./App.css";
import {
useDefaultClientAddPet,
useDefaultClientFindPets,
useDefaultClientFindPetsKey,
useDefaultClientGetNotDefined,
useDefaultClientPostNotDefined,
useDefaultServiceAddPet,
useDefaultServiceFindPets,
useDefaultServiceFindPetsKey,
useDefaultServiceGetNotDefined,
useDefaultServicePostNotDefined,
} from "../openapi/queries";
import { useState } from "react";
import { queryClient } from "./queryClient";
Expand All @@ -14,16 +14,16 @@ function App() {
const [tags, _setTags] = useState<string[]>([]);
const [limit, _setLimit] = useState<number>(10);

const { data, error, refetch } = useDefaultClientFindPets({ tags, limit });
const { data, error, refetch } = useDefaultServiceFindPets({ tags, limit });

// 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
// Note - this is marked as deprecated in the OpenAPI spec and being passed to the client
const { data: notDefined } = useDefaultClientGetNotDefined<undefined>();
const { data: notDefined } = useDefaultServiceGetNotDefined<undefined>();
const { mutate: mutateNotDefined } =
useDefaultClientPostNotDefined<undefined>();
useDefaultServicePostNotDefined<undefined>();

const { mutate: addPet } = useDefaultClientAddPet();
const { mutate: addPet } = useDefaultServiceAddPet();

if (error)
return (
Expand Down Expand Up @@ -51,7 +51,7 @@ function App() {
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [useDefaultClientFindPetsKey],
queryKey: [useDefaultServiceFindPetsKey],
});
console.log("success");
},
Expand Down
4 changes: 2 additions & 2 deletions examples/react-app/src/components/SuspenseChild.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useDefaultClientFindPetsSuspense } from "../../openapi/queries/suspense";
import { useDefaultServiceFindPetsSuspense } from "../../openapi/queries/suspense";

export const SuspenseChild = () => {
const { data } = useDefaultClientFindPetsSuspense({ tags: [], limit: 10 });
const { data } = useDefaultServiceFindPetsSuspense({ tags: [], limit: 10 });

if (!Array.isArray(data)) {
return <div>Error!</div>;
Expand Down
8 changes: 3 additions & 5 deletions examples/react-app/src/components/SuspenseParent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@ import { SuspenseChild } from "./SuspenseChild";

export const SuspenseParent = () => {
return (
<>
<Suspense fallback={<>loading...</>}>
<SuspenseChild />
</Suspense>
</>
<Suspense fallback={<>loading...</>}>
<SuspenseChild />
</Suspense>
);
};
17 changes: 9 additions & 8 deletions examples/react-app/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import { QueryClientProvider } from '@tanstack/react-query'
import { queryClient } from './queryClient'
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { QueryClientProvider } from "@tanstack/react-query";
import { queryClient } from "./queryClient";

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>
)
);
9 changes: 6 additions & 3 deletions examples/react-app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src", "openapi"],
"references": [{ "path": "./tsconfig.node.json" }]
"include": ["src"],
"references": [
{ "path": "./tsconfig.node.json" },
{ "path": "./tsconfig.openapi.json" }
]
}
18 changes: 18 additions & 0 deletions examples/react-app/tsconfig.openapi.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"composite": true,
"target": "ESNext",
"useDefineForClassFields": true,
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node10",
"resolveJsonModule": true,
"isolatedModules": true
},
"include": ["openapi"]
}
18 changes: 14 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@
"version": "0.5.3",
"description": "OpenAPI React Query Codegen",
"bin": {
"openapi-rq": "dist/src/cli.js"
"openapi-rq": "dist/cli.js"
},
"type": "module",
"workspaces": [
"examples/*"
],
"scripts": {
"build": "tsc -p tsconfig.json",
"preview": "npm run build && npm -C examples/react-app run generate:api",
Expand All @@ -27,21 +31,27 @@
"openapi",
"swagger",
"typescript",
"openapi-typescript-codegen"
"openapi-typescript-codegen",
"@hey-api/openapi-ts"
],
"author": "Daiki Urata (@7nohe)",
"license": "MIT",
"devDependencies": {
"@hey-api/openapi-ts": "0.36.0",
"@types/node": "^20.10.6",
"commander": "^12.0.0",
"glob": "^10.3.10",
"openapi-typescript-codegen": "0.25.0",
"ts-morph": "^22.0.0",
"typescript": "^5.3.3"
},
"peerDependencies": {
"@hey-api/openapi-ts": "0.36.0",
"commander": ">= 11 < 13",
"glob": ">= 10",
"openapi-typescript-codegen": "^0.24.0",
"ts-morph": ">= 22 < 23",
"typescript": ">= 4.8.3"
},
"engines": {
"node": ">=14"
}
}
Loading