-
-
Notifications
You must be signed in to change notification settings - Fork 544
Add openapi-typescript-helpers package #1300
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"openapi-fetch": patch | ||
--- | ||
|
||
Use openapi-typescript-helpers package for types |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,5 @@ | ||
import type { ErrorResponse, HttpMethod, SuccessResponse, FilterKeys, MediaType, PathsWithMethod, ResponseObjectMap, OperationRequestBodyContent } from "openapi-typescript-helpers"; | ||
|
||
// settings & const | ||
const DEFAULT_HEADERS = { | ||
"Content-Type": "application/json", | ||
|
@@ -19,55 +21,24 @@ interface ClientOptions extends RequestInit { | |
/** global bodySerializer */ | ||
bodySerializer?: BodySerializer<unknown>; | ||
} | ||
export interface BaseParams { | ||
params?: { query?: Record<string, unknown> }; | ||
} | ||
|
||
// const | ||
|
||
export type PathItemObject = { [M in HttpMethod]: OperationObject } & { parameters?: any }; | ||
export type QuerySerializer<T> = (query: T extends { parameters: any } ? NonNullable<T["parameters"]["query"]> : Record<string, unknown>) => string; | ||
export type BodySerializer<T> = (body: OperationRequestBodyContent<T>) => any; | ||
export type ParseAs = "json" | "text" | "blob" | "arrayBuffer" | "stream"; | ||
export interface OperationObject { | ||
parameters: any; | ||
requestBody: any; // note: "any" will get overridden in inference | ||
responses: any; | ||
export interface DefaultParamsOption { | ||
params?: { query?: Record<string, unknown> }; | ||
} | ||
export type HttpMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"; | ||
export type OkStatus = 200 | 201 | 202 | 203 | 204 | 206 | 207 | "2XX"; | ||
// prettier-ignore | ||
export type ErrorStatus = 500 | '5XX' | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 429 | 431 | 444 | 450 | 451 | 497 | 498 | 499 | '4XX' | "default"; | ||
|
||
// util | ||
/** Get a union of paths which have method */ | ||
export type PathsWith<Paths extends Record<string, PathItemObject>, PathnameMethod extends HttpMethod> = { | ||
[Pathname in keyof Paths]: Paths[Pathname] extends { [K in PathnameMethod]: any } ? Pathname : never; | ||
}[keyof Paths]; | ||
/** Find first match of multiple keys */ | ||
export type FilterKeys<Obj, Matchers> = { [K in keyof Obj]: K extends Matchers ? Obj[K] : never }[keyof Obj]; | ||
export type MediaType = `${string}/${string}`; | ||
|
||
// general purpose types | ||
export type Params<T> = T extends { parameters: any } ? { params: NonNullable<T["parameters"]> } : BaseParams; | ||
export type RequestBodyObj<T> = T extends { requestBody?: any } ? T["requestBody"] : never; | ||
export type RequestBodyContent<T> = undefined extends RequestBodyObj<T> ? FilterKeys<NonNullable<RequestBodyObj<T>>, "content"> | undefined : FilterKeys<RequestBodyObj<T>, "content">; | ||
export type RequestBodyMedia<T> = FilterKeys<RequestBodyContent<T>, MediaType> extends never ? FilterKeys<NonNullable<RequestBodyContent<T>>, MediaType> | undefined : FilterKeys<RequestBodyContent<T>, MediaType>; | ||
export type RequestBody<T> = RequestBodyMedia<T> extends never ? { body?: never } : undefined extends RequestBodyMedia<T> ? { body?: RequestBodyMedia<T> } : { body: RequestBodyMedia<T> }; | ||
export type QuerySerializer<T> = (query: T extends { parameters: any } ? NonNullable<T["parameters"]["query"]> : Record<string, unknown>) => string; | ||
export type BodySerializer<T> = (body: RequestBodyMedia<T>) => any; | ||
export type RequestOptions<T> = Params<T> & | ||
RequestBody<T> & { | ||
export type ParamsOption<T> = T extends { parameters: any } ? { params: NonNullable<T["parameters"]> } : DefaultParamsOption; | ||
export type RequestBodyOption<T> = OperationRequestBodyContent<T> extends never ? { body?: never } : undefined extends OperationRequestBodyContent<T> ? { body?: OperationRequestBodyContent<T> } : { body: OperationRequestBodyContent<T> }; | ||
export type FetchOptions<T> = RequestOptions<T> & Omit<RequestInit, "body">; | ||
export type FetchResponse<T> = | ||
| { data: FilterKeys<SuccessResponse<ResponseObjectMap<T>>, MediaType>; error?: never; response: Response } | ||
| { data?: never; error: FilterKeys<ErrorResponse<ResponseObjectMap<T>>, MediaType>; response: Response }; | ||
export type RequestOptions<T> = ParamsOption<T> & | ||
RequestBodyOption<T> & { | ||
querySerializer?: QuerySerializer<T>; | ||
bodySerializer?: BodySerializer<T>; | ||
parseAs?: ParseAs; | ||
}; | ||
export type Success<T> = FilterKeys<FilterKeys<T, OkStatus>, "content">; | ||
export type Error<T> = FilterKeys<FilterKeys<T, ErrorStatus>, "content">; | ||
|
||
// fetch types | ||
export type FetchOptions<T> = RequestOptions<T> & Omit<RequestInit, "body">; | ||
export type FetchResponse<T> = | ||
| { data: T extends { responses: any } ? NonNullable<FilterKeys<Success<T["responses"]>, MediaType>> : unknown; error?: never; response: Response } | ||
| { data?: never; error: T extends { responses: any } ? NonNullable<FilterKeys<Error<T["responses"]>, MediaType>> : unknown; response: Response }; | ||
|
||
export default function createClient<Paths extends {}>(clientOptions: ClientOptions = {}) { | ||
const { fetch = globalThis.fetch, querySerializer: globalQuerySerializer, bodySerializer: globalBodySerializer, ...options } = clientOptions; | ||
|
@@ -94,7 +65,7 @@ export default function createClient<Paths extends {}>(clientOptions: ClientOpti | |
// handle empty content | ||
// note: we return `{}` because we want user truthy checks for `.data` or `.error` to succeed | ||
if (response.status === 204 || response.headers.get("Content-Length") === "0") { | ||
return response.ok ? { data: {} as any, response } : { error: {} as any, response }; | ||
return response.ok ? { data: {} as any, response: response as any } : { error: {} as any, response: response as any }; | ||
} | ||
|
||
// parse response (falling back to .text() when necessary) | ||
|
@@ -104,7 +75,7 @@ export default function createClient<Paths extends {}>(clientOptions: ClientOpti | |
const cloned = response.clone(); | ||
data = typeof cloned[parseAs] === "function" ? await cloned[parseAs]() : await cloned.text(); | ||
} | ||
return { data, response }; | ||
return { data, response: response as any }; | ||
} | ||
|
||
// handle errors (always parse as .json() or .text()) | ||
|
@@ -114,40 +85,40 @@ export default function createClient<Paths extends {}>(clientOptions: ClientOpti | |
} catch { | ||
error = await response.clone().text(); | ||
} | ||
return { error, response }; | ||
return { error, response: response as any }; | ||
} | ||
|
||
return { | ||
/** Call a GET endpoint */ | ||
async GET<P extends PathsWith<Paths, "get">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "get">>) { | ||
async GET<P extends PathsWithMethod<Paths, "get">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "get">>) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. On a related note: type names became more verbose, but for the sake of clarity |
||
return coreFetch<P, "get">(url, { ...init, method: "GET" } as any); | ||
}, | ||
/** Call a PUT endpoint */ | ||
async PUT<P extends PathsWith<Paths, "put">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "put">>) { | ||
async PUT<P extends PathsWithMethod<Paths, "put">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "put">>) { | ||
return coreFetch<P, "put">(url, { ...init, method: "PUT" } as any); | ||
}, | ||
/** Call a POST endpoint */ | ||
async POST<P extends PathsWith<Paths, "post">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "post">>) { | ||
async POST<P extends PathsWithMethod<Paths, "post">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "post">>) { | ||
return coreFetch<P, "post">(url, { ...init, method: "POST" } as any); | ||
}, | ||
/** Call a DELETE endpoint */ | ||
async DELETE<P extends PathsWith<Paths, "delete">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "delete">>) { | ||
async DELETE<P extends PathsWithMethod<Paths, "delete">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "delete">>) { | ||
return coreFetch<P, "delete">(url, { ...init, method: "DELETE" } as any); | ||
}, | ||
/** Call a OPTIONS endpoint */ | ||
async OPTIONS<P extends PathsWith<Paths, "options">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "options">>) { | ||
async OPTIONS<P extends PathsWithMethod<Paths, "options">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "options">>) { | ||
return coreFetch<P, "options">(url, { ...init, method: "OPTIONS" } as any); | ||
}, | ||
/** Call a HEAD endpoint */ | ||
async HEAD<P extends PathsWith<Paths, "head">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "head">>) { | ||
async HEAD<P extends PathsWithMethod<Paths, "head">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "head">>) { | ||
return coreFetch<P, "head">(url, { ...init, method: "HEAD" } as any); | ||
}, | ||
/** Call a PATCH endpoint */ | ||
async PATCH<P extends PathsWith<Paths, "patch">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "patch">>) { | ||
async PATCH<P extends PathsWithMethod<Paths, "patch">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "patch">>) { | ||
return coreFetch<P, "patch">(url, { ...init, method: "PATCH" } as any); | ||
}, | ||
/** Call a TRACE endpoint */ | ||
async TRACE<P extends PathsWith<Paths, "trace">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "trace">>) { | ||
async TRACE<P extends PathsWithMethod<Paths, "trace">>(url: P, init: FetchOptions<FilterKeys<Paths[P], "trace">>) { | ||
return coreFetch<P, "trace">(url, { ...init, method: "TRACE" } as any); | ||
}, | ||
}; | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# openapi-typescript-helpers | ||
|
||
## 0.0.0 | ||
|
||
Initial release |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2023 Drew Powers | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# openapi-typescript-helpers | ||
|
||
Helper utilities that power `openapi-fetch` but are generically-available for any project. | ||
|
||
This package isn’t as well-documented as the others, so it’s a bit “use at your own discretion.” |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types */ | ||
|
||
// HTTP types | ||
|
||
export type HttpMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"; | ||
/** 2XX statuses */ | ||
export type OkStatus = 200 | 201 | 202 | 203 | 204 | 206 | 207 | "2XX"; | ||
// prettier-ignore | ||
/** 4XX and 5XX statuses */ | ||
export type ErrorStatus = 500 | '5XX' | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 429 | 431 | 444 | 450 | 451 | 497 | 498 | 499 | '4XX' | "default"; | ||
|
||
// OpenAPI type helpers | ||
|
||
/** Given an OpenAPI **Paths Object**, find all paths that have the given method */ | ||
export type PathsWithMethod<Paths extends Record<string, PathItemObject>, PathnameMethod extends HttpMethod> = { | ||
[Pathname in keyof Paths]: Paths[Pathname] extends { [K in PathnameMethod]: any } ? Pathname : never; | ||
}[keyof Paths]; | ||
/** Internal helper used in PathsWithMethod */ | ||
export type PathItemObject = { [M in HttpMethod]: OperationObject } & { parameters?: any }; | ||
/** Return `responses` for an Operation Object */ | ||
export type ResponseObjectMap<T> = T extends { responses: any } ? T["responses"] : unknown; | ||
/** Return `content` for a Response Object */ | ||
export type ResponseContent<T> = T extends { content: any } ? T["content"] : unknown; | ||
/** Return `requestBody` for an Operation Object */ | ||
export type OperationRequestBody<T> = T extends { requestBody?: any } ? T["requestBody"] : never; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Almost all the types got renamed. As I was writing down JSDoc descriptions for each, I realized that none of the names made sense (they were close, but didn’t accurately describe how they were actually functioning… in fairness a lot of refactoring happened, though, and the names probably were not kept up with well) |
||
/** Internal helper used in OperationRequestBodyContent */ | ||
export type OperationRequestBodyMediaContent<T> = undefined extends OperationRequestBody<T> ? FilterKeys<NonNullable<OperationRequestBody<T>>, "content"> | undefined : FilterKeys<OperationRequestBody<T>, "content">; | ||
/** Return first `content` from a Request Object Mapping, allowing any media type */ | ||
export type OperationRequestBodyContent<T> = FilterKeys<OperationRequestBodyMediaContent<T>, MediaType> extends never | ||
? FilterKeys<NonNullable<OperationRequestBodyMediaContent<T>>, MediaType> | undefined | ||
: FilterKeys<OperationRequestBodyMediaContent<T>, MediaType>; | ||
/** Return first 2XX response from a Response Object Map */ | ||
export type SuccessResponse<T> = FilterKeys<FilterKeys<T, OkStatus>, "content">; | ||
/** Return first 5XX or 4XX response (in that order) from a Response Object Map */ | ||
export type ErrorResponse<T> = FilterKeys<FilterKeys<T, ErrorStatus>, "content">; | ||
|
||
// Generic TS utils | ||
|
||
/** Find first match of multiple keys */ | ||
export type FilterKeys<Obj, Matchers> = { [K in keyof Obj]: K extends Matchers ? Obj[K] : never }[keyof Obj]; | ||
/** Return any `[string]/[string]` media type (important because openapi-fetch allows any content response, not just JSON-like) */ | ||
export type MediaType = `${string}/${string}`; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
/** | ||
* Stub file to allow importing from the root of the package. | ||
*/ | ||
export default null; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
{ | ||
"name": "openapi-typescript-helpers", | ||
"description": "TypeScript helpers for consuming openapi-typescript types", | ||
"version": "0.0.1", | ||
"author": { | ||
"name": "Drew Powers", | ||
"email": "[email protected]" | ||
}, | ||
"license": "MIT", | ||
"type": "module", | ||
"main": "./index.js", | ||
"types": "./index.d.ts", | ||
"exports": { | ||
".": { | ||
"default": "./index.js", | ||
"types": "./index.d.ts" | ||
}, | ||
"./*": "./*" | ||
}, | ||
"homepage": "https://openapi-ts.pages.dev", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/drwpow/openapi-typescript", | ||
"directory": "packages/openapi-fetch" | ||
}, | ||
"bugs": { | ||
"url": "https://github.com/drwpow/openapi-typescript/issues" | ||
}, | ||
"scripts": { | ||
"lint": "pnpm run lint:js", | ||
"lint:js": "eslint \"*.{js,ts}\"", | ||
"lint:prettier": "prettier --check \"{src,test}/**/*\"", | ||
"test": "tsc --noEmit" | ||
}, | ||
"devDependencies": { | ||
"typescript": "^5.1.6" | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"extends": "../../tsconfig.json", | ||
"compilerOptions": { | ||
"rootDir": "." | ||
}, | ||
"include": ["."] | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The types that were left in here are opinionated and meant specifically for
openapi-fetch
. They are still exported so they can still be used. But hints at “you’re probably only importing this because you want to mimic / mockopenapi-fetch
behavior specifically” while leaving the generic usecases to the new types package