@juo/admin-api
v0.5.0
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *@juo/admin-api* API.
Downloads
1,333
Readme
@juo/admin-api
Developer-friendly & type-safe Typescript SDK specifically catered to leverage @juo/admin-api API.
Summary
Juo Admin API: Programmatic access to subscription management for merchants.
Core Resources
- Subscriptions — the central entity. Belongs to a Customer, contains Items (product variants) and Discounts. Lifecycle:
active→pausedorcancelled;paused→activeorcancelled;cancelled→active(via reactivate). - Items — subscription items (product variants) (quantity, price, billing/delivery policies).
- Discounts — applied to subscriptions by discount code or manually (percentage or fixed amount, targeting subscription items or shipping).
- Customers — customers who own subscriptions and payment methods.
- Products / Variants — catalog products and variants that can be assigned to subscription plans.
- Schedules — a read-only projection of upcoming billing orders, derived from subscription state, active schedule adjustments, and triggered workflows. Schedule adjustments never modify the subscription — they apply changes to upcoming orders matching the specified criteria (by cycle, date, or both), which may cover one or more orders. For permanent changes (billing frequency, items, payment method, delivery address), update the subscription directly.
- Workflows — interactive customer-facing flows (retention, dunning, onboarding). Contain Steps connected by Transitions and produce Runs on each execution. Supports A/B experiment steps.
Authentication
Every request requires:
X-Juo-Admin-Api-Keyheader — the merchant's Admin API key.X-Tenant-IDheader — the store identifier (myshopify domain, e.g.my-store.myshopify.com).
Table of Contents
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add @juo/admin-apiPNPM
pnpm add @juo/admin-apiBun
bun add @juo/admin-apiYarn
yarn add @juo/admin-api[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { Juo } from "@juo/admin-api";
const juo = new Juo({
tenant: "<value>",
security: {
adminApiKey: process.env["JUO_ADMIN_API_KEY"] ?? "",
},
});
async function run() {
const result = await juo.analytics.query({
metric: "subscription-items:count",
grain: "year",
range: {
from: "<value>",
to: "<value>",
},
});
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security schemes globally:
| Name | Type | Scheme | Environment Variable |
| ------------- | ------ | ----------- | -------------------- |
| adminApiKey | apiKey | API key | JUO_ADMIN_API_KEY |
| bearerToken | http | HTTP Bearer | JUO_BEARER_TOKEN |
You can set the security parameters through the security optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:
import { Juo } from "@juo/admin-api";
const juo = new Juo({
security: {
adminApiKey: process.env["JUO_ADMIN_API_KEY"] ?? "",
},
tenant: "<value>",
});
async function run() {
const result = await juo.analytics.query({
metric: "subscription-items:count",
grain: "year",
range: {
from: "<value>",
to: "<value>",
},
});
console.log(result);
}
run();
Available Resources and Operations
Analytics
- query - Query analytics metrics
- listMetrics - Describe the analytics metric catalog
Customers
- list - List customers
- create - Create a customer
- update - Update a customer
- delete - Delete a customer
- createPaymentMethod - Creates a customer payment method
Products
- list - List products
- create - Create a product
- update - Update a product
- delete - Delete a product
- assignProductToPlan - Assign a product to a subscription plan
- removeProductFromPlan - Remove a product from a subscription plan
- addVariant - Add a variant to a product
- removeVariant - Remove a variant from a product
- assignVariantToPlan - Assign a variant to a subscription plan
- removeVariantFromPlan - Remove a variant from a subscription plan
Schedules
- list - List schedule orders
- listAdjustments - List schedule adjustments
- create - Create a schedule adjustment
- delete - Delete a schedule adjustment
Subscriptions
- list - List subscriptions
- create - Create a subscription
- update - Update a subscription
- pause - Pause an active subscription
- resume - Resume a paused subscription
- cancel - Cancel a subscription
- reactivate - Reactivate a canceled subscription
Subscriptions.CustomAttributes
- create - Add custom attributes to a subscription
Subscriptions.Discounts
- create - Add a discount to a subscription
- update - Update a subscription discount
- delete - Remove a subscription discount
Subscriptions.Items
- create - Add an item to a subscription
- update - Update a subscription item
- delete - Remove a subscription item
Workflows
- list - List workflows
- create - Create a workflow
- get - Get a workflow
- update - Update a workflow
- delete - Delete a workflow
- archive - Archive a workflow
- duplicate - Duplicate a workflow
- publish - Publish a workflow
- listRuns - List workflow runs
- unpublish - Unpublish a workflow
- getRun - Get a workflow run
- exportRuns - Export workflow runs as CSV
- getWorkflowsIdRunsExport - Download workflow runs CSV
- getRunStats - Get workflow run statistics
- concludeExperiment - Conclude a workflow experiment
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
analyticsListMetrics- Describe the analytics metric cataloganalyticsQuery- Query analytics metricscustomersCreate- Create a customercustomersCreatePaymentMethod- Creates a customer payment methodcustomersDelete- Delete a customercustomersList- List customerscustomersUpdate- Update a customerproductsAddVariant- Add a variant to a productproductsAssignProductToPlan- Assign a product to a subscription planproductsAssignVariantToPlan- Assign a variant to a subscription planproductsCreate- Create a productproductsDelete- Delete a productproductsList- List productsproductsRemoveProductFromPlan- Remove a product from a subscription planproductsRemoveVariant- Remove a variant from a productproductsRemoveVariantFromPlan- Remove a variant from a subscription planproductsUpdate- Update a productschedulesCreate- Create a schedule adjustmentschedulesDelete- Delete a schedule adjustmentschedulesList- List schedule ordersschedulesListAdjustments- List schedule adjustmentssubscriptionsCancel- Cancel a subscriptionsubscriptionsCreate- Create a subscriptionsubscriptionsCustomAttributesCreate- Add custom attributes to a subscriptionsubscriptionsDiscountsCreate- Add a discount to a subscriptionsubscriptionsDiscountsDelete- Remove a subscription discountsubscriptionsDiscountsUpdate- Update a subscription discountsubscriptionsItemsCreate- Add an item to a subscriptionsubscriptionsItemsDelete- Remove a subscription itemsubscriptionsItemsUpdate- Update a subscription itemsubscriptionsList- List subscriptionssubscriptionsPause- Pause an active subscriptionsubscriptionsReactivate- Reactivate a canceled subscriptionsubscriptionsResume- Resume a paused subscriptionsubscriptionsUpdate- Update a subscriptionworkflowsArchive- Archive a workflowworkflowsConcludeExperiment- Conclude a workflow experimentworkflowsCreate- Create a workflowworkflowsDelete- Delete a workflowworkflowsDuplicate- Duplicate a workflowworkflowsExportRuns- Export workflow runs as CSVworkflowsGet- Get a workflowworkflowsGetRun- Get a workflow runworkflowsGetRunStats- Get workflow run statisticsworkflowsGetWorkflowsIdRunsExport- Download workflow runs CSVworkflowsList- List workflowsworkflowsListRuns- List workflow runsworkflowsPublish- Publish a workflowworkflowsUnpublish- Unpublish a workflowworkflowsUpdate- Update a workflow
Pagination
Some of the endpoints in this SDK support pagination. To use pagination, you
make your SDK calls as usual, but the returned response object will also be an
async iterable that can be consumed using the for await...of
syntax.
Here's an example of one such pagination call:
import { Juo } from "@juo/admin-api";
const juo = new Juo({
tenant: "<value>",
security: {
adminApiKey: process.env["JUO_ADMIN_API_KEY"] ?? "",
},
});
async function run() {
const result = await juo.customers.list({});
for await (const page of result) {
console.log(page);
}
}
run();
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { Juo } from "@juo/admin-api";
const juo = new Juo({
tenant: "<value>",
security: {
adminApiKey: process.env["JUO_ADMIN_API_KEY"] ?? "",
},
});
async function run() {
const result = await juo.analytics.query({
metric: "subscription-items:count",
grain: "year",
range: {
from: "<value>",
to: "<value>",
},
}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Juo } from "@juo/admin-api";
const juo = new Juo({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
tenant: "<value>",
security: {
adminApiKey: process.env["JUO_ADMIN_API_KEY"] ?? "",
},
});
async function run() {
const result = await juo.analytics.query({
metric: "subscription-items:count",
grain: "year",
range: {
from: "<value>",
to: "<value>",
},
});
console.log(result);
}
run();
Error Handling
JuoError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | ------------------------------------------------------ |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
Example
import { Juo } from "@juo/admin-api";
import * as errors from "@juo/admin-api/models/errors";
const juo = new Juo({
tenant: "<value>",
security: {
adminApiKey: process.env["JUO_ADMIN_API_KEY"] ?? "",
},
});
async function run() {
try {
const result = await juo.analytics.query({
metric: "subscription-items:count",
grain: "year",
range: {
from: "<value>",
to: "<value>",
},
});
console.log(result);
} catch (error) {
if (error instanceof errors.JuoError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
}
}
}
run();
Error Classes
Primary error:
JuoError: The base class for HTTP error responses.
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from JuoError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { Juo } from "@juo/admin-api";
const juo = new Juo({
serverURL: "https://api.juo.io/admin/v1",
tenant: "<value>",
security: {
adminApiKey: process.env["JUO_ADMIN_API_KEY"] ?? "",
},
});
async function run() {
const result = await juo.analytics.query({
metric: "subscription-items:count",
grain: "year",
range: {
from: "<value>",
to: "<value>",
},
});
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
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:
- route requests through a proxy server using undici's ProxyAgent
- use the
"beforeRequest"hook to add a custom header and a timeout to requests - use the
"requestError"hook to log errors
import { Juo } from "@juo/admin-api";
import { ProxyAgent } from "undici";
import { HTTPClient } from "@juo/admin-api/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
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 Juo({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Juo } from "@juo/admin-api";
const sdk = new Juo({ debugLogger: console });You can also enable a default debug logger by setting an environment variable JUO_DEBUG to true.
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
