Files
doneit-web/src/app/module/chat/data/data-source/message/message-local-data-source.service.ts
T

263 lines
6.2 KiB
TypeScript
Raw Normal View History

2024-06-05 10:28:38 +01:00
import { Injectable } from '@angular/core';
import { Dexie, EntityTable, liveQuery } from 'Dexie';
2024-07-18 16:19:30 +01:00
import { err, ok, Result } from 'neverthrow';
2024-06-05 10:28:38 +01:00
import { z } from 'zod';
2024-08-06 16:53:13 +01:00
import { from, Observable, Subject } from 'rxjs';
2024-08-06 12:01:59 +01:00
import { filter } from 'rxjs/operators';
2024-06-05 10:28:38 +01:00
import { MessageInputDTO } from '../../dto/message/messageInputDtO';
2024-08-06 12:01:59 +01:00
import { MessageEntity } from '../../../domain/entity/message';
2024-08-07 16:31:31 +01:00
import { DexieRepository } from 'src/app/infra/repository/dexie/dexie-repository.service';
2024-06-05 10:28:38 +01:00
const tableSchema = z.object({
$id: z.number().optional(),
2024-08-06 11:24:00 +01:00
id: z.string().optional(),
2024-06-05 10:28:38 +01:00
roomId: z.string().uuid(),
2024-07-16 14:15:58 +01:00
message: z.string(),
messageType: z.number(),
canEdit: z.boolean(),
oneShot: z.boolean(),
sentAt: z.string().optional(),
requireUnlock: z.boolean(),
sender: z.object({
wxUserId: z.number(),
wxFullName: z.string(),
wxeMail: z.string(),
userPhoto: z.string(),
}),
2024-08-06 16:53:13 +01:00
sending: z.boolean().optional(),
reaction: z.object({
id: z.string(),
reactedAt: z.string(),
reaction: z.string(),
sender: z.object({}),
}).array()
2024-07-16 14:15:58 +01:00
})
export const IncomingMessageSchema = z.object({
messageId: z.string().optional(),
roomId: z.string().uuid(),
2024-06-05 10:28:38 +01:00
message: z.string(),
messageType: z.number(),
canEdit: z.boolean(),
oneShot: z.boolean(),
2024-06-14 09:30:14 +01:00
sentAt: z.string().optional(),
2024-06-05 10:28:38 +01:00
requireUnlock: z.boolean(),
2024-06-05 15:35:38 +01:00
sender: z.object({
wxUserId: z.number(),
wxFullName: z.string(),
wxeMail: z.string(),
2024-06-11 08:37:52 +01:00
userPhoto: z.string(),
}),
sending: z.boolean().optional()
2024-06-05 10:28:38 +01:00
})
2024-06-11 08:37:52 +01:00
2024-06-05 10:28:38 +01:00
export type TableMessage = z.infer<typeof tableSchema>
// Database declaration (move this to its own module also)
export const messageDataSource = new Dexie('chat-message') as Dexie & {
2024-08-06 11:24:00 +01:00
message: EntityTable<TableMessage, '$id'>;
2024-06-05 10:28:38 +01:00
};
messageDataSource.version(1).stores({
2024-08-06 11:24:00 +01:00
message: '++$id, id, roomId, message, messageType, canEdit, oneShot, requireUnlock, messageId, info'
2024-06-05 10:28:38 +01:00
});
2024-08-06 12:01:59 +01:00
messageDataSource.message.mapToClass(MessageEntity);
2024-06-05 10:28:38 +01:00
@Injectable({
providedIn: 'root'
})
2024-08-07 16:31:31 +01:00
export class MessageLocalDataSourceService extends DexieRepository<TableMessage> {
2024-06-05 10:28:38 +01:00
2024-06-13 12:11:17 +01:00
messageSubject = new Subject();
2024-06-05 10:28:38 +01:00
2024-06-13 12:11:17 +01:00
constructor() {
2024-08-07 16:31:31 +01:00
super(messageDataSource.message)
2024-08-06 16:53:13 +01:00
// messageDataSource.message.hook('creating', (primKey, obj, trans) => {
// // const newMessage = await trans.table('message').get(primKey);
// this.messageSubject.next(obj);
// // return newMessage
// })
2024-06-13 12:11:17 +01:00
}
2024-06-05 10:28:38 +01:00
async setAllSenderToFalse() {
try {
await messageDataSource.transaction('rw', messageDataSource.message, async () => {
// Perform the update operation within the transaction
await messageDataSource.message.toCollection().modify({ sending: false });
});
console.log('All messages updated successfully.');
} catch (error) {
console.error('Error updating messages:', error);
}
}
2024-06-05 10:28:38 +01:00
2024-07-18 16:19:30 +01:00
async getLastMessageByRoomId(roomId: string): Promise<Result<undefined|TableMessage, any>> {
try {
2024-07-25 08:51:04 +01:00
console.log({roomId})
2024-07-18 16:19:30 +01:00
const lastMessage = await messageDataSource.message
.where('roomId')
.equals(roomId)
.reverse()
.sortBy('id');
return ok(lastMessage[0]); // Get the last message
} catch (error) {
return err(error);
}
}
2024-08-06 11:24:00 +01:00
async deleteByMessageId(id: string): Promise<Result<undefined|TableMessage, any>> {
2024-07-31 17:23:44 +01:00
try {
2024-08-06 11:24:00 +01:00
console.log(id)
2024-07-31 17:23:44 +01:00
const lastMessage = await messageDataSource.message
2024-08-06 11:24:00 +01:00
.where('id')
.equals(id).delete()
2024-07-31 17:23:44 +01:00
return ok(lastMessage[0]); // Get the last message
} catch (error) {
return err(error);
}
}
2024-07-18 16:19:30 +01:00
2024-06-11 08:37:52 +01:00
async sendMessage(data: MessageInputDTO) {
(data as TableMessage).sending = true
try {
const result = await messageDataSource.message.add(data)
2024-08-06 16:53:13 +01:00
this.messageSubject.next({roomId: data.roomId});
return ok(result as number)
2024-06-11 08:37:52 +01:00
} catch (e) {
return err(false)
}
}
2024-07-11 12:12:43 +01:00
incomingSocketMessage() {
}
2024-07-25 08:51:04 +01:00
// @ValidateSchema(tableSchema)
2024-06-05 10:28:38 +01:00
async createMessage(data: MessageInputDTO) {
try {
const result = await messageDataSource.message.add(data)
2024-08-06 16:53:13 +01:00
this.messageSubject.next({roomId: data.roomId});
return ok(result)
2024-06-05 14:31:26 +01:00
} catch (e) {
return err(false)
}
}
2024-08-07 16:31:31 +01:00
async createManyMessage(data: MessageInputDTO[]) {
try {
const result = await messageDataSource.message.bulkAdd(data)
this.messageSubject.next({roomId: data[0].roomId});
return ok(result)
} catch (e) {
return err(false)
}
}
2024-06-05 14:31:26 +01:00
2024-08-06 11:24:00 +01:00
async messageExist({id}) {
2024-07-31 17:23:44 +01:00
try {
2024-08-01 16:38:08 +01:00
2024-08-06 11:24:00 +01:00
console.log({id});
2024-08-01 16:38:08 +01:00
2024-07-31 17:23:44 +01:00
const existingMessage = await messageDataSource.message
2024-08-06 11:24:00 +01:00
.where('id')
.equals(id)
2024-07-31 17:23:44 +01:00
.first();
if (existingMessage) {
2024-08-01 16:38:08 +01:00
return ok(existingMessage)
2024-07-31 17:23:44 +01:00
} else {
return err(false)
}
} catch (error) {
return err(false);
}
}
// not used
2024-08-01 16:38:08 +01:00
async updateByMessageId(data: TableMessage ) {
try {
const result = await messageDataSource.message.update(data.id as any, data)
2024-06-05 10:28:38 +01:00
return ok(result)
} catch (e) {
return err(false)
}
}
2024-06-05 15:35:38 +01:00
async findOrUpdate(data: TableMessage) {
2024-08-06 11:24:00 +01:00
const findResult = await this.findMessageById(data.id)
2024-06-05 15:35:38 +01:00
if(findResult.isOk()) {
2024-08-07 16:31:31 +01:00
return this.update(findResult.value.$id, data)
2024-06-05 15:35:38 +01:00
} else {
return this.createMessage(data)
}
}
2024-08-06 16:53:13 +01:00
getItems(roomId: string) {
return messageDataSource.message.where('roomId').equals(roomId).toArray()
}
2024-06-14 09:30:14 +01:00
getItemsLive(roomId: string) {
2024-08-06 16:53:13 +01:00
return liveQuery(() => messageDataSource.message.where('roomId').equals(roomId).sortBy('$id'))
2024-06-05 10:28:38 +01:00
}
2024-08-06 11:24:00 +01:00
async findMessageById(id: string) {
2024-06-05 15:35:38 +01:00
try {
2024-08-06 11:24:00 +01:00
const a = await messageDataSource.message.where('id').equals(id).first()
2024-06-05 15:35:38 +01:00
if(a) {
return ok(a)
} else {
return err('not found')
}
} catch (e) {
return err('DB error')
}
}
2024-06-05 10:28:38 +01:00
2024-06-13 12:11:17 +01:00
subscribeToNewMessage(roomId: string): Observable<TableMessage> {
return this.messageSubject.pipe(
filter((message: TableMessage) =>
message.roomId === roomId
)
)
}
2024-08-07 15:23:23 +01:00
async getOfflineMessages () {
try {
const allMessages = await messageDataSource.message
.filter(msg => typeof msg.id !== 'string' && msg.sending == false)
.toArray();
return allMessages as MessageEntity[];
} catch (error) {
console.error('Error fetching messages:', error);
}
}
2024-06-05 10:28:38 +01:00
}