diff --git a/README.md b/README.md index 7690fa1..c905007 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,15 @@ # OPA Typescript SDK -Styra's OPA SDK +The Styra-supported driver to connect to Open Policy Agent (OPA) and Enterprise OPA deployments. [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![NPM Version](https://img.shields.io/npm/v/%40styra%2Fopa?style=flat&color=%2324b6e0)](https://www.npmjs.com/package/@styra/opa) +> [!IMPORTANT] +> The documentation for this SDK lives at https://docs.styra.com/sdk, with reference documentation available at https://styrainc.github.io/opa-typescript + +You can use the Styra OPA SDK to connect to [Open Policy Agent](https://www.openpolicyagent.org/) and [Enterprise OPA](https://www.styra.com/enterprise-opa/) deployments. + ## SDK Installation @@ -251,37 +256,13 @@ Please refer to [the repository's README.md](https://github.com/StyraInc/opa-typ --- - -## SDK Example Usage - -### Example - -```typescript -import { OpaApiClient } from "@styra/opa"; - -const opaApiClient = new OpaApiClient(); - -async function run() { - const result = await opaApiClient.executePolicyWithInput({ - path: "app/rbac", - requestBody: { - input: { - user: "alice", - action: "read", - object: "id123", - type: "dog", - }, - }, - }); - - // Handle the result - console.log(result); -} +# OPA OpenAPI SDK (low-level) -run(); + -``` - + ## Available Resources and Operations @@ -293,169 +274,11 @@ run(); * [health](docs/sdks/opaapiclient/README.md#health) - Verify the server is operational - -## Error Handling - -All SDK methods return a response object or throw an error. If Error objects are specified in your OpenAPI Spec, the SDK will throw the appropriate Error type. - -| Error Object | Status Code | Content Type | -| ------------------ | ------------------ | ------------------ | -| errors.ClientError | 400 | application/json | -| errors.ServerError | 500 | application/json | -| errors.SDKError | 4xx-5xx | */* | - -Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The `SDKValidationError` that is thrown as a result will capture the raw value that failed validation in an attribute called `rawValue`. Additionally, a `pretty()` method is available on this error that can be used to log a nicely formatted string since validation errors can list many issues and the plain error string may be difficult read when debugging. - - -```typescript -import { OpaApiClient } from "@styra/opa"; -import * as errors from "@styra/opa/sdk/models/errors"; - -const opaApiClient = new OpaApiClient(); - -async function run() { - let result; - try { - result = await opaApiClient.executePolicy({ - path: "app/rbac", - }); - } catch (err) { - switch (true) { - case err instanceof errors.SDKValidationError: { - // Validation errors can be pretty-printed - console.error(err.pretty()); - // Raw value may also be inspected - console.error(err.rawValue); - return; - } - case err instanceof errors.ClientError: { - console.error(err); // handle exception - return; - } - case err instanceof errors.ServerError: { - console.error(err); // handle exception - return; - } - default: { - throw err; - } - } - } - - // Handle the result - console.log(result); -} - -run(); - -``` - - - -## Server Selection - -### Select Server by Index - -You can override the default server globally by passing a server index to the `serverIdx` optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers: - -| # | Server | Variables | -| - | ------ | --------- | -| 0 | `http://localhost:8181` | None | - -```typescript -import { OpaApiClient } from "@styra/opa"; - -const opaApiClient = new OpaApiClient({ - serverIdx: 0, -}); - -async function run() { - const result = await opaApiClient.executePolicy({ - path: "app/rbac", - }); - - // Handle the result - console.log(result); -} - -run(); - -``` - + -### Override Server URL Per-Client + -The default server can also be overridden globally by passing a URL to the `serverURL` optional parameter when initializing the SDK client instance. For example: - -```typescript -import { OpaApiClient } from "@styra/opa"; - -const opaApiClient = new OpaApiClient({ - serverURL: "http://localhost:8181", -}); - -async function run() { - const result = await opaApiClient.executePolicy({ - path: "app/rbac", - }); - - // Handle the result - console.log(result); -} - -run(); - -``` - - - -## Custom HTTP Client - -The TypeScript SDK makes API calls using an `HTTPClient` that wraps the native -[Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). This -client is a thin wrapper around `fetch` and provides the ability to attach hooks -around the request lifecycle that can be used to modify the request or handle -errors and response. - -The `HTTPClient` constructor takes an optional `fetcher` argument that can be -used to integrate a third-party HTTP client or when writing tests to mock out -the HTTP client and feed in fixtures. - -The following example shows how to use the `"beforeRequest"` hook to to add a -custom header and a timeout to requests and how to use the `"requestError"` hook -to log errors: - -```typescript -import { OpaApiClient } from "@styra/opa"; -import { HTTPClient } from "@styra/opa/lib/http"; - -const httpClient = new HTTPClient({ - // fetcher takes a function that has the same signature as native `fetch`. - fetcher: (request) => { - return fetch(request); - } -}); - -httpClient.addHook("beforeRequest", (request) => { - const nextRequest = new Request(request, { - signal: request.signal || AbortSignal.timeout(5000); - }); - - nextRequest.headers.set("x-custom-header", "custom value"); - - return nextRequest; -}); - -httpClient.addHook("requestError", (error, request) => { - console.group("Request Error"); - console.log("Reason:", `${error}`); - console.log("Endpoint:", `${request.method} ${request.url}`); - console.groupEnd(); -}); - -const sdk = new OpaApiClient({ httpClient }); -``` - + diff --git a/typedoc.config.cjs b/typedoc.config.cjs index 92d4ffb..595c54e 100644 --- a/typedoc.config.cjs +++ b/typedoc.config.cjs @@ -35,10 +35,6 @@ module.exports = { pattern: `> For low-level SDK usage, see the sections below.\n\n---`, replace: "", }, - { - pattern: "## SDK Example Usage\n", - replace: "## Low-level SDK Examples", // TODO(sr): insert more caveats? - }, { // this captures all links to speakeasy's generated docs pattern: "docs/sdks/opaapiclient/README\\.md",