oRPC OpenAPILink
Use OpenAPILink in oRPC clients to communicate with OpenAPI-compliant APIs.
Файлы2
Открыть в GitHubSKILL.mdskills/orpc-openapi-link/SKILL.md
GitHubOpenAPILink
Enables communication with an OpenAPIHandler or any API following the OpenAPI Specification using HTTP/Fetch.
Installation
npm install @orpc/openapi-client@latest
Setup
import type { JsonifiedClient } from '@orpc/openapi-client'
import type { ContractRouterClient } from '@orpc/contract'
import { createORPCClient, onError } from '@orpc/client'
import { OpenAPILink } from '@orpc/openapi-client/fetch'
const link = new OpenAPILink(contract, {
url: 'http://localhost:3000/api',
headers: () => ({ 'x-api-key': 'my-api-key' }),
fetch: (request, init) => {
return globalThis.fetch(request, {
...init,
credentials: 'include',
})
},
interceptors: [onError(e => console.error(e))],
})
const client: JsonifiedClient<ContractRouterClient<typeof contract>> = createORPCClient(link)
Due to JSON limitations, wrap your client with
JsonifiedClient. Alternatively, see Expanding Type Support for OpenAPI Link.
Limitations
- Payloads with
Blob/Fileoutside root usemultipart/form-dataand Bracket Notation. - For
GETrequests, payload sent asURLSearchParamswith Bracket Notation.
CORS policy
Needs Content-Disposition header to distinguish file responses:
const handler = new OpenAPIHandler(router, {
plugins: [
new CORSPlugin({
exposeHeaders: ['Content-Disposition'],
}),
],
})
Using Client Context
interface ClientContext { something?: string }
const link = new OpenAPILink<ClientContext>(contract, {
url: 'http://localhost:3000/api',
headers: async ({ context }) => ({
'x-api-key': context?.something ?? ''
})
})
const client: JsonifiedClient<ContractRouterClient<typeof contract, ClientContext>> = createORPCClient(link)
const result = await client.planet.list(
{ limit: 10 },
{ context: { something: 'value' } }
)
Lazy URL
const link = new OpenAPILink({
url: () => {
if (typeof window === 'undefined') {
throw new Error('Not allowed on server')
}
return `${window.location.origin}/api`
},
})
Lifecycle
Follows the same lifecycle as RPCLink Lifecycle.