Rates Stream Handling
Sample code for handling rates streaming in Node.js.
Handling Rate Stream Events (Node.js)
const action = async () => {
try {
let shipment_api_url = `https://api.terminal.africa/v1/rates/shipment/stream?shipment_id=SH-ZQKAPYJXGYN4GDES`;
let options = {
headers: {
Authorization: "Bearer {SECRET_KEY}"
}
}
const res = await fetch(shipment_api_url, options);
if (!res.ok) {
let res_json = await res.json();
DEBUG("Response JSON - %O", res_json);
let message = res_json.message || `Rate stream failed: ${res.status} ${res.statusText}`;
throw new Error(message);
}
if (!res.body) {
throw new Error("Response body is empty");
}
const reader = res.body.getReader();
const dec = new TextDecoder();
let buf = "";
for (;;) {
const { value, done } = await reader.read();
DEBUG("Done - %O", done);
if (done) {
buf += dec.decode(); // flush decoder
break;
}
buf += dec.decode(value, { stream: true });
const lines = buf.split("\n");
buf = lines.pop() ?? "";
for (const line of lines) {
if (!line.trim()) continue;
try {
const evt = JSON.parse(line);
if (evt.type === "carrier") {
// merge evt.rates
} else if (evt.type === "complete") {
// final evt.data
// optional: await reader.cancel(); break;
} else if (evt.type === "error") {
// handle backend stream error event if supported
}
} catch (err) {
console.log(err)
}
}
}
}catch(error) {
console.log(error);
}
}
action();Last updated
Was this helpful?