rspace-online/modules/rsocials/lib/listmonk-proxy.ts

46 lines
1.4 KiB
TypeScript

/**
* Listmonk API proxy helper — reads per-space credentials from module settings
* and forwards requests with Basic Auth.
*/
import { loadCommunity, getDocumentData } from "../../../server/community-store";
export interface ListmonkConfig {
url: string;
user: string;
password: string;
}
/** Read Listmonk credentials from the space's module settings. */
export async function getListmonkConfig(spaceSlug: string): Promise<ListmonkConfig | null> {
await loadCommunity(spaceSlug);
const data = getDocumentData(spaceSlug);
if (!data) return null;
const settings = data.meta.moduleSettings?.rsocials;
if (!settings) return null;
const url = settings.listmonkUrl as string | undefined;
const user = settings.listmonkUser as string | undefined;
const password = settings.listmonkPassword as string | undefined;
if (!url || !user || !password) return null;
return { url: url.replace(/\/+$/, ''), user, password };
}
/** Proxy a request to the Listmonk API with Basic Auth. */
export async function listmonkFetch(
config: ListmonkConfig,
path: string,
opts: RequestInit = {},
): Promise<Response> {
const auth = Buffer.from(`${config.user}:${config.password}`).toString("base64");
const headers = new Headers(opts.headers);
headers.set("Authorization", `Basic ${auth}`);
if (!headers.has("Content-Type") && opts.body) {
headers.set("Content-Type", "application/json");
}
return fetch(`${config.url}${path}`, { ...opts, headers });
}