Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
openapi-typescript-fetch
Advanced tools
A typed fetch client for openapi-typescript
npm install openapi-typescript-fetch
Or
yarn add openapi-typescript-fetch
Features
Supports JSON request and responses
Generate typescript definition from schema
npx openapi-typescript https://petstore.swagger.io/v2/swagger.json --output petstore.ts
# 🔭 Loading spec from https://petstore.swagger.io/v2/swagger.json…
# 🚀 https://petstore.swagger.io/v2/swagger.json -> petstore.ts [650ms]
Typed fetch client
import { Fetcher } from 'openapi-typescript-fetch'
import { paths } from './petstore'
// declare fetcher for paths
const fetcher = Fetcher.for<paths>()
// global configuration
fetcher.configure({
baseUrl: 'https://petstore.swagger.io/v2',
init: {
headers: {
...
},
},
use: [...] // middlewares
})
// create fetch operations
const findPetsByStatus = fetcher.path('/pet/findByStatus').method('get').create()
const addPet = fetcher.path('/pet').method('post').create()
// fetch
const { status, data: pets } = await findPetsByStatus({
status: ['available', 'pending'],
})
console.log(pets[0])
A non-ok fetch response throws a generic ApiError
But an Openapi document can declare a different response type for each status code, or a default error response type
These can be accessed via a discriminated union
on status, as in code snippet below
const findPetsByStatus = fetcher.path('/pet/findByStatus').method('get').create()
const addPet = fetcher.path('/pet').method('post').create()
try {
await findPetsByStatus({ ... })
await addPet({ ... })
} catch(e) {
// check which operation threw the exception
if (e instanceof addPet.Error) {
// get discriminated union { status, data }
const error = e.getActualType()
if (error.status === 400) {
error.data.validationErrors // only available for a 400 response
} else if (error.status === 500) {
error.data.errorMessage // only available for a 500 response
} else {
...
}
}
}
Middlewares can be used to pre and post process fetch operations (log api calls, add auth headers etc)
import { Middleware } from 'openapi-typescript-fetch'
const logger: Middleware = async (url, init, next) => {
console.log(`fetching ${url}`)
const response = await next(url, init)
console.log(`fetched ${url}`)
return response
}
fetcher.configure({
baseUrl: 'https://petstore.swagger.io/v2',
init: { ... },
use: [logger],
})
// or
fetcher.use(logger)
OpArgType
- Infer argument type of an operationOpReturnType
- Infer return type of an operationOpErrorType
- Infer error type of an operationFetchArgType
- Argument type of a typed fetch operationFetchReturnType
- Return type of a typed fetch operationFetchErrorType
- Error type of a typed fetch operationTypedFetch
- Fetch operation typeimport { paths, operations } from './petstore'
type Arg = OpArgType<operations['findPetsByStatus']>
type Ret = OpReturnType<operations['findPetsByStatus']>
type Err = OpErrorType<operations['findPetsByStatus']>
type Arg = OpArgType<paths['/pet/findByStatus']['get']>
type Ret = OpReturnType<paths['/pet/findByStatus']['get']>
type Err = OpErrorType<paths['/pet/findByStatus']['get']>
type FindPetsByStatus = TypedFetch<operations['findPetsByStatus']>
const findPetsByStatus = fetcher.path('/pet/findByStatus').method('get').create()
type Arg = FetchArgType<typeof findPetsByStatus>
type Ret = FetchReturnType<typeof findPetsByStatus>
type Err = FetchErrorType<typeof findPetsByStatus>
arrayRequestBody
- Helper to merge params when request body is an array see issue
const body = arrayRequestBody([{ item: 1}], { param: 2})
// body type is { item: number }[] & { param: number }
The baseUrl can be configured with a function that returns the url at runtime
fetcher.configure({
baseUrl: () => getBaseUrl(...)
})
It can also be overriden per method invocation
await findPetsByStatus(
{ status: ['available', 'pending'] },
{ baseUrl: "https://staging.petstore.swagger.io/v2" }
)
Happy fetching! 👍
FAQs
A typed fetch client for openapi-typescript
We found that openapi-typescript-fetch demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.