@onagentic/master-data
v1.1.0
Published
Lightweight client for fetching master data from a API endpoint
Maintainers
Readme
@onagentic/master-data
Lightweight TypeScript client for fetching master data from a Strapi-compatible REST API.
Supports Bearer/custom auth, pagination, field selection, group filtering, auto-pagination, and runtime config updates.
Install
# npm
npm install @onagentic/master-data
# yarn
yarn add @onagentic/master-data
# pnpm
pnpm add @onagentic/master-dataRequires Node.js
>=18.0.0(uses nativefetch).
Quick start
import { createClient } from "@onagentic/master-data";
const client = createClient({
baseUrl: "https://api.example.com",
token: process.env.API_TOKEN!,
});
// Fetch one page — returns MasterDataItem[]
const items = await client.getItems("UNIQUE_KEY");
// Fetch ALL pages automatically — returns MasterDataItem[]
const all = await client.fetchAll("UNIQUE_KEY");
// Full response with pagination meta
const response = await client.fetch("UNIQUE_KEY", {
pagination: { page: 2, pageSize: 50 },
sort: { field: "label", order: "asc" },
fields: ["documentId", "key", "label"],
activeOnly: false,
});
console.log(response.meta.pagination);
// { page: 2, pageSize: 50, pageCount: 4, total: 180 }CJS (CommonJS)
const { createClient } = require("@onagentic/master-data");API
createClient(config)
Factory function. Returns a MasterDataClient instance.
const client = createClient({ baseUrl: "...", token: "..." });MasterDataClient
You can also instantiate the class directly:
import { MasterDataClient } from "@onagentic/master-data";
const client = new MasterDataClient({ baseUrl: "...", token: "..." });client.getItems(groupCode, options?)
Fetch one page and return MasterDataItem[].
const items = await client.getItems("UNIQUE_KEY");client.fetchAll(groupCode, options?)
Auto-paginate all pages and return a flat MasterDataItem[]. Use maxPages to cap the number of pages fetched (default: 100).
const items = await client.fetchAll("UNIQUE_KEY", { activeOnly: false });
const capped = await client.fetchAll("UNIQUE_KEY", { maxPages: 10 });client.fetch(groupCode, options?)
Fetch one page and return the full MasterDataResponse (including meta.pagination).
const { data, meta } = await client.fetch("UNIQUE_KEY", {
pagination: { page: 1, pageSize: 25 },
});
console.log(meta.pagination.total);client.updateConfig(partial)
Update config at runtime without creating a new client (e.g. after token refresh).
client.updateConfig({ token: "new-token" });Config options
| Option | Type | Default | Description |
| ------------------ | --------------------------- | ---------------------------------------------------- | ------------------------------------ |
| baseUrl | string | required | API base URL |
| token | string | — | Bearer token (Authorization header)|
| headers | Record<string, string> | — | Custom/additional request headers |
| apiPath | string | /api/master-datas | API endpoint path |
| defaultFields | string[] | ['documentId','key','label','order','is_active'] | Fields to request |
| defaultPageSize | number | 100 | Items per page |
| defaultSortField | string | 'order' | Default sort field |
| defaultSortOrder | 'asc' \| 'desc' | 'asc' | Default sort direction |
| timeout | number | 10000 | Request timeout in milliseconds |
tokenandheaderscan be used together.headersentries override the defaultAuthorizationheader if you need a custom auth scheme (e.g.{ Authorization: 'Token my-token' }or{ apikey: 'key' }).
Fetch options
FetchOptions — used by fetch() and getItems()
| Option | Type | Default | Description |
| ------------ | ---------------------- | ------- | ------------------------------------ |
| activeOnly | boolean | true | Filter is_active = true |
| pagination | { page?, pageSize? } | — | Override pagination for this request |
| sort | { field?, order? } | — | Override sort for this request |
| fields | string[] | — | Override fields for this request |
FetchAllOptions — extends FetchOptions, used by fetchAll()
| Option | Type | Default | Description |
| ---------- | -------- | ------- | ------------------------------------------------------ |
| maxPages | number | 100 | Max pages to fetch — safeguard against infinite loops |
TypeScript types
All types are exported and can be imported directly:
import type {
MasterDataClientConfig,
MasterDataItem,
MasterDataResponse,
PaginationMeta,
PaginationOptions,
SortOptions,
FetchOptions,
FetchAllOptions,
} from "@onagentic/master-data";
import {
MasterDataClient,
createClient,
MasterDataError,
ValidationError,
TimeoutError,
ApiError,
ResponseShapeError,
} from "@onagentic/master-data";MasterDataItem
interface MasterDataItem {
documentId: string;
key: string;
label: string;
order: number;
is_active: boolean;
[key: string]: unknown; // extra fields from API
}MasterDataResponse
interface MasterDataResponse {
data: MasterDataItem[];
meta: {
pagination: PaginationMeta;
};
}PaginationMeta
interface PaginationMeta {
page: number;
pageSize: number;
pageCount: number;
total: number;
}Error handling
All errors extend MasterDataError — use instanceof to branch by type:
import { ApiError, TimeoutError, ValidationError, ResponseShapeError } from "@onagentic/master-data";
try {
const items = await client.getItems("UNIQUE_KEY");
} catch (err) {
if (err instanceof ApiError) {
console.error(`HTTP ${err.status}:`, err.body);
} else if (err instanceof TimeoutError) {
console.error(`Timed out after ${err.timeoutMs}ms`);
} else if (err instanceof ValidationError) {
console.error("Bad config:", err.message);
} else if (err instanceof ResponseShapeError) {
console.error("Unexpected API response:", err.message);
} else {
throw err;
}
}| Class | When thrown | Extra properties |
| -------------------- | -------------------------------------------------- | ------------------------- |
| ValidationError | baseUrl or groupCode is missing | — |
| TimeoutError | Request exceeds timeout ms | .timeoutMs: number |
| ApiError | HTTP response is not 2xx | .status, .body |
| ResponseShapeError | Response JSON doesn't match expected shape | — |
Release
# 1. Bump version
npm version patch # or: minor / major
# 2. Build, test, then publish
npm publish
prepublishOnlyrunsbuildandtestautomatically before publish. No need for--access public— already configured inpackage.json.
License
MIT
