Skip to content

corticph/corti-sdk-javascript

Repository files navigation

Corti JavaScript SDK

fern shield npm shield

This is a Beta version of the Corti JavaScript SDK. We are treating it as stable for production use, but there may still be breaking changes before we reach version 1.0. We're actively working to improve the SDK and would greatly appreciate any feedback if you encounter any inconsistencies or issues đź’š

The Corti JavaScript SDK provides convenient access to the Corti API from JavaScript.

Installation

npm i -s @corti/sdk

Reference

For detailed authentication instructions, see the Authentication Guide.

For information about proxying and securing frontend implementations, see the Proxying Guide.

Usage

Instantiate and use the client with the following:

import { CortiEnvironment, CortiClient } from "@corti/sdk";

// Using client credentials (OAuth2)
const client = new CortiClient({
    environment: CortiEnvironment.Eu,
    tenantName: "YOUR_TENANT_NAME",
    auth: {
        clientId: "YOUR_CLIENT_ID",
        clientSecret: "YOUR_CLIENT_SECRET",
    },
});

// Or using a bearer token
const client = new CortiClient({
    auth: {
        accessToken: "YOUR_ACCESS_TOKEN",
    },
});

// Or using just a refresh function (no initial access token needed)
const client = new CortiClient({
    auth: {
        // refreshToken will be undefined for the first call, then it will be the refreshToken returned from the previous token request
        refreshAccessToken: async (refreshToken?: string) => {
            // Your custom logic to get a new access token
            const response = await fetch("https://your-auth-server/token", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ refreshToken }),
            });

            return response.json();
        },
    },
});

// For user authentication, you can use:
// - Authorization Code Flow
// - Authorization Code Flow with PKCE
// - Resource Owner Password Credentials (ROPC) flow
// See the Authentication Guide for detailed instructions

await client.interactions.create({
    encounter: {
        identifier: "identifier",
        status: "planned",
        type: "first_consultation",
    },
});

Request And Response Types

The SDK exports all request and response types as TypeScript interfaces. Simply import them with the following namespace:

import { Corti } from "@corti/sdk";

const request: Corti.InteractionsListRequest = {
    ...
};

Exception Handling

Depending on the type of error, the SDK will throw one of the following:

  • CortiError: Thrown when the API returns a non-success status code (4xx or 5xx response). This is the base error for API-related issues.
  • ParseError: Thrown when parsing input data fails schema validation. This typically occurs when the data you provide does not match the expected schema.
  • JsonError: Thrown when serializing data to JSON fails schema validation. This typically occurs when converting parsed data to JSON for transmission or storage fails validation.
  • CortiSDKError: Base class for SDK-specific runtime issues (e.g., internal helpers, environment detection). Provides an optional code and cause for debugging.

Example usage:

import { CortiError, ParseError, JsonError, CortiSDKError } from "@corti/sdk";

try {
    await client.interactions.create(...);
} catch (err) {
    if (err instanceof CortiError) {
        // Handle API errors
        console.log(err.statusCode);
        console.log(err.message);
        console.log(err.body);
        console.log(err.rawResponse);
    }
    if (err instanceof ParseError) {
        // Handle schema validation errors during parsing
        console.error("Parse validation error details:", err.errors);
    }
    if (err instanceof JsonError) {
        // Handle schema validation errors during serialization
        console.error("JSON validation error details:", err.errors);
    }
    if (err instanceof CortiSDKError) {
        // Handle other SDK-level errors that expose extra context
        console.error("SDK error code:", err.code);
        console.error("SDK error cause:", err.cause);
        if (err.code === "local_storage_error") {
            console.error("LocalStorage operation failed:", err.message);
        }
    }
}

Pagination

List endpoints are paginated. The SDK provides an iterator so that you can simply loop over the items:

import { CortiEnvironment, CortiClient } from "@corti/sdk";

const client = new CortiClient({
    environment: CortiEnvironment.Eu,
    tenantName: "YOUR_TENANT_NAME",
    auth: {
        clientId: "YOUR_CLIENT_ID",
        clientSecret: "YOUR_CLIENT_SECRET",
    },
});
const response = await client.interactions.list();
for await (const item of response) {
    console.log(item);
}

// Or you can manually iterate page-by-page
const page = await client.interactions.list();
while (page.hasNextPage()) {
    page = page.getNextPage();
}

Advanced

Additional Headers

If you would like to send additional headers as part of the request, use the headers request option.

const response = await client.interactions.create(..., {
    headers: {
        'X-Custom-Header': 'custom value'
    }
});

Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retryable and the number of retry attempts has not grown larger than the configured retry limit (default: 2).

A request is deemed retryable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

Use the maxRetries request option to configure this behavior.

const response = await client.interactions.create(..., {
    maxRetries: 0 // override maxRetries at the request level
});

Timeouts

The SDK defaults to a 60 second timeout. Use the timeoutInSeconds option to configure this behavior.

const response = await client.interactions.create(..., {
    timeoutInSeconds: 30 // override timeout to 30s
});

Aborting Requests

The SDK allows users to abort requests at any point by passing in an abort signal.

const controller = new AbortController();
const response = await client.interactions.create(..., {
    abortSignal: controller.signal
});
controller.abort(); // aborts the request

Access Raw Response Data

The SDK provides access to raw response data, including headers, through the .withRawResponse() method. The .withRawResponse() method returns a promise that results to an object with a data and a rawResponse property.

const { data, rawResponse } = await client.interactions.create(...).withRawResponse();

console.log(data);
console.log(rawResponse.headers['X-My-Header']);

Runtime Compatibility

The SDK defaults to node-fetch but will use the global fetch client if present. The SDK works in the following runtimes:

  • Node.js 18+
  • Modern browsers
  • Vercel
  • Cloudflare Workers
  • Deno v1.25+
  • Bun 1.0+
  • React Native

Customizing Fetch Client

The SDK provides a way for you to customize the underlying HTTP client / Fetch function. If you're running in an unsupported environment, this provides a way for you to break glass and ensure the SDK works.

import { CortiClient } from "@corti/sdk";

const client = new CortiClient({
    ...
    fetcher: // provide your implementation here
});

Contributing

While we value open-source contributions to this SDK, this repo is (mostly) generated programmatically. Additions made directly to this code would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 8