@deadair/sdk
v0.37.1
Published
A typed client for the deadair station's HTTP API, generated from the same contracts the station serves.
Readme
@deadair/sdk
A typed client for a deadair station's HTTP API. It is generated from the same contracts the station serves its routes from, so a method, its parameters and the shape it answers are the station's own and not a hand-kept copy of them. The console is built on it.
npm install @deadair/sdkIt is an ES module only, and it runs anywhere with a global fetch: Node 20 and later, Deno, Bun
and every current browser.
Which version
The SDK is released with the station and carries the station's version: SDK 0.6.0 is the client
for station 0.6.0. Use the version that matches the station you talk to. Before 1.0 a minor step
of the station can change a route, and the SDK changes with it.
Getting started
Every station is self-hosted, so the address is your own. The API is served under /api on the
station's one published port, which on a default install is http://localhost:8080/api.
import { DeadairSdk } from '@deadair/sdk';
const sdk = new DeadairSdk({ baseUrl: 'http://localhost:8080/api' });
const now = await sdk.nowplaying.getNowPlaying();
console.log(now.onAir && now.track ? `${now.track.artist} - ${now.track.title}` : 'off air');getNowPlaying is the one route that needs no sign-in. For the rest, ask for a token with a password
grant and send it on every request. headers may be a function, called once per request, so a token
you replace later is picked up without building a new client:
import { DeadairSdk } from '@deadair/sdk';
let token: string | undefined;
const sdk = new DeadairSdk({
baseUrl: 'http://localhost:8080/api',
headers: (): Record<string, string> => (token ? { Authorization: `Bearer ${token}` } : {}),
});
const answer = await sdk.authentication.requestToken({ grant_type: 'password', username: '[email protected]', password: '...' });
if (answer.result === 'mfa_required') {
throw new Error('this account has a second factor to verify before it gets a token');
}
token = answer.access_token;
const page = await sdk.history.readHistory({ limit: 5 });
for (const entry of page.entries) {
console.log(entry.airedAt.toRelative(), entry.artists, '-', entry.title);
}What each route needs, what it answers and the permissions behind it are in the API reference, which is generated from the same contracts and names the method for every route.
Dates and decimals
A date-time field arrives as a Luxon DateTime and a decimal
field as a decimal.js Decimal, revived from the wire
before the method returns. Both are dependencies of this package, and Luxon's types come with it.
Importing the SDK sets decimal.js's toExpNeg and toExpPos to their limits, so a Decimal
prints as plain digits and never in exponent notation. That setting is global to the copy of
decimal.js the SDK shares with your code. Use Decimal.clone() for a constructor of your own if
you depend on the defaults.
Errors
A response at or above 400 throws SdkError, which carries the status, the statusText, the
headers and the body, parsed as JSON when it is JSON. Every request carries a fresh
X-Request-ID header. Pass requestIdFactory to make the ids yourself.
Your own fetch
fetch in the options replaces the whole transport: the SDK hands it a path relative to the API
root and a RequestInit, and parses whatever Response it returns. createSdkFetch(options)
builds the default one, which is also what throws SdkError, so a wrapper can add behaviour around
it, such as timing every request or retrying a 401 once after refreshing the token:
import { createSdkFetch, DeadairSdk, type SdkFetch } from '@deadair/sdk';
const base = createSdkFetch({ baseUrl: 'http://localhost:8080/api' });
const withLogging: SdkFetch = async (url, init) => {
const started = Date.now();
try {
return await base(url, init);
} finally {
console.debug(init.method, url, `${Date.now() - started}ms`);
}
};
const sdk = new DeadairSdk({ baseUrl: 'http://localhost:8080/api', fetch: withLogging });Where it comes from
Everything under src/ is generated by ContractKit from the .ck contracts in
apps/api/data/contracts,
and none of it is edited by hand. A change to the client is a change to a contract. The same
contracts generate the station's routes, the API reference, an
OpenAPI document for any other language, and the Kotlin, C#
and Swift clients the listener apps are built on.
