@ai-growth/n8n-nodes-wordpress
Version:
n8n node for WordPress integration with AI GROWTH - SEO WP plugin
263 lines (262 loc) • 13.3 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.CtaService = void 0;
var ErrorUtils_1 = require("../utils/ErrorUtils");
var SeoService_1 = require("./SeoService");
/**
* Serviço para gerenciamento de CTAs do WordPress
*/
var CtaService = /** @class */ (function () {
/**
* Construtor do serviço
* @param client Cliente WordPress
* @param seoService Serviço SEO (opcional, será criado se não fornecido)
*/
function CtaService(client, seoService) {
this.pluginEndpoint = 'ai-growth-seo/v1';
this.client = client;
this.seoService = seoService || new SeoService_1.SeoService(client);
}
/**
* Obtém o CTA de um post específico
* @param postId ID do post
* @param options Opções da consulta
* @returns Objeto CTA ou null se não existir
*/
CtaService.prototype.getPostCta = 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 null
if (pluginInfo.status !== 'active') {
return [2 /*return*/, null];
}
_b.label = 2;
case 2:
_b.trys.push([2, 4, , 5]);
return [4 /*yield*/, this.client.get("".concat(this.pluginEndpoint, "/post/").concat(postId, "/cta"))];
case 3:
response = _b.sent();
// Verificar se o CTA existe e é válido
if (!response || (!response.text && !response.url)) {
return [2 /*return*/, null];
}
// Formatar e retornar CTA
return [2 /*return*/, this.formatCta(response)];
case 4:
error_1 = _b.sent();
// Se o plugin não está disponível mas não é requerido, retorna null
if (!requirePlugin) {
return [2 /*return*/, null];
}
// 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 CTA for post ".concat(postId, ": ").concat(error_1.message), ErrorUtils_1.WordPressErrorType.SERVER, undefined, error_1);
case 5: return [2 /*return*/];
}
});
});
};
/**
* Atualiza o CTA de um post específico
* @param postId ID do post
* @param cta CTA para atualizar
* @returns CTA atualizado
*/
CtaService.prototype.updatePostCta = function (postId, cta) {
return __awaiter(this, void 0, void 0, function () {
var pluginInfo, response, error_2, 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, "/cta"), cta)];
case 3:
response = _a.sent();
// Verificar se o CTA foi atualizado corretamente
if (!response) {
return [2 /*return*/, null];
}
// Formatar e retornar CTA atualizado
return [2 /*return*/, {
text: response.text || '',
url: response.url || ''
}];
case 4:
error_2 = _a.sent();
if (!(error_2 instanceof ErrorUtils_1.WordPressError && error_2.type === ErrorUtils_1.WordPressErrorType.SERVER)) return [3 /*break*/, 8];
_a.label = 5;
case 5:
_a.trys.push([5, 7, , 8]);
return [4 /*yield*/, this.addPostCta(postId, cta)];
case 6:
// Tentar adicionar CTA como fallback
return [2 /*return*/, _a.sent()];
case 7:
fallbackError_1 = _a.sent();
// Se o fallback também falhar, lança o erro original
throw error_2;
case 8:
// Relançar o erro original
if (error_2 instanceof ErrorUtils_1.WordPressError) {
throw error_2;
}
throw new ErrorUtils_1.WordPressError("Failed to update CTA for post ".concat(postId, ": ").concat(error_2.message), ErrorUtils_1.WordPressErrorType.SERVER, undefined, error_2);
case 9: return [2 /*return*/];
}
});
});
};
/**
* Adiciona um CTA a um post
* @param postId ID do post
* @param cta CTA para adicionar
* @returns CTA adicionado
*/
CtaService.prototype.addPostCta = function (postId, cta) {
return __awaiter(this, void 0, void 0, function () {
var response, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.client.post("".concat(this.pluginEndpoint, "/post/").concat(postId, "/cta"), cta)];
case 1:
response = _a.sent();
// Verificar se o CTA foi adicionado corretamente
if (!response) {
return [2 /*return*/, null];
}
// Formatar e retornar CTA adicionado
return [2 /*return*/, {
text: response.text || '',
url: response.url || ''
}];
case 2:
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 CTA to post ".concat(postId, ": ").concat(error_3.message), ErrorUtils_1.WordPressErrorType.SERVER, undefined, error_3);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Remove o CTA de um post
* @param postId ID do post
* @returns true se removido com sucesso
*/
CtaService.prototype.removePostCta = function (postId) {
return __awaiter(this, void 0, void 0, function () {
var pluginInfo, error_4;
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]);
// Remover CTA do post
return [4 /*yield*/, this.client["delete"]("".concat(this.pluginEndpoint, "/post/").concat(postId, "/cta"))];
case 3:
// Remover CTA do post
_a.sent();
// Se não houve erro, considerar como sucesso
return [2 /*return*/, true];
case 4:
error_4 = _a.sent();
// Relançar o erro
if (error_4 instanceof ErrorUtils_1.WordPressError) {
throw error_4;
}
throw new ErrorUtils_1.WordPressError("Failed to remove CTA from post ".concat(postId, ": ").concat(error_4.message), ErrorUtils_1.WordPressErrorType.SERVER, undefined, error_4);
case 5: return [2 /*return*/];
}
});
});
};
/**
* Formata os dados de CTA do plugin
* @param cta Dados de CTA da API
* @returns CTA formatado
*/
CtaService.prototype.formatCta = function (cta) {
if (typeof cta === 'object' && cta !== null) {
return {
text: cta.text || '',
url: cta.url || ''
};
}
return {
text: '',
url: ''
};
};
return CtaService;
}());
exports.CtaService = CtaService;