Implemented Forum

This commit is contained in:
Torsten Schulz
2024-10-24 11:22:40 +02:00
parent 663564aa96
commit f74a16e58e
8 changed files with 270 additions and 3 deletions

View File

@@ -196,6 +196,103 @@ class ForumService extends BaseService {
return this.getForum(hashedUserId, forumId, 1);
}
async getTopic(hashedUserId, topicId) {
console.log('[ForumService.getTopic] - start');
const user = await User.findOne({
where: {
hashedId: hashedUserId
}
});
if (!user) {
throw new Error('User not found.');
}
const topic = await Title.findByPk(topicId, {
include: [
{
model: Message,
as:'messages',
include: [
{
model: User,
as: 'lastMessageUser',
attributes: ['hashedId', 'username'],
order: [['createdAt', 'ASC']]
}
]
},
{
model: User,
as: 'createdByUser',
attributes: ['username', 'hashedId']
},
{
model: Forum,
as: 'forum',
attributes: ['id', 'name']
}
]
});
if (!topic) {
throw new Error('Topic not found.');
}
console.log('[ForumService.getTopic] - check user permissions');
const hasAccess = await this.checkForumAccess(topic.forum, user);
if (!hasAccess) {
throw new Error('Access denied.');
}
console.log('[ForumService.getTopic] - return topic');
return topic;
}
async addMessage(hashedUserId, topicId, content) {
console.log('[ForumService.addMessage] - start');
const user = await User.findOne({
where: {
hashedId: hashedUserId
}
});
if (!user) {
throw new Error('User not found.');
}
const topic = await Title.findByPk(topicId, {
include: [
{
model: Message,
as:'messages',
include: [
{
model: User,
as: 'lastMessageUser',
attributes: ['hashedId', 'username'],
order: [['createdAt', 'ASC']]
}
]
},
{
model: User,
as: 'createdByUser',
attributes: ['username', 'hashedId']
},
{
model: Forum,
as: 'forum',
attributes: ['id', 'name']
}
]
});
if (!topic) {
throw new Error('Topic not found.');
}
const hasAccess = await this.checkForumAccess(topic.forum, user);
if (!hasAccess) {
throw new Error('Access denied.');
}
console.log('[ForumService.addMessage] - create new message');
await Message.create({ titleId: topicId, text: content, createdBy: user.id });
console.log('[ForumService.addMessage] - return topic');
return this.getTopic(hashedUserId, topicId);
}
async checkForumAccess(forum, user) {
console.log('[ForumService.checkForumAccess] - start');
const { age } = user;