/** * chat-message service */ import { factories } from '@strapi/strapi'; export default factories.createCoreService( 'api::chat-message.chat-message', ({ strapi }) => ({ async createMessageInConversation( conversationId: number, senderId: number, content: string, mediaId?: number ) { if (!conversationId) { throw new Error('Conversation ID is required'); } if (!senderId) { throw new Error('Sender ID is required'); } if (!content || content.trim() === '') { throw new Error('Message content is required and cannot be empty'); } const conversation = await strapi.db .query('api::chat-conversation.chat-conversation') .findOne({ where: { id: conversationId }, }); if (!conversation) { throw new Error(`Conversation with ID ${conversationId} not found`); } const member = await strapi.db .query('api::chat-conversation-member.chat-conversation-member') .findOne({ where: { user: { id: senderId }, conversation: { id: conversationId }, }, }); if (!member) { throw new Error( 'User is not a member of this conversation' ); } if (mediaId) { const media = await strapi.db .query('plugin::upload.file') .findOne({ where: { id: mediaId }, }); if (!media) { throw new Error(`Media with ID ${mediaId} not found`); } } const messageData: any = { sender: senderId, content: content.trim(), isEdited: false, }; if (mediaId) { messageData.media = mediaId; } const message = await strapi.db .query('api::chat-message.chat-message') .create({ data: messageData, }); await strapi.db .query('api::chat-conversation.chat-conversation') .update({ where: { id: conversationId }, data: { messages: { connect: [{ id: message.id }], }, }, }); return message; }, }) );