export default async function main(args) {
const { wpUsername, wpDomain, wpApikey } = args.inputVars
const apiUrl = `https://${wpDomain}/wp-json/wp/v2/posts`;
// Custom function to encode a string to Base64
function base64Encode(str) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let encoded = '', i = 0;
while (i < str.length) {
const a = str.charCodeAt(i++);
const b = i < str.length ? str.charCodeAt(i++) : 0;
const c = i < str.length ? str.charCodeAt(i++) : 0;
const b1 = (a >> 2) & 0x3F;
const b2 = ((a & 0x03) << 4) | ((b >> 4) & 0x0F);
const b3 = ((b & 0x0F) << 2) | ((c >> 6) & 0x03);
const b4 = c & 0x3F;
if (!i) {
encoded += chars.charAt(b1) + chars.charAt(b2) + '==';
} else if (i == str.length + 1) {
encoded += chars.charAt(b1) + chars.charAt(b2) + chars.charAt(b3) + '=';
} else {
encoded += chars.charAt(b1) + chars.charAt(b2) + chars.charAt(b3) + chars.charAt(b4);
}
}
return encoded;
}
// Encode credentials
const credentials = `${wpUsername}:${wpApikey}`;
const base64Credentials = base64Encode(credentials);
// Fetch API data with Basic Authentication
try {
const response = await fetch(apiUrl, {
headers: {
"Authorization": `Basic ${base64Credentials}`
}
});
// Check if the response was ok (status 200)
if (response.ok) {
const posts = await response.json; // Parse JSON response
// Check if there are posts
if (posts.length > 0) {
// Map each post title to a formatted string with bullet points
const titles = posts.map(post => `• ${post.title.rendered} (${post.id})`).join('\n');
return {
outputVars: {
wpPostTitles: titles
},
next: {
path: 'success'
},
trace: [
{
type: 'debug',
payload: {
message: `Fetched and processed post titles`
}
}
],
};
} else {
return {
outputVars: {
error: 'No posts found'
},
next: {
path: 'error'
},
trace: [
{
type: 'debug',
payload: {
message: 'No posts available at the API endpoint'
}
}
],
};
}
} else {
throw new Error(`HTTP error! status: ${response.status}`);
}
} catch (error) {
return {
outputVars: {
error: error.toString()
},
next: {
path: 'error'
},
trace: [
{
type: 'debug',
payload: {
message: `Error fetching posts: ${error}`
}
}
],
};
}
}