/** * SendPier Send API — look up one message, or list the most recent ones. * * Requirements: Node.js 18 or newer. Built-in fetch only, no packages. * * Usage: * export SENDPIER_API_KEY='sp_live_...' * export SENDPIER_DOMAIN='example.com' * node get-message.mjs # the five most recent messages * node get-message.mjs 20 # the twenty most recent messages * node get-message.mjs msg_5f1c9a... # one message by its identifier * * Mind the difference between the two answers: the list returns the internal * status of a message, the single lookup returns the public one (queued, * delivered, bounced, complained, failed). Compare like with like, or -- better * -- let a webhook tell you and stop asking. */ const API_BASE = 'https://api.sendpier.com'; /** One GET to the Send API. */ async function sendpierGet(path) { const key = process.env.SENDPIER_API_KEY; const domain = process.env.SENDPIER_DOMAIN; if (!key || !domain) { console.error('set SENDPIER_API_KEY and SENDPIER_DOMAIN first'); process.exit(78); } const response = await fetch(`${API_BASE}${path}`, { headers: { Authorization: `Bearer ${key}`, 'X-Domain-Name': domain, Accept: 'application/json', }, signal: AbortSignal.timeout(30_000), }); const raw = await response.text(); let parsed = null; try { parsed = JSON.parse(raw); } catch { // Keep the raw text: status code and body both belong in your log. } return { status: response.status, body: parsed, raw }; } const argument = process.argv[2] ?? '5'; const response = argument.startsWith('msg_') // An identifier: ask for exactly that message. ? await sendpierGet(`/v1/messages/${encodeURIComponent(argument)}`) // A number: the list endpoint. limit is clamped to 1..20 and defaults to 5. : await sendpierGet(`/v1/messages?limit=${Math.min(20, Math.max(1, Number.parseInt(argument, 10) || 5))}`); console.log(response.raw); if (response.status !== 200) { // 404 message_not_found also covers "this identifier belongs to another // domain" -- a key only ever sees its own. console.error(`request failed with HTTP ${response.status}`); process.exit(1); } // The single lookup answers one message object, the list answers a "messages" // array. Wrapping the first in an array lets one loop print both. const messages = response.body?.messages ?? [response.body]; for (const message of messages) { if (!message) { continue; } console.error([ message.status ?? '?', // The single lookup names the recipient "to", the list "to_email". (message.to ?? message.to_email ?? '?').padEnd(28), message.subject ?? '', ].join(' ')); }