UNPKG

wp-plugin-init

Version:

CLI to scaffold a PHP plugin boilerplate structure

47 lines (38 loc) 1.34 kB
import AppConfig from '@/config/AppConfig'; /** * Thin REST client for the plugin's own namespace * (/wp-json/__PLUGIN_NAME__/v1). It injects the WordPress REST nonce on * every request and normalises error handling so components can simply * `await rest.get('/stats')`. */ const base = (AppConfig.get('restUrl') || '').replace(/\/$/, ''); const nonce = AppConfig.get('nonce'); async function request(method, path, body = null) { const url = base + (path.startsWith('/') ? path : '/' + path); const options = { method, headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json', }, credentials: 'same-origin', }; if (body !== null) { options.body = JSON.stringify(body); } const response = await fetch(url, options); const payload = await response.json().catch(() => ({})); if (!response.ok) { const error = new Error(payload?.message || `Request failed (${response.status})`); error.status = response.status; error.payload = payload; throw error; } return payload; } export default { get: (path) => request('GET', path), post: (path, body) => request('POST', path, body), put: (path, body) => request('PUT', path, body), delete: (path) => request('DELETE', path), };