@openapi-codegen/typescript
Advanced tools
Comparing version 2.0.0 to 2.1.0
@@ -15,2 +15,3 @@ "use strict"; | ||
const fetcher_1 = require("../templates/fetcher"); | ||
const lodash_1 = require("lodash"); | ||
const generateFetchers = async (context, config) => { | ||
@@ -43,3 +44,6 @@ const sourceFile = typescript_1.default.createSourceFile("index.ts", "", typescript_1.default.ScriptTarget.Latest); | ||
if (!context.existsFile(`${fetcherFilename}.ts`)) { | ||
context.writeFile(`${fetcherFilename}.ts`, (0, fetcher_1.getFetcher)(filenamePrefix)); | ||
context.writeFile(`${fetcherFilename}.ts`, (0, fetcher_1.getFetcher)({ | ||
prefix: filenamePrefix, | ||
baseUrl: (0, lodash_1.get)(context.openAPIDocument, "servers.0.url"), | ||
})); | ||
} | ||
@@ -46,0 +50,0 @@ else { |
@@ -16,2 +16,3 @@ "use strict"; | ||
const context_1 = require("../templates/context"); | ||
const lodash_1 = require("lodash"); | ||
const generateReactQueryComponents = async (context, config) => { | ||
@@ -44,3 +45,7 @@ const sourceFile = typescript_1.default.createSourceFile("index.ts", "", typescript_1.default.ScriptTarget.Latest); | ||
if (!context.existsFile(`${fetcherFilename}.ts`)) { | ||
context.writeFile(`${fetcherFilename}.ts`, (0, fetcher_1.getFetcher)(filenamePrefix, contextFilename)); | ||
context.writeFile(`${fetcherFilename}.ts`, (0, fetcher_1.getFetcher)({ | ||
prefix: filenamePrefix, | ||
contextPath: contextFilename, | ||
baseUrl: (0, lodash_1.get)(context.openAPIDocument, "servers.0.url"), | ||
})); | ||
} | ||
@@ -47,0 +52,0 @@ if (!context.existsFile(`${contextFilename}.ts`)) { |
@@ -6,2 +6,6 @@ /** | ||
*/ | ||
export declare const getFetcher: (prefix: string, contextPath?: string | undefined) => string; | ||
export declare const getFetcher: ({ prefix, contextPath, baseUrl, }: { | ||
prefix: string; | ||
contextPath?: string | undefined; | ||
baseUrl?: string | undefined; | ||
}) => string; |
@@ -10,6 +10,7 @@ "use strict"; | ||
*/ | ||
const getFetcher = (prefix, contextPath) => `import qs from "qs"; | ||
${contextPath | ||
const getFetcher = ({ prefix, contextPath, baseUrl, }) => `${contextPath | ||
? `import { ${(0, case_1.pascal)(prefix)}Context } from "./${contextPath}";` | ||
: ` | ||
const baseUrl = ${baseUrl ? `"${baseUrl}"` : `""; // TODO add your baseUrl`} | ||
@@ -55,4 +56,4 @@ export type ${(0, case_1.pascal)(prefix)}FetcherExtraProps = { | ||
>): Promise<TData> { | ||
const response = await window.fetch( | ||
resolveUrl(url, queryParams, pathParams), | ||
const response = await window.fetch(\`\${baseUrl} | ||
\${resolveUrl(url, queryParams, pathParams)}\`, | ||
{ | ||
@@ -68,2 +69,3 @@ method: method.toUpperCase(), | ||
if (!response.ok) { | ||
// TODO validate & parse the error to fit the generated error types | ||
throw new Error("Network response was not ok"); | ||
@@ -76,6 +78,6 @@ } | ||
url: string, | ||
queryParams: Record<string, unknown> = {}, | ||
queryParams: Record<string, string> = {}, | ||
pathParams: Record<string, string> = {} | ||
) => { | ||
let query = qs.stringify(queryParams); | ||
let query = new URLSearchParams(queryParams).toString(); | ||
if (query) query = \`?\${query}\`; | ||
@@ -82,0 +84,0 @@ return url.replace(/\\{\\w*\\}/g, (key) => pathParams[key.slice(1, -1)]) + query; |
{ | ||
"name": "@openapi-codegen/typescript", | ||
"version": "2.0.0", | ||
"version": "2.1.0", | ||
"description": "OpenAPI Codegen typescript generators", | ||
@@ -44,3 +44,3 @@ "main": "lib/index.js", | ||
}, | ||
"gitHead": "4a5716864c19142171c5a3311147ceb06cda83d3" | ||
"gitHead": "80ee3e051031d1c70b984e66cb153b8ffb82d1a9" | ||
} |
@@ -29,9 +29,9 @@ # OpenAPI Codegen typescript | ||
export default defineConfig({ | ||
myAPI: { | ||
petstore: { | ||
from: { | ||
/* file, url or github */ | ||
}, | ||
outputDir: "./myAPI", | ||
outputDir: "./petStore", | ||
to: async (context) => { | ||
const filenamePrefix = "myAPI"; | ||
const filenamePrefix = "petStore"; | ||
const { schemasFiles } = await generateSchemaTypes(context, { | ||
@@ -60,5 +60,6 @@ filenamePrefix, | ||
```ts | ||
// `BadassContext.ts` | ||
// `PetStoreContext.ts` | ||
import type { QueryKey, UseQueryOptions } from "react-query"; | ||
export type BadassContext = { | ||
export type PetStoreContext = { | ||
fetcherOptions: { | ||
@@ -68,5 +69,3 @@ /** | ||
*/ | ||
headers?: { | ||
authorization?: string; | ||
}; | ||
headers?: {}; | ||
/** | ||
@@ -84,2 +83,6 @@ * Query params to inject in the fetcher | ||
}; | ||
/** | ||
* Query key middleware. | ||
*/ | ||
queryKeyFn: (queryKey: QueryKey) => QueryKey; | ||
}; | ||
@@ -89,5 +92,18 @@ | ||
* Context injected into every react-query hook wrappers | ||
* | ||
* @param queryOptions options from the useQuery wrapper | ||
*/ | ||
export const useBadassContext = (): BadassContext => { | ||
export function usePetStoreContext< | ||
TQueryFnData = unknown, | ||
TError = unknown, | ||
TData = TQueryFnData, | ||
TQueryKey extends QueryKey = QueryKey | ||
>( | ||
queryOptions?: Omit< | ||
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, | ||
"queryKey" | "queryFn" | ||
> | ||
): BadassContext { | ||
const token = window.localStorage.getItem("token"); | ||
return { | ||
@@ -100,10 +116,49 @@ fetcherOptions: { | ||
queryOptions: { | ||
enabled: Boolean(token), | ||
enabled: Boolean(token) && (queryOptions?.enabled ?? true), | ||
}, | ||
queryKeyFn: (queryKey) => queryKey, | ||
}; | ||
} | ||
``` | ||
You also need to tweak `{filenamePrefix}Fetcher.ts`, to inject your `baseUrl` and adjust the error management part to fullfil the `ErrorType` (you can search for the `TODO` keyword). | ||
#### Usage | ||
First of all, we need to have a working react-query context (more information [here](https://react-query.tanstack.com/quick-start)). | ||
Now that we have all this generated code and properly configured `{filenamePrefix}Fetcher.ts` to talk to the correct server. This is time to try! | ||
Assuming that you have a route with the verb `GET` and the `operationId` as `listPets`. You can simply use `useListPets` in a react component. | ||
```tsx | ||
import { useListPets } from "./petstoreComponents"; | ||
export const MyPage = () => { | ||
const { data, isLoading, error } = useListPets(["listPets"]); // <- You need to add the react-query cache key | ||
return <div>{JSON.stringify({ data, isLoading, error })}</div>; | ||
}; | ||
``` | ||
You can also tweak `{filenamePrefix}Fetcher.ts`, especially the error management part, so everything fit the expected `ErrorType`. | ||
And for any mutation. | ||
```tsx | ||
import { useUpdatePet } from "./pestoreComponents"; | ||
export const MyPage = () => { | ||
const { mutate: updatePet } = useUpdatePet(); | ||
return ( | ||
<button | ||
onClick={() => | ||
updatePet({ pathParams: { id: "2" }, body: { name: "Biscuit" } }) | ||
} | ||
> | ||
Give a cute name | ||
</button> | ||
); | ||
}; | ||
``` | ||
### generateFetchers | ||
@@ -110,0 +165,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
157164
78
1929
257