Skip to content
This repository was archived by the owner on Jul 1, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 14 additions & 191 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
# OPA Typescript SDK

Styra's OPA SDK
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a workaround for the missing description in package.json. It feeds into the NPM package descr here:
image

Without this line, it'll look like this (again):
image

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i see

The Styra-supported driver to connect to Open Policy Agent (OPA) and Enterprise OPA deployments.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@srenatus is this better?


[![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.

<!-- Start SDK Installation [installation] -->
## SDK Installation

Expand Down Expand Up @@ -251,37 +256,13 @@ Please refer to [the repository's README.md](https://github.com/StyraInc/opa-typ

---

<!-- Start SDK Example Usage [usage] -->
## 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();
<!--
We've removed most of the auto-generated Speakeasy examples because they generate the wrong import path.
-->

```
<!-- End SDK Example Usage [usage] -->
<!-- No SDK Example Usage [usage] -->

<!-- Start Available Resources and Operations [operations] -->
## Available Resources and Operations
Expand All @@ -293,169 +274,11 @@ run();
* [health](docs/sdks/opaapiclient/README.md#health) - Verify the server is operational
<!-- End Available Resources and Operations [operations] -->

<!-- Start Error Handling [errors] -->
## 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();

```
<!-- End Error Handling [errors] -->

<!-- Start Server Selection [server] -->
## 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();

```

<!-- No Error Handling [errors] -->

### Override Server URL Per-Client
<!-- No Server Selection [server] -->

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();

```
<!-- End Server Selection [server] -->

<!-- Start Custom HTTP Client [http-client] -->
## 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 });
```
<!-- End Custom HTTP Client [http-client] -->
<!-- No Custom HTTP Client [http-client] -->

<!-- Placeholder for Future Speakeasy SDK Sections -->

Expand Down
4 changes: 0 additions & 4 deletions typedoc.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down