Using the WapuuLink npm SDK in Your Node.js Projects
As WordPress developers, we're constantly looking for ways to streamline our workflows and build more sophisticated applications. While the WordPress REST API provides a solid foundation, sometimes you need more powerful tools to create truly dynamic WordPress experiences. That's where the WapuuLink โ WordPress Developer API comes in, offering AI-powered capabilities that extend far beyond traditional WordPress development.
In this comprehensive guide, we'll explore how to integrate the WapuuLink npm SDK into your Node.js projects, opening up a world of possibilities for automated WordPress development, content generation, and site management.
Why Use WapuuLink in Node.js Applications?
Before diving into the technical implementation, let's understand why you might want to use WapuuLink in your Node.js projects. Traditional WordPress development often involves manual processes: writing custom post types, creating page templates, setting up complex workflows. WapuuLink's API changes this paradigm by providing:
- AI-powered content generation for posts, pages, and custom components
- Automated theme and plugin creation based on specifications
- Visual QA testing with screenshot comparison capabilities
- Database operations with safe search and replace functionality
- Workflow automation for deployments, migrations, and audits
When you combine these capabilities with Node.js's server-side power, you can build sophisticated WordPress management tools, automated content pipelines, and even custom development platforms.
Setting Up the WapuuLink SDK
Getting started with the WapuuLink SDK is straightforward. First, you'll need to install the package in your Node.js project:
npm install @wapuulink/sdk
Next, you'll need an API key. If you don't have one yet, you can get your WapuuLink API key from the dashboard. Once you have your credentials, you can initialize the SDK:
const { WapuuLink } = require('@wapuulink/sdk');
const wapuu = new WapuuLink({
apiKey: process.env.WAPUU_API_KEY,
baseUrl: 'https://api.wapuulink.com' // Optional, defaults to production
});
It's crucial to store your API key as an environment variable rather than hardcoding it. Create a .env file in your project root:
WAPUU_API_KEY=your_api_key_here
And make sure to load it using a package like dotenv:
require('dotenv').config();
Core SDK Methods and Usage
Content Generation
One of WapuuLink's most powerful features is AI-powered content generation. Here's how you can generate WordPress pages programmatically:
async function generateBlogPost(topic, targetSite) {
try {
const response = await wapuu.content.generatePage({
site: targetSite,
prompt: `Create a comprehensive blog post about ${topic}`,
pageType: 'post',
includeImages: true,
seoOptimized: true
});
console.log('Generated post:', response.data.postId);
return response.data;
} catch (error) {
console.error('Content generation failed:', error.message);
throw error;
}
}
// Usage
generateBlogPost('WordPress performance optimization', 'https://mysite.com');
This approach is particularly powerful when building content management tools or automated publishing workflows. You can learn more about this in our guide on How to Generate WordPress Pages with AI Using WapuuLink.
Plugin and Theme Generation
The SDK also supports automated plugin and theme creation:
async function createCustomPlugin(specifications) {
const pluginConfig = {
name: specifications.pluginName,
description: specifications.description,
features: specifications.features,
hooks: specifications.requiredHooks,
security: 'enhanced'
};
try {
const plugin = await wapuu.plugins.generate(pluginConfig);
// Download the generated plugin files
const files = await wapuu.plugins.download(plugin.id);
return {
pluginId: plugin.id,
downloadUrl: files.zipUrl,
files: files.structure
};
} catch (error) {
console.error('Plugin generation failed:', error);
throw error;
}
}
This capability is especially useful for agencies that need to rapidly prototype plugins or create custom functionality for clients. Check out our detailed guide on Building WordPress Plugins with AI: A Step-by-Step Guide for more advanced techniques.
Site Auditing and Quality Assurance
WapuuLink's audit capabilities can be integrated into your CI/CD pipeline:
async function performSiteAudit(siteUrl) {
const auditConfig = {
url: siteUrl,
checks: [
'performance',
'security',
'seo',
'accessibility',
'best-practices'
],
screenshots: true,
mobileTest: true
};
try {
const audit = await wapuu.audit.run(auditConfig);
// Wait for completion
const results = await wapuu.audit.waitForCompletion(audit.id);
return {
score: results.overallScore,
issues: results.issues,
recommendations: results.recommendations,
screenshots: results.visualComparison
};
} catch (error) {
console.error('Audit failed:', error);
throw error;
}
}
This is invaluable for maintaining site quality and can be automated as part of your deployment process. Learn more in our article about Automated WordPress Site Audits with WapuuLink Workflows.
Building a WordPress Management CLI Tool
Let's create a practical example: a command-line tool for managing WordPress sites using the WapuuLink SDK. This tool will demonstrate several SDK capabilities:
#!/usr/bin/env node
const { Command } = require('commander');
const { WapuuLink } = require('@wapuulink/sdk');
const chalk = require('chalk');
const program = new Command();
const wapuu = new WapuuLink({ apiKey: process.env.WAPUU_API_KEY });
program
.name('wapuu-cli')
.description('WordPress management CLI powered by WapuuLink')
.version('1.0.0');
program
.command('generate-content')
.description('Generate content for a WordPress site')
.requiredOption('-s, --site <url>', 'WordPress site URL')
.requiredOption('-t, --type <type>', 'Content type (post, page, product)')
.requiredOption('-p, --prompt <prompt>', 'Content generation prompt')
.action(async (options) => {
console.log(chalk.blue('๐ Generating content...'));
try {
const result = await wapuu.content.generatePage({
site: options.site,
prompt: options.prompt,
pageType: options.type,
includeImages: true
});
console.log(chalk.green('โ
Content generated successfully!'));
console.log(`Post ID: ${result.postId}`);
console.log(`URL: ${result.url}`);
} catch (error) {
console.error(chalk.red('โ Generation failed:'), error.message);
process.exit(1);
}
});
program
.command('audit')
.description('Run a comprehensive site audit')
.requiredOption('-s, --site <url>', 'Site URL to audit')
.option('-o, --output <file>', 'Output file for results')
.action(async (options) => {
console.log(chalk.blue('๐ Starting site audit...'));
try {
const audit = await performSiteAudit(options.site);
console.log(chalk.green('โ
Audit completed!'));
console.log(`Overall Score: ${audit.score}/100`);
console.log(`Issues Found: ${audit.issues.length}`);
if (options.output) {
require('fs').writeFileSync(options.output, JSON.stringify(audit, null, 2));
console.log(`Results saved to: ${options.output}`);
}
} catch (error) {
console.error(chalk.red('โ Audit failed:'), error.message);
}
});
program.parse();
This CLI tool can be extended with additional commands for plugin generation, theme creation, and deployment automation.
Error Handling and Best Practices
When working with the WapuuLink SDK, proper error handling is essential. The API uses standard HTTP status codes and provides detailed error messages:
async function handleApiOperation(operation) {
try {
const result = await operation();
return { success: true, data: result };
} catch (error) {
// Log detailed error information
console.error('WapuuLink API Error:', {
status: error.status,
message: error.message,
code: error.code,
details: error.details
});
// Handle specific error types
switch (error.status) {
case 401:
throw new Error('Invalid API key. Please check your credentials.');
case 429:
console.warn('Rate limit exceeded. Retrying in 60 seconds...');
await new Promise(resolve => setTimeout(resolve, 60000));
return handleApiOperation(operation);
case 500:
throw new Error('WapuuLink service temporarily unavailable');
default:
throw error;
}
}
}
Rate Limiting and Retries
The WapuuLink API implements rate limiting to ensure fair usage. Implement exponential backoff for resilient applications:
async function retryWithBackoff(operation, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
if (error.status === 429 && attempt < maxRetries) {
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
console.log(`Rate limited. Retrying in ${delay/1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw error;
}
}
}
Advanced Integration Patterns
Webhook Integration
For real-time updates, you can set up webhooks to receive notifications when operations complete:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhooks/wapuulink', (req, res) => {
const { event, data } = req.body;
switch (event) {
case 'content.generated':
console.log('Content generation completed:', data.contentId);
// Update your database, send notifications, etc.
break;
case 'audit.completed':
console.log('Site audit finished:', data.auditId);
// Process audit results
break;
case 'plugin.built':
console.log('Plugin generation finished:', data.pluginId);
// Download and deploy plugin
break;
}
res.status(200).send('OK');
});
app.listen(3000, () => {
console.log('Webhook server listening on port 3000');
});
Database Integration
For applications that manage multiple WordPress sites, integrate with a database to track operations:
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('wapuu-operations.db');
// Initialize database schema
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS operations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL,
site_url TEXT NOT NULL,
status TEXT NOT NULL,
wapuu_id TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
completed_at DATETIME
)`);
});
async function trackOperation(type, siteUrl, wapuuId) {
return new Promise((resolve, reject) => {
db.run(
'INSERT INTO operations (type, site_url, status, wapuu_id) VALUES (?, ?, ?, ?)',
[type, siteUrl, 'pending', wapuuId],
function(err) {
if (err) reject(err);
else resolve(this.lastID);
}
);
});
}
async function updateOperationStatus(operationId, status) {
return new Promise((resolve, reject) => {
db.run(
'UPDATE operations SET status = ?, completed_at = CURRENT_TIMESTAMP WHERE id = ?',
[status, operationId],
(err) => {
if (err) reject(err);
else resolve();
}
);
});
}
Performance Optimization
When building applications with the WapuuLink SDK, consider these performance optimization strategies:
Connection Pooling
For high-throughput applications, implement connection pooling to reuse HTTP connections:
const https = require('https');
const agent = new https.Agent({
keepAlive: true,
maxSockets: 10,
timeout: 60000
});
const wapuu = new WapuuLink({
apiKey: process.env.WAPUU_API_KEY,
httpAgent: agent
});
Parallel Operations
Leverage JavaScript's async capabilities for parallel processing:
async function processMultipleSites(sites) {
const operations = sites.map(site => ({
site,
operation: wapuu.audit.run({ url: site.url })
}));
try {
const results = await Promise.allSettled(
operations.map(op => op.operation)
);
return results.map((result, index) => ({
site: operations[index].site,
success: result.status === 'fulfilled',
data: result.status === 'fulfilled' ? result.value : null,
error: result.status === 'rejected' ? result.reason : null
}));
} catch (error) {
console.error('Batch operation failed:', error);
throw error;
}
}
Testing Your Integration
Testing is crucial when building applications with external APIs. Here's a basic test structure using Jest:
const { WapuuLink } = require('@wapuulink/sdk');
// Mock the SDK for testing
jest.mock('@wapuulink/sdk');
describe('WapuuLink Integration', () => {
let wapuu;
beforeEach(() => {
wapuu = new WapuuLink({ apiKey: 'test-key' });
});
test('should generate content successfully', async () => {
const mockResponse = {
data: {
postId: 123,
url: 'https://example.com/test-post'
}
};
wapuu.content.generatePage.mockResolvedValue(mockResponse);
const result = await generateBlogPost('test topic', 'https://example.com');
expect(result.postId).toBe(123);
expect(wapuu.content.generatePage).toHaveBeenCalledWith({
site: 'https://example.com',
prompt: 'Create a comprehensive blog post about test topic',
pageType: 'post',
includeImages: true,
seoOptimized: true
});
});
});
Security Considerations
When working with APIs in Node.js applications, security should be a top priority:
Environment Variables
Never commit API keys to version control. Use environment variables and consider using a service like AWS Secrets Manager for production applications.
Input Validation
Always validate user inputs before sending them to the API:
const Joi = require('joi');
const contentGenerationSchema = Joi.object({
site: Joi.string().uri().required(),
prompt: Joi.string().min(10).max(1000).required(),
pageType: Joi.string().valid('post