The official brokerize JavaScript client. The API client comes with TypeScript types so that auto-complete for JS code as well as proper types for TypeScript clients are available. Most of the heavy lifting is in the internal generated code (we use @openapitools/openapi-generator-cli to generate it), but we provide a manually maintained layer around it for a more consistent developer experience.
Example usage:
import { Brokerize, BrokerName } from '@brokerize/client'
async function someBrokerizeActions() {
const brokerize = new Brokerize({
/* provide implementations of fetch, AbortController and WebSocket that will
be used for interacting with the API. If you leave out those dependencies, they will default to globally available
implementations, which should usually work in browsers and newer Node.JS environments, but may fail in other JS environments
that do not provide them (e.g. runtimes in mobile apps). */
fetch: ((url, init) => {
return fetch(url, init)
}) as any,
createAbortController: () => new AbortController(),
createWebSocket: (url, protocol) => new WebSocket(url, protocol),
// basePath: 'https://api-preview.brokerize.com', // this is the default value
// basePathCryptoService: 'https://crypto-service-api.com' // the optional external crypto service
// acceptLanguage: 'de', // optional `Accept-Language` header for localized responses (e.g. legal terms).
// // may also be a function `() => 'de'` that is evaluated on every request,
// // so runtime language changes are picked up without recreating the client.
})
/* create a guest user. the result contains the user's tokens and be stored, e.g. in a cookie or session storage */
const guestUserAuthContextConfiguration = await brokerize.createGuestUser()
const tokenRefreshCallback = (updatedAuthCtx) => {
/* this callback gets called when the token set gets updated and allows you to store it */
};
/* with the guest user's token, create an authorized context.*/
const ctx = brokerize.createAuthorizedContext(guestUserAuthContextConfiguration, tokenRefreshCallback);
/* do some API calls */
console.log('BROKERS', await ctx.getBrokers())
console.log('EXCHANGES', await ctx.getExchanges())
const { id } = await ctx.createDemoAccount()
const demoAccounts = await ctx.getDemoAccounts()
const demoAccount = demoAccounts.accounts.find(x => x.accountId == id)
const session = await ctx.addSession({
brokerName: BrokerName.Demo,
env: 'test',
password: '42',
username: demoAccount.accountName
})
/* subscribe to some non-existent decoupled operation */
const client = ctx.createWebSocketClient()
const s = client.subscribeDecoupledOperation({
decoupledOperationId: 'X',
sessionId: 'XXXX'
}, (err, data) => {
console.log('SUBSCR')
})
s.unsubscribe();
console.log('SESSION', session)
}
someBrokerizeActions().then(console.log, console.error)Every error reported by the websocket client is a BrokerizeWebSocketError, a subclass of
BrokerizeError, so it can be handled like any other error of this library. Errors reach an
application through two separate channels:
- Subscription callbacks only receive terminal errors: the subscription is over and will not
receive any further data. This maps directly onto e.g. an RxJS
subscriber.error(). subscribeConnectionStatereports the state of the underlying connection, including the errors that the client recovers from on its own. Use it to tell the user that live updates are currently unavailable, instead of tearing down subscriptions on every connection hiccup.
const client = ctx.createWebSocketClient();
client.subscribeConnectionState(({ status, error }) => {
/* 'closed' | 'connecting' | 'open' | 'reconnecting' | 'fatal' */
if (status == "fatal") {
/* the client is unusable, all subscriptions were terminated with `error`. */
console.error("live updates stopped", error);
client.reconnect(); /* ... and subscribe again */
}
});
client.subscribeInvalidate({ entity: "sessions" }, (err) => {
if (err) {
/* err is a BrokerizeWebSocketError with err.terminal === true. */
console.error("subscription ended", err.code, err.message);
return;
}
reloadSessions();
});A connection that cannot be authenticated is not a special case: the client refreshes the token
and keeps retrying with a wide backoff, staying in reconnecting with the rejection as error.
The usual cause is an id token that expired in flight, and the first retry fixes it without the
application noticing more than a short gap - the subscriptions stay alive throughout. Only a token
that is still being rejected after several minutes makes the client fatal, because by then the
session is gone rather than stale.
This means an application does not need its own retry: it only has to decide what to show while
status is reconnecting, and how to react to fatal - usually the same way it reacts to a 401
on the REST API, which it will have seen by then anyway.
The code in src/swagger is generated by the npm script npm run generate from the OpenAPI spec and will be regenerated whenever API changes are made. No manual changes should be made in the src/swagger directory. npm run download-spec will download the current spec from api-preview.brokerize.com.
The following manual steps have to be performed when updating the API:
src/webSocketTypes.tsis a copy from the backendwebSocketTypes.tsand must be kept in sync manually for the time being.src/modelExports.tsis a manual selection of the types as generated byopenapi-generator(it generates a few types and internal JSON conversion helpers that do not need to be exported). Have a look at the diff ofsrc/swagger/models/index.tsto see which changes should me made.
npm run build lets api-extractor generate a new API report.
brokerize uses AWS Cognito for user authentication. If clients want brokerize users to log in with their brokerize credentials, they can use the libraries provided by AWS to do so. If you use our component-based solution @brokerize/elements, a wrapper is provided there.
BrokerizeConfig needs to be provided with the cognito configuration, including a CognitoFacade which is responsible for getting the current idToken to use for API calls:
const brokerize = new Brokerize({
// see above:
fetch,
createAbortController,
createWebSocket,
cognito: {
poolConfig /* client and user pool config options */,
cognitoFacade /* a small wrapper interface for retrieving the token */,
},
});