Files
harmony-back/src/api/chat-message/services/chat-message.ts
julien vdb 0bb06e0e2d
All checks were successful
Build release Docker image / Build Docker Images (push) Successful in 7m23s
0.12.18 : add create message, conversation
2026-01-16 13:23:27 +01:00

96 lines
2.2 KiB
TypeScript

/**
* 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;
},
})
);