Skip to content
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

feat/new openapi client support 2 #131

Merged
merged 17 commits into from
Oct 7, 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
5 changes: 4 additions & 1 deletion .github/workflows/comment-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const { issue: { number: issue_number }, repo: { owner, repo }, payload } = context;
const { name: packageName, version } = require(`${process.env.GITHUB_WORKSPACE}/package.json`);
const fs = require('fs')
const jsonString = fs.readFileSync(`${process.env.GITHUB_WORKSPACE}/package.json`)
var packageJson = JSON.parse(jsonString)
const { name: packageName, version } = packageJson;

const body = [
`npm package published to pre tag.`,
Expand Down
11 changes: 5 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ Register the command to the `scripts` property in your package.json file.
```json
{
"scripts": {
"codegen": "openapi-rq -i ./petstore.yaml -c axios"
"codegen": "openapi-rq -i ./petstore.yaml -c @hey-api/client-fetch"
}
}
```

You can also run the command without installing it in your project using the npx command.

```bash
$ npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./petstore.yaml -c axios
$ npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./petstore.yaml -c @hey-api/client-fetch
```

## Usage
Expand All @@ -46,23 +46,22 @@ Options:
-V, --version output the version number
-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 (choices: "angular", "axios", "fetch", "node", "xhr", default: "fetch")
-c, --client <value> HTTP client to generate (choices: "@hey-api/client-fetch", "@hey-api/client-axios", default: "@hey-api/client-fetch")
--request <value> Path to custom request file
--format <value> Process output folder with formatter? (choices: "biome", "prettier")
--lint <value> Process output folder with linter? (choices: "biome", "eslint")
--operationId Use operation ID to generate operation names?
--serviceResponse <value> Define shape of returned value from service calls (choices: "body", "response", default: "body")
--base <value> Manually set base in OpenAPI config instead of inferring from server value
--enums <value> Generate JavaScript objects from enum definitions? ['javascript', 'typescript', 'typescript+namespace']
--enums <value> Generate JavaScript objects from enum definitions? (choices: "javascript", "typescript")
--useDateType Use Date type instead of string for date types for models, this will not convert the data to a Date object
--debug Run in debug mode?
--noSchemas Disable generating JSON schemas
--schemaType <value> Type of JSON schema [Default: 'json'] (choices: "form", "json")
--pageParam <value> Name of the query parameter used for pagination (default: "page")
--nextPageParam <value> Name of the response parameter used for next page (default: "nextPage")
--initialPageParam <value> Initial value for the pagination parameter (default: "1")
-h, --help display help for command
--initialPageParam <value> Initial page value to query (default: "initialPageParam")
-h, --help display help for command
```

### Example Usage
Expand Down
1 change: 1 addition & 0 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
},
"files": {
"ignore": [
".vscode",
"dist",
"examples/react-app/openapi",
"coverage",
Expand Down
7 changes: 3 additions & 4 deletions examples/nextjs-app/app/components/Pets.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
"use client";

import { useDefaultServiceFindPets } from "@/openapi/queries";
import { useFindPets } from "@/openapi/queries";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

export default function Pets() {
const { data } = useDefaultServiceFindPets({
limit: 10,
tags: [],
const { data } = useFindPets({
query: { tags: [], limit: 10 },
});

return (
Expand Down
7 changes: 3 additions & 4 deletions examples/nextjs-app/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import { prefetchUseDefaultServiceFindPets } from "@/openapi/queries/prefetch";
import {
HydrationBoundary,
QueryClient,
dehydrate,
} from "@tanstack/react-query";
import Link from "next/link";
import { prefetchUseFindPets } from "../openapi/queries/prefetch";
import Pets from "./components/Pets";

export default async function Home() {
const queryClient = new QueryClient();

await prefetchUseDefaultServiceFindPets(queryClient, {
limit: 10,
tags: [],
await prefetchUseFindPets(queryClient, {
query: { tags: [], limit: 10 },
});

return (
Expand Down
5 changes: 3 additions & 2 deletions examples/nextjs-app/app/providers.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import "../fetchClient";

// 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";
// extracting this part out into

function makeQueryClient() {
return new QueryClient({
Expand Down
5 changes: 5 additions & 0 deletions examples/nextjs-app/fetchClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { client } from "@/openapi/requests/services.gen";

client.setConfig({
baseUrl: "http://localhost:4010",
});
2 changes: 1 addition & 1 deletion examples/nextjs-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"build": "next build",
"start": "next start",
"lint": "next lint",
"generate:api": "rimraf ./openapi && node ../../dist/cli.mjs -i ../petstore.yaml -c axios --request ./request.ts --format=biome --lint=biome"
"generate:api": "rimraf ./openapi && node ../../dist/cli.mjs -i ../petstore.yaml --request ./request.ts --format=biome --lint=biome --base http://localhost:4010"
},
"dependencies": {
"@tanstack/react-query": "^5.32.1",
Expand Down
6 changes: 3 additions & 3 deletions examples/petstore.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -197,12 +197,12 @@ components:
NewPet:
type: object
required:
- name
- name
properties:
name:
type: string
tag:
type: string
type: string

Error:
type: object
Expand All @@ -214,4 +214,4 @@ components:
type: integer
format: int32
message:
type: string
type: string
3 changes: 2 additions & 1 deletion examples/react-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
"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 --format=biome --lint=biome",
"generate:api": "rimraf ./openapi && node ../../dist/cli.mjs -i ../petstore.yaml --format=biome --lint=biome -c @hey-api/client-axios",
"test:generated": "tsc -p ./tsconfig.openapi.json --noEmit"
},
"dependencies": {
"@hey-api/client-axios": "^0.2.7",
"@tanstack/react-query": "^5.32.1",
"axios": "^1.6.7",
"form-data": "~4.0.0",
Expand Down
94 changes: 0 additions & 94 deletions examples/react-app/request.ts

This file was deleted.

29 changes: 16 additions & 13 deletions examples/react-app/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,35 @@
import "./App.css";
import { useState } from "react";

import { createClient } from "@hey-api/client-fetch";
import {
UseDefaultServiceFindPetsKeyFn,
useDefaultServiceAddPet,
useDefaultServiceFindPets,
useDefaultServiceGetNotDefined,
useDefaultServicePostNotDefined,
UseFindPetsKeyFn,
useAddPet,
useFindPets,
useGetNotDefined,
usePostNotDefined,
} from "../openapi/queries";
import { SuspenseParent } from "./components/SuspenseParent";
import { queryClient } from "./queryClient";

function App() {
createClient({ baseUrl: "http://localhost:4010" });

const [tags, _setTags] = useState<string[]>([]);
const [limit, _setLimit] = useState<number>(10);

const { data, error, refetch } = useDefaultServiceFindPets({ tags, limit });
const { data, error, refetch } = useFindPets({ query: { 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 { data: _ } = useDefaultServiceFindPets();
const { data: _ } = useFindPets();

// 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 } = useDefaultServiceGetNotDefined<undefined>();
const { mutate: mutateNotDefined } =
useDefaultServicePostNotDefined<undefined>();
const { data: notDefined } = useGetNotDefined<undefined>();
const { mutate: mutateNotDefined } = usePostNotDefined<undefined>();

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

if (error)
return (
Expand All @@ -52,12 +55,12 @@ function App() {
onClick={() => {
addPet(
{
requestBody: { name: "Duggy" },
body: { name: "Duggy" },
},
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: UseDefaultServiceFindPetsKeyFn(),
queryKey: UseFindPetsKeyFn({ query: { tags, limit } }),
});
console.log("success");
},
Expand Down
5 changes: 5 additions & 0 deletions examples/react-app/src/axios.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { client } from "../openapi/requests/services.gen";

client.setConfig({
baseURL: "http://localhost:4010",
});
10 changes: 6 additions & 4 deletions examples/react-app/src/components/SuspenseChild.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { useDefaultServiceFindPetsSuspense } from "../../openapi/queries/suspense";
import { useFindPetsSuspense } from "../../openapi/queries/suspense";

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

const { data, error } = useFindPetsSuspense({
query: { tags: [], limit: 10 },
});
console.log({ error });
if (!Array.isArray(data)) {
return <div>Error!</div>;
}

return (
<ul>
{data?.map((pet, index) => (
{data?.map((pet) => (
<li key={pet.id}>{pet.name}</li>
))}
</ul>
Expand Down
1 change: 1 addition & 0 deletions examples/react-app/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import App from "./App";
import "./index.css";
import { QueryClientProvider } from "@tanstack/react-query";
import { queryClient } from "./queryClient";
import "./axios";

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
Expand Down
2 changes: 1 addition & 1 deletion lefthook.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ 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
run: npx biome check --write --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
Loading
Loading