2023-05-04 20:25:00 +00:00
|
|
|
// @ts-check
|
|
|
|
|
2023-05-05 05:29:08 +00:00
|
|
|
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 {
|
|
|
|
constructor(data) {
|
|
|
|
this.data = data
|
|
|
|
/** @type {string} */
|
|
|
|
this.errcode = data.errcode
|
|
|
|
/** @type {string} */
|
|
|
|
this.error = data.error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {string} method
|
|
|
|
* @param {string} url
|
|
|
|
* @param {any} [body]
|
|
|
|
* @param {any} [extra]
|
|
|
|
*/
|
2023-05-05 05:29:08 +00:00
|
|
|
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)
|
2023-05-05 05:29:08 +00:00
|
|
|
|
2023-05-04 20:25:00 +00:00
|
|
|
console.log(baseUrl + url, opts)
|
2023-05-05 05:29:08 +00:00
|
|
|
const res = await fetch(baseUrl + url, opts)
|
|
|
|
const root = await res.json()
|
|
|
|
|
|
|
|
if (!res.ok || root.errcode) throw new MatrixServerError(root)
|
|
|
|
return root
|
2023-05-04 20:25:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports.MatrixServerError = MatrixServerError
|
|
|
|
module.exports.mreq = mreq
|