export default async function main(args) {
// Input variables from Voiceflow
const { wpDomain, wpApikey, wpUsername, wpSearchString } = args.inputVars;
// 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 using the custom function
const credentials = `${wpUsername}:${wpApikey}`;
const base64Credentials = base64Encode(credentials);
// Define the API URL with parameters
const baseUrl = `https://${wpDomain}/wp-json/wp/v2/search`;
const queryParams = `?type=post&subtype=post&search=${encodeURIComponent(wpSearchString)}`;
const apiUrl = baseUrl + queryParams;
// Configuration for fetch request
const config = {
method: 'GET',
headers: {
"Authorization": `Basic ${base64Credentials}`,
"Content-Type": "application/json"
}
};
try {
const response = await fetch(apiUrl, config);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const posts = await response.json;
if (!posts || posts.length === 0) {
throw new Error("No posts found");
}
// Format the fetched posts into a bullet list with titles and IDs
const titles = posts.map(post => `• ${post.title} (${post.id})`).join('\n');
return {
outputVars: {
wpPostTitles: titles
},
next: { path: 'success' },
trace: [{ type: "text", payload: { message: `Posts successfully fetched. Here are the titles:\n${titles}` }}]
};
} catch (error) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Error:" + error.message } }]
};
}
}