RSS Git Download  Clone
Raw Blame History 1kB 36 lines
import { getAccessToken } from './auth.mjs';

const BASE = 'https://graph.microsoft.com/v1.0';

async function graph(method, path, { body, headers = {}, raw = false } = {}) {
    const token = await getAccessToken();
    const res = await fetch(`${BASE}${path}`, {
        method,
        headers: {
            Authorization: `Bearer ${token}`,
            ...headers,
        },
        body,
    });
    if (!res.ok) {
        const text = await res.text();
        throw new Error(`Graph ${method} ${path} → ${res.status}: ${text}`);
    }
    if (raw) return res;
    const text = await res.text();
    if (!text) return null;
    const contentType = res.headers.get('content-type') || '';
    if (contentType.includes('application/json')) return JSON.parse(text);
    return text;
}

export const graphGet = (path, headers) => graph('GET', path, { headers });
export const graphGetText = (path, headers) => graph('GET', path, { headers, raw: false });
export const graphPostJson = (path, body) =>
    graph('POST', path, { body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } });
export const graphPostHtml = (path, html) =>
    graph('POST', path, { body: html, headers: { 'Content-Type': 'application/xhtml+xml' } });
export const graphPatch = (path, commands) =>
    graph('PATCH', path, { body: JSON.stringify(commands), headers: { 'Content-Type': 'application/json' } });
export const graphDelete = (path) => graph('DELETE', path);