Dwelling/homepage/guestbook.js

79 lines
2.2 KiB
JavaScript
Raw Normal View History

2021-02-10 01:01:50 +04:00
const mysql = require("mysql");
const config = require("./config");
const util = require("../shared/util");
2021-02-10 01:01:50 +04:00
let connection = mysql.createConnection(config.database);
2021-02-10 01:01:50 +04:00
connection.config.queryFormat = util.mysqlQueryFormat;
2021-02-10 01:01:50 +04:00
exports.pageSize = config.guestbook.pageSize !== undefined
? config.guestbook.pageSize : 20;
2021-02-10 01:01:50 +04:00
exports.closeConnection = () => connection.end();
exports.getPosts = async (page = 1, page_size = exports.pageSize) => {
return new Promise((resolve, reject) => {
let query = `
SELECT
guestbook.post_id,
guestbook.created,
guestbook.name,
(CASE
WHEN guestbook.hide_email IS false
THEN guestbook.email
ELSE NULL
END) AS email,
(CASE
WHEN guestbook.hide_website IS false
THEN guestbook.website
ELSE NULL
END) AS website,
guestbook.message,
guestbook_feedback.comment AS feedback,
guestbook_feedback.created AS feedback_created
FROM guestbook
LEFT JOIN guestbook_feedback ON guestbook.post_id = guestbook_feedback.post_id
ORDER BY guestbook.created DESC
LIMIT :page_size
OFFSET :page_offset;`;
2021-02-10 01:01:50 +04:00
connection.query(query, { page_size: page_size, page_offset: (page-1) * page_size },
(err, results) => {
if (err) reject(err);
resolve(results); });
});
};
exports.getPostsCount = async () => {
let promise = new Promise((resolve, reject) => {
connection.query("SELECT COUNT(`post_id`) AS total FROM `guestbook`;", (err, results, fields) => {
if (err) reject(err);
resolve(results[0].total); });
});
return promise.then(count => count);
};
exports.addPost = async (post) => {
return new Promise((resolve, reject) => {
let query = "INSERT INTO `guestbook` (`name`, `email`, `website`, `message`, `hide_website`, `hide_email`) \
VALUES (:name, :email, :website, :message, :hide_website, :hide_email);";
if (post.message === undefined || post.message === "")
return reject("empty message");
2021-02-10 01:01:50 +04:00
if (post.name === undefined || post.name === "")
post.name = "Anonymous";
post.message = post.message.trim();
post.message = post.message.replace(/(?:\r\n|\n\r|\r)/g, "\n");
post.message = post.message.replace(/(?:\n\n|\n \n)/g, "\n");
connection.query(query, post, (err, results, fields) => {
if (err) return reject(err);
return resolve(true); });
2021-02-10 01:01:50 +04:00
});
}