@ai-growth/n8n-nodes-wordpress
Version:
n8n node for WordPress integration with AI GROWTH - SEO WP plugin
284 lines (283 loc) • 14.9 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.FaqService = void 0;
var ErrorUtils_1 = require("../utils/ErrorUtils");
var SeoService_1 = require("./SeoService");
/**
* Serviço para gerenciamento de FAQs do WordPress
*/
var FaqService = /** @class */ (function () {
/**
* Construtor do serviço
* @param client Cliente WordPress
* @param seoService Serviço SEO (opcional, será criado se não fornecido)
*/
function FaqService(client, seoService) {
this.pluginEndpoint = 'ai-growth-seo/v1';
this.client = client;
this.seoService = seoService || new SeoService_1.SeoService(client);
}
/**
* Obtém as FAQs de um post específico
* @param postId ID do post
* @param options Opções da consulta
* @returns Array de FAQs
*/
FaqService.prototype.getPostFaqs = function (postId, options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var _a, requirePlugin, pluginInfo, response, error_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = options.requirePlugin, requirePlugin = _a === void 0 ? false : _a;
return [4 /*yield*/, this.seoService.checkPluginAvailability()];
case 1:
pluginInfo = _b.sent();
// Se o plugin não está disponível e é requerido, lança erro
if (pluginInfo.status !== 'active' && requirePlugin) {
throw new ErrorUtils_1.WordPressError('AI GROWTH - SEO WP plugin is required but not available on the WordPress site', ErrorUtils_1.WordPressErrorType.NOT_FOUND);
}
// Se o plugin não está disponível, retorna array vazio
if (pluginInfo.status !== 'active') {
return [2 /*return*/, []];
}
_b.label = 2;
case 2:
_b.trys.push([2, 4, , 5]);
return [4 /*yield*/, this.client.get("".concat(this.pluginEndpoint, "/post/").concat(postId, "/faq"))];
case 3:
response = _b.sent();
// Verificar se as FAQs existem e são válidas
if (!response || !response.items) {
return [2 /*return*/, []];
}
// Formatar e retornar FAQs
return [2 /*return*/, this.formatFaqs(response.items)];
case 4:
error_1 = _b.sent();
// Se o plugin não está disponível mas não é requerido, retorna array vazio
if (!requirePlugin) {
return [2 /*return*/, []];
}
// Caso contrário, relança o erro
if (error_1 instanceof ErrorUtils_1.WordPressError) {
throw error_1;
}
throw new ErrorUtils_1.WordPressError("Failed to fetch FAQs for post ".concat(postId, ": ").concat(error_1.message), ErrorUtils_1.WordPressErrorType.SERVER, undefined, error_1);
case 5: return [2 /*return*/];
}
});
});
};
/**
* Obtém todas as FAQs do site
* @param options Opções da consulta
* @returns Array de FAQs
*/
FaqService.prototype.getAllFaqs = function (options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var _a, requirePlugin, pluginInfo, response, error_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = options.requirePlugin, requirePlugin = _a === void 0 ? false : _a;
return [4 /*yield*/, this.seoService.checkPluginAvailability()];
case 1:
pluginInfo = _b.sent();
// Se o plugin não está disponível e é requerido, lança erro
if (pluginInfo.status !== 'active' && requirePlugin) {
throw new ErrorUtils_1.WordPressError('AI GROWTH - SEO WP plugin is required but not available on the WordPress site', ErrorUtils_1.WordPressErrorType.NOT_FOUND);
}
// Se o plugin não está disponível, retorna array vazio
if (pluginInfo.status !== 'active') {
return [2 /*return*/, []];
}
_b.label = 2;
case 2:
_b.trys.push([2, 4, , 5]);
return [4 /*yield*/, this.client.get("".concat(this.pluginEndpoint, "/faqs"))];
case 3:
response = _b.sent();
// Verificar se as FAQs existem e são válidas
if (!response || !response.items) {
return [2 /*return*/, []];
}
// Formatar e retornar FAQs
return [2 /*return*/, this.formatFaqs(response.items)];
case 4:
error_2 = _b.sent();
// Se o plugin não está disponível mas não é requerido, retorna array vazio
if (!requirePlugin) {
return [2 /*return*/, []];
}
// Caso contrário, relança o erro
if (error_2 instanceof ErrorUtils_1.WordPressError) {
throw error_2;
}
throw new ErrorUtils_1.WordPressError("Failed to fetch all FAQs: ".concat(error_2.message), ErrorUtils_1.WordPressErrorType.SERVER, undefined, error_2);
case 5: return [2 /*return*/];
}
});
});
};
/**
* Adiciona FAQs a um post
* @param postId ID do post
* @param faqs Array de FAQs para adicionar
* @returns FAQs atualizadas do post
*/
FaqService.prototype.addFaqsToPost = function (postId, faqs) {
return __awaiter(this, void 0, void 0, function () {
var pluginInfo, response, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.seoService.checkPluginAvailability()];
case 1:
pluginInfo = _a.sent();
// Se o plugin não está disponível, lança erro
if (pluginInfo.status !== 'active') {
throw new ErrorUtils_1.WordPressError('AI GROWTH - SEO WP plugin is not available on the WordPress site', ErrorUtils_1.WordPressErrorType.NOT_FOUND);
}
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, this.client.post("".concat(this.pluginEndpoint, "/post/").concat(postId, "/faq"), {
items: faqs
})];
case 3:
response = _a.sent();
// Verificar se as FAQs foram adicionadas corretamente
if (!response || !response.items) {
return [2 /*return*/, []];
}
// Formatar e retornar FAQs atualizadas
return [2 /*return*/, this.formatFaqs(response.items)];
case 4:
error_3 = _a.sent();
// Relançar o erro
if (error_3 instanceof ErrorUtils_1.WordPressError) {
throw error_3;
}
throw new ErrorUtils_1.WordPressError("Failed to add FAQs to post ".concat(postId, ": ").concat(error_3.message), ErrorUtils_1.WordPressErrorType.SERVER, undefined, error_3);
case 5: return [2 /*return*/];
}
});
});
};
/**
* Atualiza as FAQs de um post específico
* @param postId ID do post
* @param faqs Array de FAQs para atualizar
* @returns FAQs atualizadas do post
*/
FaqService.prototype.updatePostFaqs = function (postId, faqs) {
return __awaiter(this, void 0, void 0, function () {
var pluginInfo, response, error_4, fallbackError_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.seoService.checkPluginAvailability()];
case 1:
pluginInfo = _a.sent();
// Se o plugin não está disponível, lança erro
if (pluginInfo.status !== 'active') {
throw new ErrorUtils_1.WordPressError('AI GROWTH - SEO WP plugin is not available on the WordPress site', ErrorUtils_1.WordPressErrorType.NOT_FOUND);
}
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 9]);
return [4 /*yield*/, this.client.put("".concat(this.pluginEndpoint, "/post/").concat(postId, "/faq"), {
items: faqs
})];
case 3:
response = _a.sent();
// Verificar se as FAQs foram atualizadas corretamente
if (!response || !response.items) {
return [2 /*return*/, []];
}
// Formatar e retornar FAQs atualizadas
return [2 /*return*/, this.formatFaqs(response.items)];
case 4:
error_4 = _a.sent();
if (!(error_4 instanceof ErrorUtils_1.WordPressError && error_4.type === ErrorUtils_1.WordPressErrorType.SERVER)) return [3 /*break*/, 8];
_a.label = 5;
case 5:
_a.trys.push([5, 7, , 8]);
return [4 /*yield*/, this.addFaqsToPost(postId, faqs)];
case 6: return [2 /*return*/, _a.sent()];
case 7:
fallbackError_1 = _a.sent();
// Se o fallback também falhar, lança o erro original
throw error_4;
case 8:
// Relançar o erro original
if (error_4 instanceof ErrorUtils_1.WordPressError) {
throw error_4;
}
throw new ErrorUtils_1.WordPressError("Failed to update FAQs for post ".concat(postId, ": ").concat(error_4.message), ErrorUtils_1.WordPressErrorType.SERVER, undefined, error_4);
case 9: return [2 /*return*/];
}
});
});
};
/**
* Formata os dados de FAQ do plugin
* @param faqs Dados de FAQ da API
* @returns FAQs formatadas
*/
FaqService.prototype.formatFaqs = function (faqs) {
if (Array.isArray(faqs)) {
return faqs.map(function (item) { return ({
question: item.question || '',
answer: item.answer || ''
}); });
}
if (typeof faqs === 'object' && faqs !== null) {
// Alguns plugins podem retornar um objeto com índices numéricos
return Object.values(faqs).map(function (item) { return ({
question: item.question || '',
answer: item.answer || ''
}); });
}
return [];
};
return FaqService;
}());
exports.FaqService = FaqService;