zulip-plane/zulip.js

38 lines
1003 B
JavaScript

/** @typedef {{email: string, apiKey: string, baseURI: string}} Config */
/** @type {(c: Config, url: string, body: Record<string, unknown>) => Promise<void>} */
export const post = async (config, url, body) => {
const params = new URLSearchParams()
Object.entries(body).forEach(([k, v]) => {
params.append(k, typeof v === 'string' ? v : JSON.stringify(v))
})
const rep = await fetch(config.baseURI + url, {
method: 'POST',
body: params,
headers: {
Authorization:
'Basic ' +
Buffer.from(`${config.email}:${config.apiKey}`, 'utf8').toString(
'base64url',
),
},
})
if (!rep.ok) {
let m = `Status not OK: ${rep.status}`
try {
m += '\n' + (await rep.text())
} catch {}
throw new Error(m)
}
}
export default {
Messages: {
/** @type {(c: Config, body: {type: string, to: string, content: string, topic?: string}) => Promise<void>} */
send: async (config, b) => post(config, '/messages', b),
},
}