JS-240 · Lesson 12 of 12 · 33 min
Capstone: a real-time order board
▶ Video coming soon A video version of this lesson is on the way.
On Tuesday, July 18, 2028, Mira assembles the course into the feature that started it: a live order board on a tablet in Rosa's kitchen. Since the pilot review on May 26, every lesson has added a piece. The board needs a device that can sign in without anyone typing a password each morning, short-lived tokens, a role that can read the day and nothing else, rate limits, an event stream that survives Wi-Fi drops, and a screen that shows the orders in the order the van is loaded. The review with Theo, Rosa and Gareth is planned for Thursday, July 20, and a trial in the kitchen for Monday, July 24.
This lesson writes the requirements down and traces each one to the lessons and tests that meet it, designs how the tablet is enrolled and how it stays signed in, builds the board's state from events, runs the whole path from a staff member's change to the board's screen with real servers, and sets out the review checklist and the rollout plan. It is also a review of the course, because almost every topic appears in it once more.
Requirements
Mira and Rosa write the requirements together in plain language, and Theo adds the security ones. Every requirement has a number, so that the design, the code and the tests can refer to it.
| No. | Requirement | Lessons |
|---|---|---|
| R1 | The board shows the next delivery day's orders, grouped in the van's loading order, with totals per item | 1, 12 |
| R2 | A change by an agency or the kitchen appears on the board within 5 seconds | 9 |
| R3 | After a dropped connection, the board catches up without missing a change | 9 |
| R4 | The tablet is enrolled once by Rosa and stays signed in for up to 90 days without a password | 4, 12 |
| R5 | The board can read the day and nothing else; changes are made by signed-in people | 6 |
| R6 | A stolen tablet can be cut off at once from Rosa's laptop | 4 |
| R7 | Loaded and delivered are recorded with who made the change | 1, 6 |
| R8 | Agencies see the same changes on the partner page and get the notifications they chose | 9 |
| R9 | Streams, tokens and requests are rate-limited and size-limited | 7 |
| R10 | No new endpoint breaks existing clients; every change is in the changelog | 2 |
Enrolling the tablet
The board is a web page served by the partner service at /board, running full screen on a wall-mounted tablet. It has no keyboard user and no person of its own, so it cannot sign in like a staff member. Instead, Rosa enrolls it once. She signs in on the tablet with her own account, opens /board/setup and presses Enroll this device. The partner service creates a device record named Kitchen board, with the board-device role from lesson 6, and gives the tablet a long-lived refresh token in a cookie. Rosa's own session on the tablet is then ended, so that her permissions do not stay behind on a device anyone can touch.
The refresh token cookie is a little different from the session cookie of lesson 3. It must be sent only to the board's token endpoint, so its Path is /api/partners/v1/board/token, and that rules out the __Host- prefix, which requires Path=/. It uses the __Secure- prefix instead, which requires only the Secure attribute, together with HttpOnly and SameSite=Strict. The refresh token is opaque and stored hashed, it rotates every time it is used with the reuse detection from lesson 4, and the device record has an expiry 90 days after the last use. If the tablet is lost, Rosa revokes the device on her laptop, and the next refresh fails.
| Credential | Where it lives | Lifetime | Sent to |
|---|---|---|---|
| Refresh token | __Secure-board-refresh cookie, HttpOnly, SameSite=Strict | Rotates on every use; device expires 90 days after last use | Only POST /v1/board/token |
| Access token | A JavaScript variable in the board page | 15 minutes | The events stream and the day endpoint |
| Rosa's session | Her own browser, ended on the tablet after enrollment | 30 minutes idle, 12 hours absolute | Everything a kitchen lead may do |
The board's state
The board keeps one piece of state: the day's orders, keyed by id, and the id of the last event applied. When it starts, it loads the day with GET /v1/kitchen/days/:date, then opens the stream with Last-Event-ID set to the id that came with the day, and applies each event as it arrives. Every event goes through one function, a reducer in the sense of JS-220, that takes the current state and an event and returns the new state. Unknown event types are ignored, because new types may be added later, which is the tolerant reading of lesson 2 applied to events.
// The board's state: the day's orders, updated by events.
const ROUTE = ['northside', 'westview', 'elm-seniors']; // the van's loading order
function reduce(state, ev) {
const orders = { ...state.orders };
switch (ev.type) {
case 'order.created': case 'order.changed': orders[ev.data.id] = { ...orders[ev.data.id], ...ev.data }; break;
case 'order.withdrawn': delete orders[ev.data.id]; break;
case 'order.loaded': orders[ev.data.id] = { ...orders[ev.data.id], loaded: true }; break;
case 'order.delivered': orders[ev.data.id] = { ...orders[ev.data.id], status: 'delivered' }; break;
default: return { ...state, lastEventId: ev.id }; // unknown events change nothing but are still counted
}
return { lastEventId: ev.id, orders };
}
function view(state) {
const list = Object.values(state.orders).sort((a, b) => ROUTE.indexOf(a.agency) - ROUTE.indexOf(b.agency) || a.id - b.id);
const totals = {};
for (const o of list) for (const [item, n] of Object.entries(o.trays)) totals[item] = (totals[item] ?? 0) + n;
return { list, totals };
}
let state = { lastEventId: 0, orders: {} };
const events = [
{ id: 1, type: 'order.created', data: { id: 61, agency: 'elm-seniors', trays: { soup: 4, stew: 3 }, status: 'received' } },
{ id: 2, type: 'order.created', data: { id: 62, agency: 'northside', trays: { soup: 6, sandwiches: 2 }, status: 'received' } },
{ id: 3, type: 'order.created', data: { id: 63, agency: 'westview', trays: { sandwiches: 3 }, status: 'received' } },
{ id: 4, type: 'order.changed', data: { id: 62, trays: { soup: 8, sandwiches: 2 } } },
{ id: 5, type: 'order.loaded', data: { id: 62 } },
{ id: 6, type: 'order.withdrawn', data: { id: 63 } },
{ id: 7, type: 'menu.updated', data: {} },
];
for (const ev of events) state = reduce(state, ev);
const { list, totals } = view(state);
console.log('last event', state.lastEventId);
for (const o of list) console.log(`#${o.id} ${o.agency.padEnd(12)} ${JSON.stringify(o.trays)} ${o.loaded ? 'LOADED' : ''}`);
console.log('totals', totals);last event 7
#62 northside {"soup":8,"sandwiches":2} LOADED
#61 elm-seniors {"soup":4,"stew":3}
totals { soup: 12, sandwiches: 2, stew: 3 }What this code does
reduce never changes the old state; it copies the orders and applies one event, so the board can keep or compare earlier states if it needs to. view sorts the orders by the van's route and then by id, and adds up the trays per item across all orders, which is what Rosa's cooks look at first. The withdrawn order disappears, the changed order shows its new trays, and the menu event, which the board does not know, leaves the orders as they were, though its id is still recorded so that it is not replayed after a reconnection.
// The board's state: the day's orders, updated by events.
const ROUTE = ['northside', 'westview', 'elm-seniors']; // the van's loading order
function reduce(state, ev) {
const orders = { ...state.orders };
switch (ev.type) {
case 'order.created': case 'order.changed': orders[ev.data.id] = { ...orders[ev.data.id], ...ev.data }; break;
case 'order.withdrawn': delete orders[ev.data.id]; break;
case 'order.loaded': orders[ev.data.id] = { ...orders[ev.data.id], loaded: true }; break;
case 'order.delivered': orders[ev.data.id] = { ...orders[ev.data.id], status: 'delivered' }; break;
default: return { ...state, lastEventId: ev.id }; // unknown events change nothing but are still counted
}
return { lastEventId: ev.id, orders };
}
function view(state) {
const list = Object.values(state.orders).sort((a, b) => ROUTE.indexOf(a.agency) - ROUTE.indexOf(b.agency) || a.id - b.id);
const totals = {};
for (const o of list) for (const [item, n] of Object.entries(o.trays)) totals[item] = (totals[item] ?? 0) + n;
return { list, totals };
}
function render(state, now) {
const { list, totals } = view(state);
const lines = [`Wednesday, July 19 updated ${now}`, ''];
for (const o of list) {
const items = Object.entries(o.trays).map(([k, n]) => `${n} ${k}`).join(', ');
const mark = o.status === 'delivered' ? '[delivered]' : o.loaded ? '[loaded]' : '';
lines.push(`${String(o.id).padEnd(4)}${o.agency.padEnd(13)}${items.padEnd(26)}${mark}`);
}
lines.push('', 'To cook: ' + Object.entries(totals).map(([k, n]) => `${k} ${n}`).join(' | '));
return lines.join('\n');
}
let state = { lastEventId: 0, orders: {} };
for (const ev of [
{ id: 1, type: 'order.created', data: { id: 61, agency: 'elm-seniors', trays: { soup: 4, stew: 3 }, status: 'received' } },
{ id: 2, type: 'order.created', data: { id: 62, agency: 'northside', trays: { soup: 8, sandwiches: 2 }, status: 'received' } },
{ id: 3, type: 'order.loaded', data: { id: 62 } },
{ id: 4, type: 'order.delivered', data: { id: 62 } },
]) state = reduce(state, ev);
console.log(render(state, '10:58'));Wednesday, July 19 updated 10:58 62 northside 8 soup, 2 sandwiches [delivered] 61 elm-seniors 4 soup, 3 stew To cook: soup 12 | sandwiches 2 | stew 3
What this code does
render turns the board's state into the lines the tablet shows: the day and the time of the last update, one line per order in loading order with its trays and status, and the cooking totals at the bottom. The real board builds the same lines as HTML elements with textContent, never innerHTML, as JS-110 taught, so a note typed by an agency can never inject markup. Keeping rendering separate from the reducer means each can be tested on its own.
Staying connected
The tablet will lose its connection several times a day, and its access token expires every 15 minutes. The board's connection logic is a small state machine. When it is connected, it reads events and remembers the last id. When the stream ends or fails, it waits, with exponential backoff and jitter from lesson 7, starting at 1 second and capped at 30, and reconnects with Last-Event-ID. If the server answers 401, the access token has expired, so it asks the token endpoint for a new one, which also rotates the refresh token, and tries again at once. If the token endpoint itself answers 401, the device has been revoked or has expired, and the board shows a message asking Rosa to enroll it again instead of retrying forever.
// The board's reconnection logic, driven by a script of what the server does.
function controller(script) {
let lastId = 0, delay = 1, t = 0;
const log = (msg) => console.log(`t=${String(t).padStart(3)}s ${msg}`);
for (const step of script) {
if (step.kind === 'events') { lastId = step.upTo; delay = 1; log(`connected after id ${step.from}; got events up to ${lastId}`); t += step.lasts; }
else if (step.kind === 'drop') { log(`connection dropped; retry in ${delay}s`); t += delay; delay = Math.min(delay * 2, 30); }
else if (step.kind === '401-stream') { log('stream says 401: refresh the access token'); }
else if (step.kind === 'token-ok') { log('token endpoint: new access token, refresh token rotated'); }
else if (step.kind === '401-token') { log('token endpoint says 401: show "Ask Rosa to set up this board again"'); return; }
}
}
controller([
{ kind: 'events', from: 0, upTo: 12, lasts: 300 },
{ kind: 'drop' },
{ kind: 'drop' },
{ kind: 'events', from: 12, upTo: 15, lasts: 600 },
{ kind: '401-stream' },
{ kind: 'token-ok' },
{ kind: 'events', from: 15, upTo: 19, lasts: 120 },
{ kind: '401-stream' },
{ kind: '401-token' },
]);t= 0s connected after id 0; got events up to 12 t=300s connection dropped; retry in 1s t=301s connection dropped; retry in 2s t=303s connected after id 12; got events up to 15 t=903s stream says 401: refresh the access token t=903s token endpoint: new access token, refresh token rotated t=903s connected after id 15; got events up to 19 t=1023s stream says 401: refresh the access token t=1023s token endpoint says 401: show "Ask Rosa to set up this board again"
What this code does
The controller follows a script of server behavior so that every branch can be seen in order. Each dropped connection doubles the wait before the next attempt, and a successful connection resets the wait to 1 second and resumes from the last event id, so events 13 to 15 are not missed. A 401 on the stream leads to a token refresh, but a 401 from the token endpoint means the device itself is no longer trusted, and the board stops and asks for a person.
The whole path, end to end
The last piece is to run the path for real: the board gets an access token with its refresh cookie, opens the day's stream with that token, and a kitchen staff member marks an order loaded and then delivered from their own device. The server is a compressed version of the partner service with the same shape: a token endpoint, an authenticated stream, and a PATCH route that publishes after it would have committed. The client is the board's connection code, run with Node.
import http from 'node:http';
import { randomBytes } from 'node:crypto';
const refreshTokens = new Set(['board-kitchen.r7']); // issued when Rosa enrolled the tablet
const accessTokens = new Map(); // token -> expiry (ms)
const streams = new Set();
let seq = 0;
const publish = (type, data) => {
const ev = `id: ${++seq}\nevent: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
for (const res of streams) res.write(ev);
};
const cookie = (req, name) => (req.headers.cookie ?? '').split('; ').find((c) => c.startsWith(name + '='))?.slice(name.length + 1);
http.createServer(async (req, res) => {
const json = (status, body) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };
if (req.method === 'POST' && req.url === '/api/partners/v1/board/token') {
if (!refreshTokens.has(cookie(req, '__Secure-board-refresh'))) return json(401, { title: 'Set up this device again' });
const token = randomBytes(24).toString('base64url');
accessTokens.set(token, Date.now() + 15 * 60 * 1000);
return json(200, { accessToken: token, expiresIn: 900 });
}
if (req.method === 'GET' && req.url === '/api/partners/v1/kitchen/days/2028-07-19/events') {
const token = (req.headers.authorization ?? '').replace(/^Bearer /, '');
if (!(accessTokens.get(token) > Date.now())) return json(401, { title: 'Token missing or expired' });
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
res.write(': connected\n\n');
streams.add(res);
req.on('close', () => streams.delete(res));
return;
}
if (req.method === 'PATCH' && req.url.startsWith('/api/partners/v1/orders/')) {
if (req.headers['x-demo-role'] !== 'kitchen-staff') return json(403, { title: 'Forbidden' }); // stands in for a staff session
let body = '';
for await (const c of req) body += c;
const id = Number(req.url.split('/').pop());
const change = JSON.parse(body);
// ...validate, authorize with the policy, save in a transaction, then publish after commit:
publish(change.status === 'delivered' ? 'order.delivered' : 'order.loaded', { id, ...change });
return json(200, { id, ...change });
}
json(404, { title: 'Not found' });
}).listen(3147);What this code does
The token endpoint accepts only the enrolled device's refresh cookie and returns a random 15-minute access token. The stream endpoint refuses any request without a valid Bearer token, then holds the response open as text/event-stream and registers it with the publisher, removing it when the client disconnects. The PATCH route stands in for a signed-in staff member's change and publishes an event to every open stream after the point where the real service commits the transaction.
$ node board-client.mjs
token: 200 expires in 900 s
stream: 200 text/event-stream
board: #1 order.loaded {"id":61,"loaded":true}
board: #2 order.delivered {"id":61,"status":"delivered"}
stream without a token: 401 Token missing or expired// The board's connection logic, run with Node instead of the tablet's browser.
const base = 'http://localhost:3147/api/partners/v1';
const tok = await fetch(`${base}/board/token`, { method: 'POST', headers: { cookie: '__Secure-board-refresh=board-kitchen.r7' } });
const { accessToken, expiresIn } = await tok.json();
console.log('token:', tok.status, `expires in ${expiresIn} s`);
const ctrl = new AbortController();
const res = await fetch(`${base}/kitchen/days/2028-07-19/events`, { headers: { authorization: `Bearer ${accessToken}` }, signal: ctrl.signal });
console.log('stream:', res.status, res.headers.get('content-type'));
// A kitchen staff member marks two orders, from their own signed-in phone
setTimeout(() => fetch(`${base}/orders/61`, { method: 'PATCH', headers: { 'x-demo-role': 'kitchen-staff' }, body: '{"loaded":true}' }), 200);
setTimeout(() => fetch(`${base}/orders/61`, { method: 'PATCH', headers: { 'x-demo-role': 'kitchen-staff' }, body: '{"status":"delivered"}' }), 400);
let buffer = '', seen = 0;
try {
for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
buffer += chunk;
for (let end; (end = buffer.indexOf('\n\n')) !== -1; ) {
const block = buffer.slice(0, end); buffer = buffer.slice(end + 2);
const line = (f) => block.split('\n').find((l) => l.startsWith(f + ': '))?.slice(f.length + 2);
if (!line('data')) continue;
console.log(`board: #${line('id')} ${line('event')} ${line('data')}`);
if (++seen === 2) ctrl.abort();
}
}
} catch (e) {
if (e.name !== 'AbortError') throw e;
}
const noToken = await fetch(`${base}/kitchen/days/2028-07-19/events`);
console.log('stream without a token:', noToken.status, (await noToken.json()).title);What this code does
The client first exchanges the refresh cookie for an access token, then opens the stream with fetch and an Authorization header, and parses events from a buffer as in lesson 9. Two timed PATCH requests play the part of a kitchen staff member's phone, and each change arrives on the board as a numbered event a moment later. The last request shows that the stream refuses a client without a token.
Two numbered events arrive, loaded and then delivered, each within a fraction of a second of the change. In the kitchen, the time from a tap on a phone to the board updating is dominated by Wi-Fi, comfortably within requirement R2's 5 seconds.
The review checklist
For Thursday's review, Mira prepares a checklist that walks through the course's lessons one more time, with the evidence for each item.
| Area | Check | Evidence |
|---|---|---|
| Design | New endpoints follow the URL rules and return problem details | URL checker run in CI; contract tests |
| Versioning | All changes are additive; changelog entries written; day sheet deprecated with Sunset | Breaking-change checker against the OpenAPI document |
| Authentication | Cookies have the right prefixes and attributes; refresh tokens rotate; reuse revokes the family | Unit tests; a manual check in the browser's storage panel |
| Authorization | The board-device role reads only days; matrix tests pass for every role | node --test policy suite, 48 rows |
| Abuse | Token endpoint, streams and PATCH are rate-limited; at most 3 streams per device or person | Limiter tests with a fake clock |
| Real time | Publishing happens after commit; streams unsubscribe on close; heartbeats every 25 seconds | Integration test with a rolled-back transaction |
| Uploads | Allergen sheet link on the board is a signed URL valid for 24 hours | Signature tests |
| Operations | Theo's web server does not buffer the stream; HTTP/2 enabled; alerts on 401 bursts | Configuration reviewed by Theo |
Rosa's part of the review is the screen itself: the font size readable from the stove, the totals at the bottom where the cooks look, and what happens when the tablet shows the re-enroll message. Her test is simple. During the trial on Monday, July 24, she will phone Northside, ask them to change an order, and count the seconds until the board changes.
Rollout and what comes next
| When (all plans) | What |
|---|---|
| Thursday, July 20, 2028 | Review with Theo, Rosa and Gareth |
| Monday, July 24 | Kitchen trial of the board; printed day sheet kept as a backup |
| Monday, July 31 | Staff sign-in opens: Elm Street with Microsoft, Northside with Google, Westview with passwords |
| Monday, August 14 | Notifications switched on; Northside's import moves to client credentials and its API key is revoked |
| August 1 to November 30 | Day sheet endpoint deprecated, then retired if the access log shows no calls |
| Autumn 2028 | Passkeys for Westview staff; revisit GraphQL if reports multiply |
At the end of the session, Gareth asks Mira what she would tell someone starting the same course. Her answer is the course in one sentence: design the API so it is boring to use, decide who is calling before anything else, check every object against the caller, limit everything, and push changes only after they are true. Then, in the same breath, she asks Theo when the next pilot review is.
Worked problem
Checking requirement R2 with numbers
On the trial day, the path from a tap on a staff member's phone to the board changing has these typical times: phone to server over mobile data 180 ms, validation, policy and database transaction 25 ms, publish and write to the stream 2 ms, server to tablet over the kitchen Wi-Fi 60 ms, and the board's reducer and screen update 15 ms. If the tablet's stream has dropped just before the change, add the first reconnection wait of 1 second and a reconnection of 250 ms. Does the board meet R2's 5 seconds in both cases?
Show solution
- Connected: 180 + 25 + 2 + 60 + 15 = 282 ms.
- Just disconnected: the change is published while the board is away, and the board receives it when it reconnects with Last-Event-ID.
- The wait is 1,000 ms and the reconnection 250 ms, then the replayed event arrives and is applied: 282 + 1,000 + 250 = 1,532 ms in the worst case of this kind.
- Both are well under 5,000 ms.
Answer: About 0.3 seconds normally and about 1.5 seconds just after a drop, both well within R2. Only a longer outage, with backoff waits of 2, 4 and 8 seconds, would exceed it, and R3 guarantees that nothing is missed even then.
Common mistakes
MistakeLeaving Rosa's session signed in on the tablet after enrollment.
InsteadEnd it, so the device keeps only the read-only board role.
MistakeUsing __Host- for a cookie limited to one path.
Instead__Host- requires Path=/. Use __Secure- with Secure, HttpOnly and the narrow path.
MistakeRetrying forever when the token endpoint answers 401.
InsteadA 401 there means the device is revoked or expired; show a message for a person.
MistakeRendering agency notes with innerHTML.
InsteadUse textContent so notes cannot inject markup.
MistakeLetting the board mark orders delivered.
InsteadChanges come from signed-in people, so every change records who made it.
Summary and key terms
- The order board brings the course together.
- Its requirements are numbered and traced to lessons and tests.
- Rosa enrolls the tablet once; it then holds an opaque, rotating refresh token in a __Secure- cookie limited to the board's token endpoint and a 15-minute access token in memory, with the read-only board-device role, and Rosa can revoke it at once.
- The board loads the day, opens the event stream with Last-Event-ID, and applies every event through a reducer that ignores unknown types, then renders the orders in loading order with totals using textContent.
- Its connection logic backs off on drops, refreshes on 401 from the stream and asks for re-enrollment on 401 from the token endpoint.
- Changes come from signed-in people through PATCH, are published after commit and reach the board in well under a second.
- A review checklist covers design, versioning, authentication, authorization, limits, real time, uploads and operations, and the rollout runs from a kitchen trial on July 24 to passkeys in the autumn.
- Enrollment
- Registering a device once, by a trusted person, so it can authenticate on its own afterwards.
- Device record
- The server's record of an enrolled device, with its role, expiry and revocation state.
- __Secure- prefix
- A cookie name prefix that browsers accept only with the Secure attribute.
- Reducer
- A function that takes the current state and an event and returns the new state.
- Requirement trace
- A table linking each requirement to the design, code and tests that meet it.
- Rollout plan
- The dated steps by which a feature is tried, switched on and its predecessor retired.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why does the board's refresh cookie use the __Secure- prefix rather than __Host-?
Show answer
Its Path is the token endpoint, and __Host- requires Path=/.
What does the board do when the stream answers 401?
Show answer
It asks the token endpoint for a new access token and reconnects.
What does a 401 from the token endpoint mean?
Show answer
The device has been revoked or has expired, so a person must enroll it again.
Why does the reducer ignore unknown event types?
Show answer
So that new event types can be added without breaking existing boards.
Who marks an order delivered, and why not the board?
Show answer
A signed-in staff member, so the change records who made it and the board stays read-only.
Try it yourself
Apply board events
Complete apply(orders, ev) so that it returns a new object of orders after one event. order.created adds ev.data under its id, order.withdrawn removes the order, and order.delivered sets its status to delivered.
Any other event type returns orders unchanged. Do not modify the object passed in.
function apply(orders, ev) {
orders[ev.data.id] = ev.data;
return orders;
}
let orders = {};
const before = orders;
for (const ev of [
{ type: 'order.created', data: { id: 61, agency: 'elm-seniors', status: 'received' } },
{ type: 'order.created', data: { id: 62, agency: 'northside', status: 'received' } },
{ type: 'order.delivered', data: { id: 62 } },
{ type: 'order.withdrawn', data: { id: 61 } },
{ type: 'menu.updated', data: {} },
]) orders = apply(orders, ev);
console.log(JSON.stringify(orders));
console.log('original untouched:', Object.keys(before).length === 0);Try it yourself
Decide the next step
Complete nextStep(status, source, delay) for the board's connection logic. source is stream or token. It returns an object with an action and a new delay in seconds.
For a 200 from the stream: { action: 'read', delay: 1 }. For a 401 from the stream: { action: 'refresh', delay }. For a 401 from the token endpoint: { action: 'ask for setup', delay }. For anything else, such as a network error passed as 0 or a 503: { action: 'wait ' + delay, delay: Math.min(delay * 2, 30) }.
function nextStep(status, source, delay) {
return { action: 'wait ' + delay, delay: delay * 2 };
}
let delay = 1;
for (const [status, source] of [[0, 'stream'], [503, 'stream'], [0, 'stream'], [200, 'stream'], [401, 'stream'], [401, 'token']]) {
const step = nextStep(status, source, delay);
delay = step.delay;
console.log(`${source} ${status}: ${step.action} (next delay ${delay})`);
}
console.log(JSON.stringify(nextStep(503, 'stream', 16)), JSON.stringify(nextStep(503, 'stream', 30)));Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.