@atomic-solutions/wordpress-api-client
v0.1.0
Published
Type-safe WordPress REST API client (platform-agnostic)
Maintainers
Readme
@atomic-solutions/wordpress-utils
Type-safe WordPress REST API client (platform-agnostic)
⚛️ React users: This is a platform-agnostic client. If you're using React or React Native, use
@atomic-solutions/react-wordpressinstead for React Query hooks and context providers.
Features
- 🔒 Type-safe: Full TypeScript support with Zod schema validation
- 🌐 Platform-agnostic: Works in Node.js, browsers, React, React Native
- 🔐 JWT Authentication: Support for JWT Authentication plugin
- 📄 Pagination: Automatic handling of WordPress pagination headers
- 🎯 Error Handling: Built-in error classes with optional error reporter injection
Installation
pnpm add @atomic-solutions/wordpress-utilsFor React/React Native projects, install react-wordpress instead:
pnpm add @atomic-solutions/react-wordpressPeer Dependencies
pnpm add axios zodQuick Start
React users: See
@atomic-solutions/react-wordpressfor React Query hooks and provider.
Basic Usage (Platform-agnostic)
import { createClient } from '@atomic-solutions/wordpress-utils';
// Create a client
const client = createClient({
baseURL: 'https://example.com/wp-json',
jwtToken: {
get: () => AsyncStorage.getItem('wp_jwt_token'),
},
});
// Use the API directly
const posts = await client.posts.list({ per_page: 10 });
const post = await client.posts.get(123);
const categories = await client.categories.list();API Reference
Client Configuration
interface WordPressConfig {
baseURL: string; // WordPress wp-json URL
jwtToken?: JwtTokenAdapter; // Optional JWT token provider
queryKeyPrefix?: string[]; // Query key prefix (default: ['wordpress'])
timeout?: number; // Request timeout (default: 30000)
headers?: Record<string, string>; // Custom headers
errorReporter?: ErrorReporter; // Optional error reporter for tracking (default: console.error)
onRequest?: (config) => config; // Request interceptor
onResponse?: (response) => response; // Response interceptor
onError?: (error) => void; // Error handler
}Client API Methods
The client provides direct access to all WordPress REST API endpoints:
// Posts
const posts = await client.posts.list({ per_page: 10 });
const post = await client.posts.get(123);
const postBySlug = await client.posts.getBySlug('hello-world');
// Categories
const categories = await client.categories.list();
const category = await client.categories.get(5);
// Media
const media = await client.media.get(456);
// Users (requires authentication)
const currentUser = await client.users.me();
// Auth
const token = await client.auth.login({ username: 'user', password: 'pass' });
const isValid = await client.auth.validateToken();Error Handling
import { WordPressError } from '@atomic-solutions/wordpress-utils';
try {
await client.posts.get(999);
} catch (error) {
if (error instanceof WordPressError) {
console.log(error.userMessage); // User-friendly message
console.log(error.wpCode); // WordPress error code
console.log(error.retryable); // Whether to retry
console.log(error.isAuthError); // Authentication error?
console.log(error.isNotFoundError); // 404 error?
}
}Error Reporter Integration
You can integrate with error tracking services like Sentry:
import * as Sentry from '@sentry/react-native';
import { createClient } from '@atomic-solutions/wordpress-utils';
const client = createClient({
baseURL: 'https://example.com/wp-json',
errorReporter: {
report: (error) => Sentry.captureException(error),
},
});Integration Testing
The package provides testing utilities for consumer projects to verify WordPress API connectivity in CI/CD pipelines.
Quick Health Check
import { createClient } from '@atomic-solutions/wordpress-utils';
import { runHealthCheck, assertHealthy } from '@atomic-solutions/wordpress-utils/testing';
test('WordPress API is healthy', async () => {
const client = createClient({ baseURL: process.env.WP_API_URL! });
const report = await runHealthCheck(client);
assertHealthy(report); // Throws if any check fails
expect(report.overall).toBe(true);
}, 30000);Health Checker Factory
import { createHealthChecker } from '@atomic-solutions/wordpress-utils/testing';
const checkHealth = createHealthChecker({
baseURL: process.env.WP_API_URL!,
});
test('WordPress API responds', async () => {
const report = await checkHealth();
expect(report.summary.failed).toBe(0);
});Full Test Suite
For comprehensive integration testing, use the pre-built test suite:
// wordpress-api.integration.test.ts
import { createWordPressTestSuite } from '@atomic-solutions/wordpress-utils/testing';
createWordPressTestSuite({
config: {
baseURL: process.env.WP_API_URL || 'https://example.com/wp-json',
},
timeout: 30000,
skipMedia: false, // Set true if site has no media
skipAuth: true, // Set false if testing JWT auth
});This runs tests for:
- Health check (connectivity, schema validation)
- Posts API (list, single, slug lookup, pagination)
- Categories API (list, single)
- Media API (featured images)
- Auth API (JWT validation, if enabled)
Health Check Report
interface HealthCheckReport {
baseURL: string;
timestamp: string;
overall: boolean; // true if all checks passed
results: HealthCheckResult[];
summary: {
passed: number;
failed: number;
total: number;
};
}Tree-shaking Support
Import only what you need for optimal bundle size:
// Import just the client
import { createClient } from '@atomic-solutions/wordpress-utils/client';
// Import just schemas
import { PostSchema, CategorySchema } from '@atomic-solutions/wordpress-utils/schemas';
// Import just HTTP utilities
import { calculatePagination } from '@atomic-solutions/wordpress-utils/http';
// Import just query keys utility
import { createQueryKeys } from '@atomic-solutions/wordpress-utils/utils';Migration from v1.x
If you were using React hooks from v1.x, follow these steps:
1. Install react-wordpress
pnpm add @atomic-solutions/react-wordpress2. Update Imports
// Before (v1.x)
import { usePosts, WordPressProvider } from '@atomic-solutions/wordpress-utils';
// After (v2.x)
import { usePosts, WordPressProvider } from '@atomic-solutions/react-wordpress';3. Update Dependencies
{
"dependencies": {
"@atomic-solutions/wordpress-utils": "^2.0.0",
"@atomic-solutions/react-wordpress": "^1.1.0"
}
}That's it! The API is identical - only the package name changed.
What Changed in v2.0.0
- ❌ Removed: React hooks (usePosts, useCategories, etc.) - now in
react-wordpress - ❌ Removed: WordPressProvider and WordPressContext - now in
react-wordpress - ❌ Removed: React and React Query peer dependencies
- ✅ Added:
/schemasexport path for tree-shaking - ✅ Added:
/utilsexport path for query keys utility - ✅ Improved: Test coverage (112+ tests)
If You're NOT Using React
No breaking changes! Just update the version:
{
"dependencies": {
"@atomic-solutions/wordpress-utils": "^2.0.0"
}
}Architecture
schemas (Zod schemas)
↓
wordpress-utils (platform-agnostic API client)
↓
react-wordpress (React Query hooks + provider)
↓
React / React Native appsLicense
MIT
