Fetch API Wrapper

by Matraca Berg March 12, 2026 Public
64 views Raw Download Revisions (v1)
api.js javascript Raw
const BASE = '/wp-json/snipshare/v1';

async function request(path, options = {}) {
  const res = await fetch(`${BASE}${path}`, {
    headers: {
      'Content-Type': 'application/json',
      'X-WP-Nonce': window.snipshareData?.nonce ?? '',
      ...options.headers,
    },
    ...options,
  });

  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw Object.assign(new Error(err.message ?? res.statusText), { status: res.status });
  }

  return res.status === 204 ? null : res.json();
}

export const api = {
  get:    (path)         => request(path),
  post:   (path, body)   => request(path, { method: 'POST',   body: JSON.stringify(body) }),
  put:    (path, body)   => request(path, { method: 'PUT',    body: JSON.stringify(body) }),
  delete: (path)         => request(path, { method: 'DELETE' }),
};
Skip to toolbar