JavaScript · Track 1 · Tutorial 2 of 3

Get a token and keep it fresh

Sign your code in to BrizoConsol, keep it signed in as the token runs out, and handle the two answers that simply mean try again.

You will needThe project from Set up your JavaScript project.
By the endA client that signs in, renews itself, and waits when BrizoConsol is busy - and a script that shows what your credential may do.

1Understand the two tokens

Your code doesn't send the client secret with every call. It signs in once and gets two tokens back: an access token, sent with every call and good for 60 minutes, and a refresh token, good for 30 days, which buys the next pair.

The exchange: credential in, two tokens out
Signing in: your client ID and secret go in once; an access token and a refresh token come back.

2Add the HTTP call

Add this to brizo.mjs. It makes one call and gives back the status, the headers and the answer. It asks for JSON on every call, so even a refusal comes back as JSON.

brizo.mjs

// One HTTP call: answers the status, the response headers and the decoded JSON body.
export async function send(method, path, body = null, headers = {}) {
    let response;
    try {
        response = await fetch(baseUrl + path, {
            method,
            headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...headers },
            body: body !== null ? JSON.stringify(body) : (method === 'POST' ? '' : undefined),
            signal: AbortSignal.timeout(TIMEOUT_MS),
        });
    } catch (error) {
        throw new Error(`Could not reach BrizoConsol: ${error.message}`);
    }

    const text = await response.text();
    let decoded = null;
    try {
        decoded = text === '' ? null : JSON.parse(text);
    } catch {
        decoded = null; // not JSON: a proxy or gateway answered instead of BrizoConsol
    }

    return {
        status: response.status,
        headers: Object.fromEntries(response.headers),
        body: decoded,
    };
}

3Add signing in and renewing

Add these two functions. getToken() signs in. refreshToken() spends the refresh token for a new pair - and if that refresh token was already used or has expired, it signs in again.

brizo.mjs

let tokens = null;

export async function getToken() {
    const answer = await send('POST', '/tokens', { client_id: clientId, client_secret: clientSecret });
    if (answer.status !== 201) {
        throw new Error(`Sign-in refused (${answer.status}): ${answer.body?.message ?? ''}`);
    }
    tokens = answer.body;

    return tokens;
}

export async function refreshToken() {
    const answer = await send('POST', '/tokens/refresh', { refresh_token: tokens.refresh_token });
    if (answer.status === 201) {
        tokens = answer.body;
        return;
    }
    await getToken(); // the refresh token was already used or has expired: sign in again
}
Renewing: a 401 spends the refresh token for a new pair
How the client keeps signed in: a 401 spends the refresh token, and the call is sent again.

4Add the call every script uses

Every call after signing in goes through call(). It sends the access token, and handles the two answers that mean send it again:

  • 401 - the access token has expired. It renews once and sends the call again.
  • 429 - the company is busy with another write, or your group has used its requests for the minute. Nothing was written, so it waits as long as BrizoConsol asks and sends again.

brizo.mjs

// Every call after sign-in goes through here. It sends the access token, and handles the two answers that mean
// "send it again": 401 (the token expired) and 429 (the company is busy, or the minute's requests are used up).
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

export async function call(method, path, body = null, headers = {}) {
    if (tokens === null) {
        await getToken();
    }

    let refreshed = false;
    for (let attempt = 1; attempt <= 5; attempt++) {
        const answer = await send(method, path, body, { Authorization: `Bearer ${tokens.access_token}`, ...headers });

        if (answer.status === 401 && !refreshed) {
            await refreshToken();
            refreshed = true;
            continue;
        }

        if (answer.status === 429) {
            await sleep(Number(answer.headers['retry-after'] ?? 5));
            continue; // nothing was written for this call
        }

        return answer;
    }

    throw new Error(`${method} ${path} is still answering 429 after five attempts.`);
}

5Sign in

Create token.mjs and run it:

token.mjs

// token.mjs - signs in with your credential and shows what the token may do.
import { getToken } from './brizo.mjs';

const tokens = await getToken();

console.log(`Signed in. The access token lasts ${tokens.expires_in} seconds.`);
console.log('It may:');
for (const ability of tokens.abilities) {
    console.log(`  ${ability}`);
}
node token.mjs

Check

Signed in. The access token lasts 3600 seconds.
It may:
  read
  write
  organisation:149
  scope:accounts.write
  …

organisation: lists each company the credential can reach, and scope: each box you ticked. If sign-in is refused, the message says why: The client id and secret do not match means a typing error in a setting.

Want more detail? See the documentation