Files
evig/cms-api/dist/controllers/contentController.js
T
Your Name 148d91a1b7 Update Dockerfile and TypeScript definitions; enhance health check and user role management
- Added curl to Dockerfile for health check improvements.
- Modified npm install commands to build TypeScript and prune unnecessary packages.
- Updated health check command to use curl for better reliability.
- Adjusted TypeScript definitions for user-related functions to return more specific response types.
- Changed user role options from 'viewer' to 'user' in multiple places for consistency.
- Updated package.json dependencies, including downgrading jsonwebtoken types and switching bcrypt to bcryptjs for compatibility.
- Added new environment variables for email configuration in the env.template file.
- Cleaned up various files by removing unnecessary newlines and ensuring consistent formatting.
2025-12-16 16:11:35 +01:00

720 lines
29 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteCategory = exports.updateCategory = exports.createCategory = exports.getCategory = exports.getCategories = exports.deleteBlogPost = exports.updateBlogPost = exports.createBlogPost = exports.getBlogPost = exports.getBlogPosts = exports.deleteStaticPage = exports.updateStaticPage = exports.createStaticPage = exports.getStaticPage = exports.getStaticPages = void 0;
const express_validator_1 = require("express-validator");
const database_1 = require("../utils/database");
exports.getStaticPages = [
(0, express_validator_1.query)('page').optional().isInt({ min: 1 }),
(0, express_validator_1.query)('limit').optional().isInt({ min: 1, max: 100 }),
(0, express_validator_1.query)('search').optional().trim(),
(0, express_validator_1.query)('is_published').optional().isBoolean(),
async (req, res) => {
try {
const errors = (0, express_validator_1.validationResult)(req);
if (!errors.isEmpty()) {
res.status(400).json({
success: false,
error: 'Validation failed',
details: errors.array(),
});
return;
}
const { page = 1, limit = 10, search = '', is_published } = req.query;
const offset = (page - 1) * limit;
let whereClause = '1=1';
const params = [];
let paramIndex = 1;
if (search) {
whereClause += ` AND (title ILIKE $${paramIndex} OR content ILIKE $${paramIndex + 1})`;
params.push(`%${search}%`, `%${search}%`);
paramIndex += 2;
}
if (is_published !== undefined) {
whereClause += ` AND is_published = $${paramIndex}`;
params.push(is_published);
paramIndex++;
}
const countResult = await (0, database_1.executeQuerySingle)(`SELECT COUNT(*) as count FROM static_pages WHERE ${whereClause}`, params);
if (!countResult) {
res.status(500).json({
success: false,
error: 'Database error: Unable to count pages'
});
return;
}
const pages = await (0, database_1.executeQuery)(`SELECT * FROM static_pages
WHERE ${whereClause}
ORDER BY updated_at DESC
LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [...params, limit, offset]);
const response = {
data: pages,
pagination: {
page,
limit,
total: countResult.count,
total_pages: Math.ceil(countResult.count / limit),
has_next: page * limit < countResult.count,
has_prev: page > 1,
},
};
res.json({
success: true,
data: response,
});
}
catch (error) {
console.error('Get static pages error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
},
];
const getStaticPage = async (req, res) => {
try {
const { slug } = req.params;
const page = await (0, database_1.executeQuerySingle)('SELECT * FROM static_pages WHERE slug = $1', [slug]);
if (!page) {
res.status(404).json({
success: false,
error: 'Static page not found',
});
return;
}
res.json({
success: true,
data: page,
});
}
catch (error) {
console.error('Get static page error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
};
exports.getStaticPage = getStaticPage;
exports.createStaticPage = [
(0, express_validator_1.body)('slug').trim().isLength({ min: 1, max: 255 }).matches(/^[a-z0-9-]+$/),
(0, express_validator_1.body)('title').trim().isLength({ min: 1, max: 500 }),
(0, express_validator_1.body)('content').trim().isLength({ min: 1 }),
(0, express_validator_1.body)('seo_title').optional().trim().isLength({ max: 500 }),
(0, express_validator_1.body)('seo_description').optional().trim(),
(0, express_validator_1.body)('meta_keywords').optional().trim(),
(0, express_validator_1.body)('is_published').optional().isBoolean(),
async (req, res) => {
try {
const errors = (0, express_validator_1.validationResult)(req);
if (!errors.isEmpty()) {
res.status(400).json({
success: false,
error: 'Validation failed',
details: errors.array(),
});
return;
}
const { slug, title, content, seo_title, seo_description, meta_keywords, is_published = false } = req.body;
if (!req.user) {
res.status(401).json({ success: false, error: 'Unauthorized' });
return;
}
const userId = req.user.id;
const existingPage = await (0, database_1.executeQuerySingle)('SELECT id FROM static_pages WHERE slug = $1', [slug]);
if (existingPage) {
res.status(409).json({
success: false,
error: 'Slug already exists',
});
return;
}
const newPage = await (0, database_1.executeQuerySingle)(`INSERT INTO static_pages (slug, title, content, seo_title, seo_description, meta_keywords, is_published, created_by, updated_by)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8)
RETURNING *`, [slug, title, content, seo_title, seo_description, meta_keywords, is_published, userId]);
res.status(201).json({
success: true,
message: 'Static page created successfully',
data: newPage,
});
}
catch (error) {
console.error('Create static page error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
},
];
exports.updateStaticPage = [
(0, express_validator_1.body)('slug').optional().trim().isLength({ min: 1, max: 255 }).matches(/^[a-z0-9-]+$/),
(0, express_validator_1.body)('title').optional().trim().isLength({ min: 1, max: 500 }),
(0, express_validator_1.body)('content').optional().trim().isLength({ min: 1 }),
(0, express_validator_1.body)('seo_title').optional().trim().isLength({ max: 500 }),
(0, express_validator_1.body)('seo_description').optional().trim(),
(0, express_validator_1.body)('meta_keywords').optional().trim(),
(0, express_validator_1.body)('is_published').optional().isBoolean(),
async (req, res) => {
try {
const errors = (0, express_validator_1.validationResult)(req);
if (!errors.isEmpty()) {
res.status(400).json({
success: false,
error: 'Validation failed',
details: errors.array(),
});
return;
}
const { id } = req.params;
const { slug, title, content, seo_title, seo_description, meta_keywords, is_published } = req.body;
if (!req.user) {
res.status(401).json({ success: false, error: 'Unauthorized' });
return;
}
const userId = req.user.id;
if (slug) {
const existingPage = await (0, database_1.executeQuerySingle)('SELECT id FROM static_pages WHERE slug = $1 AND id != $2', [slug, id]);
if (existingPage) {
res.status(409).json({
success: false,
error: 'Slug already exists',
});
return;
}
}
const updatedPage = await (0, database_1.executeQuerySingle)(`UPDATE static_pages
SET slug = COALESCE($1, slug),
title = COALESCE($2, title),
content = COALESCE($3, content),
seo_title = COALESCE($4, seo_title),
seo_description = COALESCE($5, seo_description),
meta_keywords = COALESCE($6, meta_keywords),
is_published = COALESCE($7, is_published),
updated_by = $8,
updated_at = CURRENT_TIMESTAMP
WHERE id = $9
RETURNING *`, [slug, title, content, seo_title, seo_description, meta_keywords, is_published, userId, id]);
if (!updatedPage) {
res.status(404).json({
success: false,
error: 'Static page not found',
});
return;
}
res.json({
success: true,
message: 'Static page updated successfully',
data: updatedPage,
});
}
catch (error) {
console.error('Update static page error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
},
];
const deleteStaticPage = async (req, res) => {
try {
const { id } = req.params;
const deletedPage = await (0, database_1.executeQuerySingle)('DELETE FROM static_pages WHERE id = $1 RETURNING *', [id]);
if (!deletedPage) {
res.status(404).json({
success: false,
error: 'Static page not found',
});
return;
}
res.json({
success: true,
message: 'Static page deleted successfully',
});
}
catch (error) {
console.error('Delete static page error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
};
exports.deleteStaticPage = deleteStaticPage;
exports.getBlogPosts = [
(0, express_validator_1.query)('page').optional().isInt({ min: 1 }),
(0, express_validator_1.query)('limit').optional().isInt({ min: 1, max: 100 }),
(0, express_validator_1.query)('search').optional().trim(),
(0, express_validator_1.query)('category_id').optional().isUUID(),
(0, express_validator_1.query)('is_published').optional().isBoolean(),
async (req, res) => {
try {
const errors = (0, express_validator_1.validationResult)(req);
if (!errors.isEmpty()) {
res.status(400).json({
success: false,
error: 'Validation failed',
details: errors.array(),
});
return;
}
const { page = 1, limit = 10, search = '', category_id, is_published } = req.query;
const offset = (page - 1) * limit;
let whereClause = '1=1';
const params = [];
let paramIndex = 1;
if (search) {
whereClause += ` AND (title ILIKE $${paramIndex} OR content ILIKE $${paramIndex + 1} OR excerpt ILIKE $${paramIndex + 2})`;
params.push(`%${search}%`, `%${search}%`, `%${search}%`);
paramIndex += 3;
}
if (category_id) {
whereClause += ` AND category_id = $${paramIndex}`;
params.push(category_id);
paramIndex++;
}
if (is_published !== undefined) {
whereClause += ` AND is_published = $${paramIndex}`;
params.push(is_published);
paramIndex++;
}
const countResult = await (0, database_1.executeQuerySingle)(`SELECT COUNT(*) as count FROM blog_posts WHERE ${whereClause}`, params);
if (!countResult) {
res.status(500).json({
success: false,
error: 'Database error: Unable to count blog posts'
});
return;
}
const posts = await (0, database_1.executeQuery)(`SELECT bp.*, c.name as category_name, c.slug as category_slug
FROM blog_posts bp
LEFT JOIN categories c ON bp.category_id = c.id
WHERE ${whereClause}
ORDER BY bp.published_at DESC NULLS LAST, bp.updated_at DESC
LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [...params, limit, offset]);
const response = {
data: posts,
pagination: {
page,
limit,
total: countResult.count,
total_pages: Math.ceil(countResult.count / limit),
has_next: page * limit < countResult.count,
has_prev: page > 1,
},
};
res.json({
success: true,
data: response,
});
}
catch (error) {
console.error('Get blog posts error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
},
];
const getBlogPost = async (req, res) => {
try {
const { slug } = req.params;
const post = await (0, database_1.executeQuerySingle)(`SELECT bp.*, c.name as category_name, c.slug as category_slug
FROM blog_posts bp
LEFT JOIN categories c ON bp.category_id = c.id
WHERE bp.slug = $1`, [slug]);
if (!post) {
res.status(404).json({
success: false,
error: 'Blog post not found',
});
return;
}
res.json({
success: true,
data: post,
});
}
catch (error) {
console.error('Get blog post error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
};
exports.getBlogPost = getBlogPost;
exports.createBlogPost = [
(0, express_validator_1.body)('slug').trim().isLength({ min: 1, max: 255 }).matches(/^[a-z0-9-]+$/),
(0, express_validator_1.body)('title').trim().isLength({ min: 1, max: 500 }),
(0, express_validator_1.body)('content').trim().isLength({ min: 1 }),
(0, express_validator_1.body)('excerpt').optional().trim(),
(0, express_validator_1.body)('featured_image').optional().trim(),
(0, express_validator_1.body)('seo_title').optional().trim().isLength({ max: 500 }),
(0, express_validator_1.body)('seo_description').optional().trim(),
(0, express_validator_1.body)('meta_keywords').optional().trim(),
(0, express_validator_1.body)('category_id').optional().isUUID(),
(0, express_validator_1.body)('tags').optional().isArray(),
(0, express_validator_1.body)('is_published').optional().isBoolean(),
async (req, res) => {
try {
const errors = (0, express_validator_1.validationResult)(req);
if (!errors.isEmpty()) {
res.status(400).json({
success: false,
error: 'Validation failed',
details: errors.array(),
});
return;
}
const { slug, title, content, excerpt, featured_image, seo_title, seo_description, meta_keywords, category_id, tags = [], is_published = false } = req.body;
if (!req.user) {
res.status(401).json({ success: false, error: 'Unauthorized' });
return;
}
const userId = req.user.id;
const existingPost = await (0, database_1.executeQuerySingle)('SELECT id FROM blog_posts WHERE slug = $1', [slug]);
if (existingPost) {
res.status(409).json({
success: false,
error: 'Slug already exists',
});
return;
}
if (category_id) {
const category = await (0, database_1.executeQuerySingle)('SELECT id FROM categories WHERE id = $1 AND is_active = true', [category_id]);
if (!category) {
res.status(400).json({
success: false,
error: 'Invalid category',
});
return;
}
}
const publishedAt = is_published ? new Date() : null;
const newPost = await (0, database_1.executeQuerySingle)(`INSERT INTO blog_posts (slug, title, content, excerpt, featured_image, seo_title, seo_description, meta_keywords, category_id, tags, is_published, published_at, created_by, updated_by)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $13)
RETURNING *`, [slug, title, content, excerpt, featured_image, seo_title, seo_description, meta_keywords, category_id, tags, is_published, publishedAt, userId]);
res.status(201).json({
success: true,
message: 'Blog post created successfully',
data: newPost,
});
}
catch (error) {
console.error('Create blog post error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
},
];
exports.updateBlogPost = [
(0, express_validator_1.body)('slug').optional().trim().isLength({ min: 1, max: 255 }).matches(/^[a-z0-9-]+$/),
(0, express_validator_1.body)('title').optional().trim().isLength({ min: 1, max: 500 }),
(0, express_validator_1.body)('content').optional().trim().isLength({ min: 1 }),
(0, express_validator_1.body)('excerpt').optional().trim(),
(0, express_validator_1.body)('featured_image').optional().trim(),
(0, express_validator_1.body)('seo_title').optional().trim().isLength({ max: 500 }),
(0, express_validator_1.body)('seo_description').optional().trim(),
(0, express_validator_1.body)('meta_keywords').optional().trim(),
(0, express_validator_1.body)('category_id').optional().isUUID(),
(0, express_validator_1.body)('tags').optional().isArray(),
(0, express_validator_1.body)('is_published').optional().isBoolean(),
async (req, res) => {
try {
const errors = (0, express_validator_1.validationResult)(req);
if (!errors.isEmpty()) {
res.status(400).json({
success: false,
error: 'Validation failed',
details: errors.array(),
});
return;
}
const { id } = req.params;
const { slug, title, content, excerpt, featured_image, seo_title, seo_description, meta_keywords, category_id, tags, is_published } = req.body;
if (!req.user) {
res.status(401).json({ success: false, error: 'Unauthorized' });
return;
}
const userId = req.user.id;
if (slug) {
const existingPost = await (0, database_1.executeQuerySingle)('SELECT id FROM blog_posts WHERE slug = $1 AND id != $2', [slug, id]);
if (existingPost) {
res.status(409).json({
success: false,
error: 'Slug already exists',
});
return;
}
}
if (category_id) {
const category = await (0, database_1.executeQuerySingle)('SELECT id FROM categories WHERE id = $1 AND is_active = true', [category_id]);
if (!category) {
res.status(400).json({
success: false,
error: 'Invalid category',
});
return;
}
}
const publishedAt = is_published !== undefined && is_published ? new Date() : undefined;
const updatedPost = await (0, database_1.executeQuerySingle)(`UPDATE blog_posts
SET slug = COALESCE($1, slug),
title = COALESCE($2, title),
content = COALESCE($3, content),
excerpt = COALESCE($4, excerpt),
featured_image = COALESCE($5, featured_image),
seo_title = COALESCE($6, seo_title),
seo_description = COALESCE($7, seo_description),
meta_keywords = COALESCE($8, meta_keywords),
category_id = COALESCE($9, category_id),
tags = COALESCE($10, tags),
is_published = COALESCE($11, is_published),
published_at = COALESCE($12, published_at),
updated_by = $13,
updated_at = CURRENT_TIMESTAMP
WHERE id = $14
RETURNING *`, [slug, title, content, excerpt, featured_image, seo_title, seo_description, meta_keywords, category_id, tags, is_published, publishedAt, userId, id]);
if (!updatedPost) {
res.status(404).json({
success: false,
error: 'Blog post not found',
});
return;
}
res.json({
success: true,
message: 'Blog post updated successfully',
data: updatedPost,
});
}
catch (error) {
console.error('Update blog post error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
},
];
const deleteBlogPost = async (req, res) => {
try {
const { id } = req.params;
const deletedPost = await (0, database_1.executeQuerySingle)('DELETE FROM blog_posts WHERE id = $1 RETURNING *', [id]);
if (!deletedPost) {
res.status(404).json({
success: false,
error: 'Blog post not found',
});
return;
}
res.json({
success: true,
message: 'Blog post deleted successfully',
});
}
catch (error) {
console.error('Delete blog post error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
};
exports.deleteBlogPost = deleteBlogPost;
const getCategories = async (req, res) => {
try {
const categories = await (0, database_1.executeQuery)('SELECT * FROM categories WHERE is_active = true ORDER BY name');
res.json({
success: true,
data: categories,
});
}
catch (error) {
console.error('Get categories error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
};
exports.getCategories = getCategories;
const getCategory = async (req, res) => {
try {
const { slug } = req.params;
const category = await (0, database_1.executeQuerySingle)('SELECT * FROM categories WHERE slug = $1 AND is_active = true', [slug]);
if (!category) {
res.status(404).json({
success: false,
error: 'Category not found',
});
return;
}
res.json({
success: true,
data: category,
});
}
catch (error) {
console.error('Get category error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
};
exports.getCategory = getCategory;
exports.createCategory = [
(0, express_validator_1.body)('slug').trim().isLength({ min: 1, max: 255 }).matches(/^[a-z0-9-]+$/),
(0, express_validator_1.body)('name').trim().isLength({ min: 1, max: 255 }),
(0, express_validator_1.body)('description').optional().trim(),
(0, express_validator_1.body)('color').optional().matches(/^#[0-9A-F]{6}$/i),
async (req, res) => {
try {
const errors = (0, express_validator_1.validationResult)(req);
if (!errors.isEmpty()) {
res.status(400).json({
success: false,
error: 'Validation failed',
details: errors.array(),
});
return;
}
const { slug, name, description, color = '#6B7280' } = req.body;
if (!req.user) {
res.status(401).json({ success: false, error: 'Unauthorized' });
return;
}
const userId = req.user.id;
const existingCategory = await (0, database_1.executeQuerySingle)('SELECT id FROM categories WHERE slug = $1', [slug]);
if (existingCategory) {
res.status(409).json({
success: false,
error: 'Slug already exists',
});
return;
}
const newCategory = await (0, database_1.executeQuerySingle)(`INSERT INTO categories (slug, name, description, color, created_by, updated_by)
VALUES ($1, $2, $3, $4, $5, $5)
RETURNING *`, [slug, name, description, color, userId]);
res.status(201).json({
success: true,
message: 'Category created successfully',
data: newCategory,
});
}
catch (error) {
console.error('Create category error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
},
];
exports.updateCategory = [
(0, express_validator_1.body)('slug').optional().trim().isLength({ min: 1, max: 255 }).matches(/^[a-z0-9-]+$/),
(0, express_validator_1.body)('name').optional().trim().isLength({ min: 1, max: 255 }),
(0, express_validator_1.body)('description').optional().trim(),
(0, express_validator_1.body)('color').optional().matches(/^#[0-9A-F]{6}$/i),
(0, express_validator_1.body)('is_active').optional().isBoolean(),
async (req, res) => {
try {
const errors = (0, express_validator_1.validationResult)(req);
if (!errors.isEmpty()) {
res.status(400).json({
success: false,
error: 'Validation failed',
details: errors.array(),
});
return;
}
const { id } = req.params;
const { slug, name, description, color, is_active } = req.body;
if (!req.user) {
res.status(401).json({ success: false, error: 'Unauthorized' });
return;
}
const userId = req.user.id;
if (slug) {
const existingCategory = await (0, database_1.executeQuerySingle)('SELECT id FROM categories WHERE slug = $1 AND id != $2', [slug, id]);
if (existingCategory) {
res.status(409).json({
success: false,
error: 'Slug already exists',
});
return;
}
}
const updatedCategory = await (0, database_1.executeQuerySingle)(`UPDATE categories
SET slug = COALESCE($1, slug),
name = COALESCE($2, name),
description = COALESCE($3, description),
color = COALESCE($4, color),
is_active = COALESCE($5, is_active),
updated_by = $6,
updated_at = CURRENT_TIMESTAMP
WHERE id = $7
RETURNING *`, [slug, name, description, color, is_active, userId, id]);
if (!updatedCategory) {
res.status(404).json({
success: false,
error: 'Category not found',
});
return;
}
res.json({
success: true,
message: 'Category updated successfully',
data: updatedCategory,
});
}
catch (error) {
console.error('Update category error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
},
];
const deleteCategory = async (req, res) => {
try {
const { id } = req.params;
const postCount = await (0, database_1.executeQuerySingle)('SELECT COUNT(*) as count FROM blog_posts WHERE category_id = $1', [id]);
if (postCount && postCount.count > 0) {
res.status(409).json({
success: false,
error: 'Cannot delete category with associated posts',
message: 'Please reassign or delete the associated posts first',
});
return;
}
const deletedCategory = await (0, database_1.executeQuerySingle)('DELETE FROM categories WHERE id = $1 RETURNING *', [id]);
if (!deletedCategory) {
res.status(404).json({
success: false,
error: 'Category not found',
});
return;
}
res.json({
success: true,
message: 'Category deleted successfully',
});
}
catch (error) {
console.error('Delete category error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
});
}
};
exports.deleteCategory = deleteCategory;
//# sourceMappingURL=contentController.js.map