@rnaga/wp-node
Version:
👉 **[View Full Documentation at rnaga.github.io/wp-node →](https://rnaga.github.io/wp-node/)**
312 lines (311 loc) • 12.3 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommentTrx = void 0;
const zod_1 = require("zod");
const common_1 = require("../common");
const config_1 = require("../config");
const components_1 = require("../core/components");
const logger_1 = require("../core/logger");
const comment_util_1 = require("../core/utils/comment.util");
const date_time_util_1 = require("../core/utils/date-time.util");
const post_util_1 = require("../core/utils/post.util");
const query_util_1 = require("../core/utils/query.util");
const validator_1 = require("../core/validator");
const database_1 = __importDefault(require("../database"));
const component_1 = require("../decorators/component");
const val = __importStar(require("../validators"));
const meta_trx_1 = require("./meta.trx");
const trx_1 = require("./trx");
let CommentTrx = class CommentTrx extends trx_1.Trx {
database;
logger;
config;
components;
constructor(database, logger, config, components) {
super(components);
this.database = database;
this.logger = logger;
this.config = config;
this.components = components;
}
// wp_insert_comment
async upsert(input) {
const commentUtil = this.components.get(comment_util_1.CommentUtil);
let update = false;
let commentBefore = undefined;
if (input.comment_ID && 0 < input.comment_ID) {
update = true;
commentBefore = await commentUtil.get(input.comment_ID);
if (!commentBefore || !commentBefore.props) {
throw new Error(`Comment not found - ${input.comment_ID}`);
}
input = {
...commentBefore.props,
comment_meta: await commentBefore.meta.props(),
...input,
};
}
const parsedInput = val.trx.commentUpsert.parse(input);
const dateTimeUtil = this.components.get(date_time_util_1.DateTimeUtil);
const dateTime = dateTimeUtil.get();
parsedInput.comment_date = dateTime.mySQLDatetime;
parsedInput.comment_date_gmt = dateTime.mySQLGMTDatetime;
let dataUpsert = {};
const validator = this.components.get(validator_1.Validator);
try {
dataUpsert = validator.execAny(update ? val.trx.commentUpdate : val.trx.commentInsert, Object.entries(parsedInput)
.map(([key, value]) => ({
[key]: common_1.formatting.unslash(value),
}))
.reduce((obj, item) => ({ ...obj, ...item }), {}));
}
catch (e) {
this.logger.info(`parse error: ${e}`, { parsedInput });
throw e;
}
if (!dataUpsert) {
throw new Error(`Invalid post data - ${JSON.stringify(parsedInput)}`);
}
let commentId = parsedInput.comment_ID ?? 0;
const trx = await this.database.transaction;
try {
if (update) {
await trx
.table(this.tables.get("comments"))
.where("comment_ID", parsedInput.comment_ID)
.update(dataUpsert);
}
else {
await trx
.insert(dataUpsert)
.into(this.tables.get("comments"))
.then((v) => {
commentId = v[0];
});
}
}
catch (e) {
await trx.rollback();
throw new Error(`Failed to insert user - ${e}`);
}
await trx.commit();
const comment = await commentUtil.get(commentId);
if (!comment.props?.comment_ID) {
throw new Error(`Comment not found - ${commentId}`);
}
if (parsedInput.comment_meta) {
const metaTrx = this.components.get(meta_trx_1.MetaTrx);
for (const [key, value] of Object.entries(parsedInput.comment_meta)) {
if (!value) {
continue;
}
await metaTrx.upsert("comment", commentId, key, value, {
serialize: typeof value == "object" || Array.isArray(value),
});
}
}
if (comment.props.comment_approved == "1" &&
parsedInput.comment_post_ID > 0) {
await this.updateCount(parsedInput.comment_post_ID);
}
return commentId;
}
async updateCount(postId, forceCount = -1) {
const postUtil = this.components.get(post_util_1.PostUtil);
const post = await postUtil.get(postId);
if (!post.props) {
throw new Error(`Post not found - ${postId}`);
}
const queryUtil = this.components.get(query_util_1.QueryUtil);
const counts = await queryUtil.comments((query) => {
query.countApproved(postId);
}, zod_1.z.array(zod_1.z.object({ count: zod_1.z.number() })));
const count = counts ? counts[0].count : 0;
const trx = await this.database.transaction;
try {
await trx
.table(this.tables.get("posts"))
.where("ID", postId)
.update({
comment_count: forceCount > 0 ? forceCount : count,
});
}
catch (e) {
trx.rollback();
throw new Error(`Failed to update count - ${e}`);
}
await trx.commit();
return true;
}
// wp_delete_comment
async remove(commentId, force = false) {
const EMPTY_TRASH_DAYS = this.config.config.constants.EMPTY_TRASH_DAYS;
const queryUtil = this.components.get(query_util_1.QueryUtil);
const commentUtil = this.components.get(comment_util_1.CommentUtil);
const comment = await queryUtil.comments((query) => {
query.where("ID", commentId).builder.first();
}, val.database.wpComments);
if (!comment) {
return false;
}
const commentStatus = await commentUtil.getStatusAsString(comment.comment_ID);
if (!force &&
EMPTY_TRASH_DAYS &&
typeof commentStatus == "string" &&
["trash", "spam"].includes(commentStatus)) {
return await this.trash(commentId);
}
// Move children up a level.
const children = await queryUtil.comments((query) => {
query.where("parent", commentId);
});
if (children) {
const trx = await this.database.transaction;
try {
await trx
.table(this.tables.get("comments"))
.where("comment_parent", commentId)
.update({
comment_parent: comment.comment_parent,
});
}
catch (e) {
await trx.rollback();
throw new Error(`Failed to update comment parent - ${commentId}`);
}
await trx.commit();
}
// Delete metadata.
const metaTrx = this.components.get(meta_trx_1.MetaTrx);
await metaTrx.removeObject("comment", commentId);
const trx = await this.database.transaction;
try {
await trx
.table(this.tables.get("comments"))
.where("comment_ID", commentId)
.del();
}
catch (e) {
await trx.rollback();
throw new Error(`Failed to delete comment - ${e}`);
}
await trx.commit();
return true;
}
// wp_trash_comment
async trash(commentId) {
const EMPTY_TRASH_DAYS = this.config.config.constants.EMPTY_TRASH_DAYS;
if (!EMPTY_TRASH_DAYS) {
return await this.remove(commentId, true);
}
const queryUtil = this.components.get(query_util_1.QueryUtil);
const comment = await queryUtil.comments((query) => {
query.where("ID", commentId).builder.first();
}, val.database.wpComments);
if (!comment) {
return false;
}
const result = await this.updateStatus(commentId, "trash");
if (!result) {
return false;
}
const metaTrx = this.components.get(meta_trx_1.MetaTrx);
await metaTrx.upsert("comment", commentId, "_wp_trash_meta_status", comment.comment_approved);
await metaTrx.upsert("comment", commentId, "_wp_trash_meta_time", (0, common_1.currentUnixTimestamp)());
return true;
}
// wp_set_comment_status
async updateStatus(commentId, commentStatus) {
const commentUtil = this.components.get(comment_util_1.CommentUtil);
let status = "";
switch (commentStatus) {
case "hold":
case "0":
status = "0";
break;
case "approve":
case "1":
status = "1";
break;
case "spam":
case "trash":
status = commentStatus;
break;
default:
return false;
}
const trx = await this.database.transaction;
try {
await trx
.table(this.tables.get("comments"))
.where("comment_ID", commentId)
.update({
comment_approved: status,
});
}
catch (e) {
await trx.rollback();
throw new Error(`Failed to update comment status - ${e}`);
}
await trx.commit();
const comment = await commentUtil.get(commentId);
if (!comment.props) {
throw new Error(`Comment not found - ${commentId}`);
}
await this.updateCount(comment.props.comment_post_ID);
return true;
}
};
exports.CommentTrx = CommentTrx;
exports.CommentTrx = CommentTrx = __decorate([
(0, component_1.transactions)(),
__metadata("design:paramtypes", [database_1.default,
logger_1.Logger,
config_1.Config,
components_1.Components])
], CommentTrx);