@ai-growth/n8n-nodes-wordpress
Version:
n8n node for WordPress integration with AI GROWTH - SEO WP plugin
924 lines (923 loc) • 43.6 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
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 };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
exports.__esModule = true;
exports.TaxonomyService = void 0;
var ErrorUtils_1 = require("../utils/ErrorUtils");
/**
* Serviço para gerenciamento de taxonomias do WordPress (categorias e tags)
*/
var TaxonomyService = /** @class */ (function () {
/**
* Construtor do serviço
* @param client Cliente WordPress
*/
function TaxonomyService(client) {
this.taxonomyEndpoints = {
category: 'wp/v2/categories',
post_tag: 'wp/v2/tags'
};
this.client = client;
}
/**
* Obtém o endpoint para o tipo de taxonomia
* @param type Tipo de taxonomia
* @returns Endpoint da taxonomia
*/
TaxonomyService.prototype.getTaxonomyEndpoint = function (type) {
return this.taxonomyEndpoints[type];
};
/**
* Converte opções de consulta para parâmetros de requisição
* @param options Opções de consulta
* @returns Parâmetros da requisição
*/
TaxonomyService.prototype.getQueryParams = function (options) {
var params = {};
// Paginação
if (options.page) {
params.page = options.page.toString();
}
if (options.perPage) {
params.per_page = options.perPage.toString();
}
// Busca
if (options.search) {
params.search = options.search;
}
// Pai (apenas para categorias)
if (options.parent !== undefined) {
params.parent = options.parent.toString();
}
return params;
};
/**
* Verifica se uma taxonomia existe
* @param type Tipo de taxonomia
* @param nameOrId Nome ou ID da taxonomia
* @returns A taxonomia encontrada ou null
*/
TaxonomyService.prototype.checkExists = function (type, nameOrId) {
return __awaiter(this, void 0, void 0, function () {
var endpoint, result, error_1, params, results, exactMatch, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 6, , 7]);
endpoint = this.getTaxonomyEndpoint(type);
if (!(typeof nameOrId === 'number')) return [3 /*break*/, 4];
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.client.get("".concat(endpoint, "/").concat(nameOrId))];
case 2:
result = _a.sent();
return [2 /*return*/, result];
case 3:
error_1 = _a.sent();
// Se não encontrar pelo ID, retorna null
if (error_1 instanceof ErrorUtils_1.WordPressError && error_1.type === ErrorUtils_1.WordPressErrorType.NOT_FOUND) {
return [2 /*return*/, null];
}
throw error_1;
case 4:
params = { search: nameOrId };
return [4 /*yield*/, this.client.get(endpoint, params)];
case 5:
results = _a.sent();
// Verificar resultados para encontrar correspondência exata
if (Array.isArray(results) && results.length > 0) {
exactMatch = results.find(function (item) {
if (typeof item.name === 'string' && typeof item.slug === 'string' && typeof nameOrId === 'string') {
return item.name.toLowerCase() === nameOrId.toLowerCase() ||
item.slug.toLowerCase() === nameOrId.toLowerCase();
}
return false;
});
if (exactMatch) {
return [2 /*return*/, exactMatch];
}
}
return [2 /*return*/, null];
case 6:
error_2 = _a.sent();
if (error_2 instanceof ErrorUtils_1.WordPressError) {
throw error_2;
}
throw new ErrorUtils_1.WordPressError("Erro ao verificar exist\u00EAncia de ".concat(type, ": ").concat(nameOrId), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_2);
case 7: return [2 /*return*/];
}
});
});
};
/**
* Obtém uma categoria por ID ou nome
* @param idOrName ID ou nome da categoria
* @returns Categoria encontrada ou null
*/
TaxonomyService.prototype.getCategory = function (idOrName) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.checkExists('category', idOrName)];
});
});
};
/**
* Obtém uma tag por ID ou nome
* @param idOrName ID ou nome da tag
* @returns Tag encontrada ou null
*/
TaxonomyService.prototype.getTag = function (idOrName) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.checkExists('post_tag', idOrName)];
});
});
};
/**
* Obtém categorias com base em opções de filtro
* @param options Opções de consulta
* @returns Lista de categorias
*/
TaxonomyService.prototype.getCategories = function (options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var endpoint, params, results, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
endpoint = this.getTaxonomyEndpoint('category');
params = this.getQueryParams(options);
return [4 /*yield*/, this.client.get(endpoint, params)];
case 1:
results = _a.sent();
return [2 /*return*/, results];
case 2:
error_3 = _a.sent();
if (error_3 instanceof ErrorUtils_1.WordPressError) {
throw error_3;
}
throw new ErrorUtils_1.WordPressError('Erro ao obter categorias', ErrorUtils_1.WordPressErrorType.UNKNOWN, error_3);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Obtém tags com base em opções de filtro
* @param options Opções de consulta
* @returns Lista de tags
*/
TaxonomyService.prototype.getTags = function (options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var endpoint, params, results, error_4;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
endpoint = this.getTaxonomyEndpoint('post_tag');
params = this.getQueryParams(options);
return [4 /*yield*/, this.client.get(endpoint, params)];
case 1:
results = _a.sent();
return [2 /*return*/, results];
case 2:
error_4 = _a.sent();
if (error_4 instanceof ErrorUtils_1.WordPressError) {
throw error_4;
}
throw new ErrorUtils_1.WordPressError('Erro ao obter tags', ErrorUtils_1.WordPressErrorType.UNKNOWN, error_4);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Obtém hierarquia de categorias
* @param options Opções de consulta
* @returns Lista de categorias com hierarquia
*/
TaxonomyService.prototype.getCategoryHierarchy = function (options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var categories_1, topLevelCategories, getChildCategories_1, buildHierarchy_1, error_5;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.getCategories(options)];
case 1:
categories_1 = _a.sent();
topLevelCategories = categories_1.filter(function (cat) { return !cat.parent || cat.parent === 0; });
getChildCategories_1 = function (parentId) {
return categories_1.filter(function (cat) {
var catParent = typeof cat.parent === 'number' ? cat.parent : 0;
return catParent === parentId;
});
};
buildHierarchy_1 = function (category) {
var children = getChildCategories_1(category.id);
return __assign(__assign({}, category), { children: children.map(function (child) { return buildHierarchy_1(child); }) });
};
// Construir hierarquia para cada categoria de nível superior
return [2 /*return*/, topLevelCategories.map(function (cat) { return buildHierarchy_1(cat); })];
case 2:
error_5 = _a.sent();
if (error_5 instanceof ErrorUtils_1.WordPressError) {
throw error_5;
}
throw new ErrorUtils_1.WordPressError('Erro ao obter hierarquia de categorias', ErrorUtils_1.WordPressErrorType.UNKNOWN, error_5);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Cria uma categoria
* @param data Dados da categoria
* @returns Categoria criada
*/
TaxonomyService.prototype.createCategory = function (data) {
return __awaiter(this, void 0, void 0, function () {
var endpoint, result, error_6;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
endpoint = this.getTaxonomyEndpoint('category');
return [4 /*yield*/, this.client.post(endpoint, data)];
case 1:
result = _a.sent();
return [2 /*return*/, result];
case 2:
error_6 = _a.sent();
if (error_6 instanceof ErrorUtils_1.WordPressError) {
throw error_6;
}
throw new ErrorUtils_1.WordPressError("Erro ao criar categoria: ".concat(data.name), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_6);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Cria uma tag
* @param data Dados da tag
* @returns Tag criada
*/
TaxonomyService.prototype.createTag = function (data) {
return __awaiter(this, void 0, void 0, function () {
var endpoint, result, error_7;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
endpoint = this.getTaxonomyEndpoint('post_tag');
return [4 /*yield*/, this.client.post(endpoint, data)];
case 1:
result = _a.sent();
return [2 /*return*/, result];
case 2:
error_7 = _a.sent();
if (error_7 instanceof ErrorUtils_1.WordPressError) {
throw error_7;
}
throw new ErrorUtils_1.WordPressError("Erro ao criar tag: ".concat(data.name), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_7);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Atualiza uma categoria
* @param id ID da categoria
* @param data Dados atualizados
* @returns Categoria atualizada
*/
TaxonomyService.prototype.updateCategory = function (id, data) {
return __awaiter(this, void 0, void 0, function () {
var endpoint, result, error_8;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
endpoint = this.getTaxonomyEndpoint('category');
return [4 /*yield*/, this.client.put("".concat(endpoint, "/").concat(id), data)];
case 1:
result = _a.sent();
return [2 /*return*/, result];
case 2:
error_8 = _a.sent();
if (error_8 instanceof ErrorUtils_1.WordPressError) {
throw error_8;
}
throw new ErrorUtils_1.WordPressError("Erro ao atualizar categoria: ".concat(id), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_8);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Atualiza uma tag
* @param id ID da tag
* @param data Dados atualizados
* @returns Tag atualizada
*/
TaxonomyService.prototype.updateTag = function (id, data) {
return __awaiter(this, void 0, void 0, function () {
var endpoint, result, error_9;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
endpoint = this.getTaxonomyEndpoint('post_tag');
return [4 /*yield*/, this.client.put("".concat(endpoint, "/").concat(id), data)];
case 1:
result = _a.sent();
return [2 /*return*/, result];
case 2:
error_9 = _a.sent();
if (error_9 instanceof ErrorUtils_1.WordPressError) {
throw error_9;
}
throw new ErrorUtils_1.WordPressError("Erro ao atualizar tag: ".concat(id), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_9);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Exclui uma categoria
* @param id ID da categoria
* @returns true se excluída com sucesso
*/
TaxonomyService.prototype.deleteCategory = function (id) {
return __awaiter(this, void 0, void 0, function () {
var endpoint, error_10;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
endpoint = this.getTaxonomyEndpoint('category');
return [4 /*yield*/, this.client["delete"]("".concat(endpoint, "/").concat(id))];
case 1:
_a.sent();
return [2 /*return*/, true];
case 2:
error_10 = _a.sent();
if (error_10 instanceof ErrorUtils_1.WordPressError) {
throw error_10;
}
throw new ErrorUtils_1.WordPressError("Erro ao excluir categoria: ".concat(id), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_10);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Exclui uma tag
* @param id ID da tag
* @returns true se excluída com sucesso
*/
TaxonomyService.prototype.deleteTag = function (id) {
return __awaiter(this, void 0, void 0, function () {
var endpoint, error_11;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
endpoint = this.getTaxonomyEndpoint('post_tag');
return [4 /*yield*/, this.client["delete"]("".concat(endpoint, "/").concat(id))];
case 1:
_a.sent();
return [2 /*return*/, true];
case 2:
error_11 = _a.sent();
if (error_11 instanceof ErrorUtils_1.WordPressError) {
throw error_11;
}
throw new ErrorUtils_1.WordPressError("Erro ao excluir tag: ".concat(id), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_11);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Garante que uma categoria existe (cria se não existir)
* @param name Nome da categoria
* @param parent ID da categoria pai (opcional)
* @returns Categoria existente ou nova
*/
TaxonomyService.prototype.ensureCategory = function (name, parent) {
return __awaiter(this, void 0, void 0, function () {
var existingCategory, data, error_12;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
return [4 /*yield*/, this.getCategory(name)];
case 1:
existingCategory = _a.sent();
if (existingCategory) {
return [2 /*return*/, existingCategory];
}
data = { name: name };
if (parent) {
data.parent = parent;
}
return [4 /*yield*/, this.createCategory(data)];
case 2: return [2 /*return*/, _a.sent()];
case 3:
error_12 = _a.sent();
if (error_12 instanceof ErrorUtils_1.WordPressError) {
throw error_12;
}
throw new ErrorUtils_1.WordPressError("Erro ao garantir exist\u00EAncia da categoria: ".concat(name), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_12);
case 4: return [2 /*return*/];
}
});
});
};
/**
* Garante que uma tag existe (cria se não existir)
* @param name Nome da tag
* @returns Tag existente ou nova
*/
TaxonomyService.prototype.ensureTag = function (name) {
return __awaiter(this, void 0, void 0, function () {
var existingTag, data, error_13;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
return [4 /*yield*/, this.getTag(name)];
case 1:
existingTag = _a.sent();
if (existingTag) {
return [2 /*return*/, existingTag];
}
data = { name: name };
return [4 /*yield*/, this.createTag(data)];
case 2: return [2 /*return*/, _a.sent()];
case 3:
error_13 = _a.sent();
if (error_13 instanceof ErrorUtils_1.WordPressError) {
throw error_13;
}
throw new ErrorUtils_1.WordPressError("Erro ao garantir exist\u00EAncia da tag: ".concat(name), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_13);
case 4: return [2 /*return*/];
}
});
});
};
/**
* Garante que múltiplas categorias existam
* @param names Nomes das categorias
* @returns Categorias existentes ou novas
*/
TaxonomyService.prototype.ensureCategories = function (names) {
return __awaiter(this, void 0, void 0, function () {
var promises, error_14;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
promises = names.map(function (name) { return _this.ensureCategory(name); });
return [4 /*yield*/, Promise.all(promises)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
error_14 = _a.sent();
if (error_14 instanceof ErrorUtils_1.WordPressError) {
throw error_14;
}
throw new ErrorUtils_1.WordPressError("Erro ao garantir exist\u00EAncia de m\u00FAltiplas categorias", ErrorUtils_1.WordPressErrorType.UNKNOWN, error_14);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Garante que múltiplas tags existam
* @param names Nomes das tags
* @returns Tags existentes ou novas
*/
TaxonomyService.prototype.ensureTags = function (names) {
return __awaiter(this, void 0, void 0, function () {
var promises, error_15;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
promises = names.map(function (name) { return _this.ensureTag(name); });
return [4 /*yield*/, Promise.all(promises)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
error_15 = _a.sent();
if (error_15 instanceof ErrorUtils_1.WordPressError) {
throw error_15;
}
throw new ErrorUtils_1.WordPressError("Erro ao garantir exist\u00EAncia de m\u00FAltiplas tags", ErrorUtils_1.WordPressErrorType.UNKNOWN, error_15);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Gera um slug a partir do nome da taxonomia
* @param name Nome da taxonomia
* @returns Slug gerado
*/
TaxonomyService.prototype.generateSlug = function (name) {
if (!name) {
return '';
}
// Converter para minúsculas
var slug = name.toLowerCase();
// Remover acentos
slug = slug.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
// Substituir espaços por hífens
slug = slug.replace(/\s+/g, '-');
// Remover caracteres especiais e manter apenas alfanuméricos e hífens
slug = slug.replace(/[^a-z0-9-]/g, '');
// Remover hífens duplicados
slug = slug.replace(/-+/g, '-');
// Remover hífens do início e fim
slug = slug.replace(/^-|-$/g, '');
return slug;
};
/**
* Associa categorias e tags a um post
* @param postId ID do post
* @param categories Nomes ou slugs das categorias
* @param tags Nomes ou slugs das tags
* @returns Post atualizado
*/
TaxonomyService.prototype.associateTaxonomiesWithPost = function (postId, categories, tags) {
if (categories === void 0) { categories = []; }
if (tags === void 0) { tags = []; }
return __awaiter(this, void 0, void 0, function () {
var endpoint, post, error_16, categoryIds, categoryResults, tagIds, tagResults, data, updatedPost, error_17;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 10, , 11]);
endpoint = 'wp/v2/posts';
post = void 0;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.client.get("".concat(endpoint, "/").concat(postId))];
case 2:
post = _a.sent();
return [3 /*break*/, 4];
case 3:
error_16 = _a.sent();
throw new ErrorUtils_1.WordPressError("Post n\u00E3o encontrado: ".concat(postId), ErrorUtils_1.WordPressErrorType.NOT_FOUND, error_16);
case 4:
categoryIds = [];
if (!(categories.length > 0)) return [3 /*break*/, 6];
return [4 /*yield*/, this.ensureCategories(categories.map(String))];
case 5:
categoryResults = _a.sent();
categoryIds = categoryResults.map(function (cat) { return cat.id; });
_a.label = 6;
case 6:
tagIds = [];
if (!(tags.length > 0)) return [3 /*break*/, 8];
return [4 /*yield*/, this.ensureTags(tags.map(String))];
case 7:
tagResults = _a.sent();
tagIds = tagResults.map(function (tag) { return tag.id; });
_a.label = 8;
case 8:
data = {};
if (categoryIds.length > 0) {
data.categories = categoryIds;
}
if (tagIds.length > 0) {
data.tags = tagIds;
}
// Se não há taxonomias para associar, retornar o post atual
if (Object.keys(data).length === 0) {
return [2 /*return*/, post];
}
return [4 /*yield*/, this.client.put("".concat(endpoint, "/").concat(postId), data)];
case 9:
updatedPost = _a.sent();
return [2 /*return*/, updatedPost];
case 10:
error_17 = _a.sent();
if (error_17 instanceof ErrorUtils_1.WordPressError) {
throw error_17;
}
throw new ErrorUtils_1.WordPressError("Erro ao associar taxonomias ao post: ".concat(postId), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_17);
case 11: return [2 /*return*/];
}
});
});
};
/**
* Associa categorias e tags a uma página
* @param pageId ID da página
* @param categories Nomes ou slugs das categorias
* @param tags Nomes ou slugs das tags
* @returns Página atualizada
*/
TaxonomyService.prototype.associateTaxonomiesWithPage = function (pageId, categories, tags) {
if (categories === void 0) { categories = []; }
if (tags === void 0) { tags = []; }
return __awaiter(this, void 0, void 0, function () {
var endpoint, page, error_18, data, categoryResults, categoryIds, error_19, tagResults, tagIds, error_20, updatedPage, error_21;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 14, , 15]);
endpoint = 'wp/v2/pages';
page = void 0;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.client.get("".concat(endpoint, "/").concat(pageId))];
case 2:
page = _a.sent();
return [3 /*break*/, 4];
case 3:
error_18 = _a.sent();
throw new ErrorUtils_1.WordPressError("P\u00E1gina n\u00E3o encontrada: ".concat(pageId), ErrorUtils_1.WordPressErrorType.NOT_FOUND, error_18);
case 4:
data = {};
if (!(categories.length > 0)) return [3 /*break*/, 8];
_a.label = 5;
case 5:
_a.trys.push([5, 7, , 8]);
return [4 /*yield*/, this.ensureCategories(categories.map(String))];
case 6:
categoryResults = _a.sent();
categoryIds = categoryResults.map(function (cat) { return cat.id; });
data.categories = categoryIds;
return [3 /*break*/, 8];
case 7:
error_19 = _a.sent();
// Ignorar erros - nem todas as instalações suportam categorias em páginas
console.warn('Aviso: Esta instalação WordPress pode não suportar categorias em páginas');
return [3 /*break*/, 8];
case 8:
if (!(tags.length > 0)) return [3 /*break*/, 12];
_a.label = 9;
case 9:
_a.trys.push([9, 11, , 12]);
return [4 /*yield*/, this.ensureTags(tags.map(String))];
case 10:
tagResults = _a.sent();
tagIds = tagResults.map(function (tag) { return tag.id; });
data.tags = tagIds;
return [3 /*break*/, 12];
case 11:
error_20 = _a.sent();
// Ignorar erros - nem todas as instalações suportam tags em páginas
console.warn('Aviso: Esta instalação WordPress pode não suportar tags em páginas');
return [3 /*break*/, 12];
case 12:
// Se não há taxonomias para associar, retornar a página atual
if (Object.keys(data).length === 0) {
return [2 /*return*/, page];
}
return [4 /*yield*/, this.client.put("".concat(endpoint, "/").concat(pageId), data)];
case 13:
updatedPage = _a.sent();
return [2 /*return*/, updatedPage];
case 14:
error_21 = _a.sent();
if (error_21 instanceof ErrorUtils_1.WordPressError) {
throw error_21;
}
throw new ErrorUtils_1.WordPressError("Erro ao associar taxonomias \u00E0 p\u00E1gina: ".concat(pageId), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_21);
case 15: return [2 /*return*/];
}
});
});
};
/**
* Obtém subcategorias de uma categoria específica
* @param parentId ID da categoria pai
* @param options Opções de consulta
* @returns Lista de subcategorias
*/
TaxonomyService.prototype.getSubcategories = function (parentId, options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var queryOptions, error_22;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
queryOptions = __assign(__assign({}, options), { parent: parentId });
return [4 /*yield*/, this.getCategories(queryOptions)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
error_22 = _a.sent();
if (error_22 instanceof ErrorUtils_1.WordPressError) {
throw error_22;
}
throw new ErrorUtils_1.WordPressError("Erro ao obter subcategorias de: ".concat(parentId), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_22);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Obtém o caminho completo da hierarquia de uma categoria
* @param categoryId ID da categoria
* @returns Lista de categorias do topo até a categoria especificada
*/
TaxonomyService.prototype.getCategoryPath = function (categoryId) {
return __awaiter(this, void 0, void 0, function () {
var category, path, parentPath, error_23;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 4, , 5]);
return [4 /*yield*/, this.getCategory(categoryId)];
case 1:
category = _a.sent();
if (!category) {
throw new ErrorUtils_1.WordPressError("Categoria n\u00E3o encontrada: ".concat(categoryId), ErrorUtils_1.WordPressErrorType.NOT_FOUND);
}
path = [category];
if (!(category.parent && category.parent > 0)) return [3 /*break*/, 3];
return [4 /*yield*/, this.getCategoryPath(category.parent)];
case 2:
parentPath = _a.sent();
return [2 /*return*/, __spreadArray(__spreadArray([], parentPath, true), [category], false)];
case 3: return [2 /*return*/, path];
case 4:
error_23 = _a.sent();
if (error_23 instanceof ErrorUtils_1.WordPressError) {
throw error_23;
}
throw new ErrorUtils_1.WordPressError("Erro ao obter caminho da categoria: ".concat(categoryId), ErrorUtils_1.WordPressErrorType.UNKNOWN, error_23);
case 5: return [2 /*return*/];
}
});
});
};
/**
* Obtém todas as categorias e organiza em uma estrutura hierárquica de árvore
* @param options Opções de consulta
* @returns Árvore de categorias
*/
TaxonomyService.prototype.getCategoryTree = function (options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var hierarchicalCategories, buildTree_1, error_24;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.getCategoryHierarchy(options)];
case 1:
hierarchicalCategories = _a.sent();
buildTree_1 = function (categories) {
return categories.map(function (category) {
var node = {
id: category.id,
name: category.name,
slug: category.slug,
description: category.description || '',
count: category.count || 0
};
if (category.children && category.children.length > 0) {
node.children = buildTree_1(category.children);
}
else {
node.children = [];
}
return node;
});
};
return [2 /*return*/, {
count: hierarchicalCategories.length,
items: buildTree_1(hierarchicalCategories)
}];
case 2:
error_24 = _a.sent();
if (error_24 instanceof ErrorUtils_1.WordPressError) {
throw error_24;
}
throw new ErrorUtils_1.WordPressError('Erro ao obter árvore de categorias', ErrorUtils_1.WordPressErrorType.UNKNOWN, error_24);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Obtém estatísticas sobre taxonomias
* @returns Estatísticas de taxonomias
*/
TaxonomyService.prototype.getTaxonomyStats = function () {
return __awaiter(this, void 0, void 0, function () {
var categories, totalCategories, topLevelCategories, tags, totalTags, error_25;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 4, , 5]);
return [4 /*yield*/, this.getCategories({
perPage: 1,
page: 1
})];
case 1:
categories = _a.sent();
totalCategories = parseInt(this.client.getLastResponseHeader('X-WP-Total') || '0');
return [4 /*yield*/, this.getCategories({
parent: 0
})];
case 2:
topLevelCategories = _a.sent();
return [4 /*yield*/, this.getTags({
perPage: 1,
page: 1
})];
case 3:
tags = _a.sent();
totalTags = parseInt(this.client.getLastResponseHeader('X-WP-Total') || '0');
return [2 /*return*/, {
categories: {
total: totalCategories,
topLevel: topLevelCategories.length
},
tags: {
total: totalTags
}
}];
case 4:
error_25 = _a.sent();
if (error_25 instanceof ErrorUtils_1.WordPressError) {
throw error_25;
}
throw new ErrorUtils_1.WordPressError('Erro ao obter estatísticas de taxonomias', ErrorUtils_1.WordPressErrorType.UNKNOWN, error_25);
case 5: return [2 /*return*/];
}
});
});
};
return TaxonomyService;
}());
exports.TaxonomyService = TaxonomyService;