1
0
Fork 0
out-of-your-element-fork-th.../matrix/mreq.js

48 lines
1.1 KiB
JavaScript
Raw Normal View History

2023-05-04 20:25:00 +00:00
// @ts-check
const fetch = require("node-fetch").default
2023-05-04 20:25:00 +00:00
const mixin = require("mixin-deep")
const passthrough = require("../passthrough")
const { sync } = passthrough
/** @type {import("./read-registration")} */
const reg = sync.require("./read-registration.js")
const baseUrl = "https://matrix.cadence.moe/_matrix"
class MatrixServerError extends Error {
2023-05-09 03:29:46 +00:00
constructor(data, opts) {
super(data.error || data.errcode)
2023-05-04 20:25:00 +00:00
this.data = data
/** @type {string} */
this.errcode = data.errcode
2023-05-09 03:29:46 +00:00
this.opts = opts
2023-05-04 20:25:00 +00:00
}
}
/**
* @param {string} method
* @param {string} url
* @param {any} [body]
* @param {any} [extra]
*/
async function mreq(method, url, body, extra = {}) {
2023-05-04 20:25:00 +00:00
const opts = mixin({
method,
body: (body == undefined || Object.is(body.constructor, Object)) ? JSON.stringify(body) : body,
headers: {
Authorization: `Bearer ${reg.as_token}`
}
}, extra)
// console.log(baseUrl + url, opts)
const res = await fetch(baseUrl + url, opts)
const root = await res.json()
2023-05-09 03:29:46 +00:00
if (!res.ok || root.errcode) throw new MatrixServerError(root, opts)
return root
2023-05-04 20:25:00 +00:00
}
module.exports.MatrixServerError = MatrixServerError
module.exports.mreq = mreq