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

131 lines
4.0 KiB
TypeScript
Raw Normal View History

2024-06-05 10:28:38 +01:00
import { Injectable } from '@angular/core';
2024-08-13 10:52:35 +01:00
import { liveQuery } from 'Dexie';
2024-08-26 14:47:03 +01:00
import { MessageEntity } from '../../../../../core/chat/entity/message';
2024-08-07 16:31:31 +01:00
import { DexieRepository } from 'src/app/infra/repository/dexie/dexie-repository.service';
2024-10-29 16:00:19 +01:00
import { PromiseExtended } from 'Dexie';
2024-09-05 11:45:54 +01:00
import { DexieMessageTable, MessageTable, MessageTableSchema } from 'src/app/infra/database/dexie/instance/chat/schema/message';
2024-10-07 13:27:49 +01:00
import { chatDatabase } from 'src/app/infra/database/dexie/instance/chat/service';
2024-09-17 16:02:12 +01:00
import { IDirectMessages, IMessageLocalRepository } from 'src/app/core/chat/repository/message/message-local-repository';
2024-10-29 16:00:19 +01:00
import { combineLatest, from, Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';
2024-09-04 22:48:29 +01:00
import { v4 as uuidv4 } from 'uuid'
2024-09-17 16:02:12 +01:00
import { err, ok } from 'neverthrow';
2024-06-05 10:28:38 +01:00
@Injectable({
providedIn: 'root'
})
2024-09-05 11:45:54 +01:00
export class MessageLocalDataSourceService extends DexieRepository<MessageTable, MessageEntity, DexieMessageTable> implements IMessageLocalRepository {
2024-06-05 10:28:38 +01:00
2024-10-10 11:08:32 +01:00
private creatingSubject : Subject<MessageTable> = new Subject<MessageTable>();
2024-09-04 22:48:29 +01:00
private lastTimestamp = 0;
2024-06-05 10:28:38 +01:00
2024-06-13 12:11:17 +01:00
constructor() {
2024-09-05 11:45:54 +01:00
super(chatDatabase.message, MessageTableSchema, chatDatabase)
2024-08-15 10:26:20 +01:00
this.setAllSenderToFalse();
2024-09-02 15:27:07 +01:00
this.onCreatingHook()
2024-06-13 12:11:17 +01:00
}
2024-06-05 10:28:38 +01:00
2024-09-02 12:33:43 +01:00
private onCreatingHook() {
chatDatabase.message.hook('creating', (primaryKey, obj, transaction) => {
2024-09-04 22:48:29 +01:00
let now = Date.now();
// If the current time is the same as the last, increment
if (now <= this.lastTimestamp) {
obj.$createAt = this.lastTimestamp + 1;
this.lastTimestamp = this.lastTimestamp + 1;
} else {
this.lastTimestamp = now;
obj.$createAt = now;
}
if(obj.id) {
obj.$id = obj.id
} else {
obj.$id = 'Local-'+uuidv4()
}
2024-09-02 15:27:07 +01:00
this.creatingSubject.next(obj)
2024-09-02 12:33:43 +01:00
});
}
2024-09-02 15:27:07 +01:00
onCreateObservable() {
return this.creatingSubject.asObservable()
}
2024-09-02 12:33:43 +01:00
async setAllSenderToFalse() {
2024-09-05 11:45:54 +01:00
// this.createTransaction(async (table) => {
// const result = await this.find({sending: true })
// if(result.isOk()) {
// for(const message of result.value) {
// await this.update(message.$id, { sending: false })
// }
// }
// })
try {
2024-08-07 19:30:20 +01:00
await chatDatabase.transaction('rw', chatDatabase.message, async () => {
// Perform the update operation within the transaction
2024-08-07 19:30:20 +01:00
await chatDatabase.message.toCollection().modify({ sending: false });
});
2024-09-05 11:45:54 +01:00
// console.log('All messages updated successfully.');
} catch (error) {
console.error('Error updating messages:', error);
}
}
2024-06-05 10:28:38 +01:00
2024-08-13 10:52:35 +01:00
getItems(roomId: string): PromiseExtended<MessageEntity[]> {
2024-09-12 14:50:10 +01:00
return chatDatabase.message.where('roomId').equals(roomId).sortBy('sentAt') as any
2024-08-06 16:53:13 +01:00
}
2024-06-05 10:28:38 +01:00
2024-08-07 15:23:23 +01:00
async getOfflineMessages () {
try {
2024-08-07 19:30:20 +01:00
const allMessages = await chatDatabase.message
2024-08-07 15:23:23 +01:00
.filter(msg => typeof msg.id !== 'string' && msg.sending == false)
.toArray();
return allMessages as MessageEntity[];
} catch (error) {
console.error('Error fetching messages:', error);
}
}
2024-09-01 12:57:33 +01:00
getLastMessageForRooms(roomIds: string[]): Observable<any[]> {
const observables = roomIds.map(roomId =>
from (liveQuery(async() =>{
const messages = await chatDatabase.message
.where('roomId')
.equals(roomId)
.reverse()
.sortBy('timestamp')
return messages[0] || null; // Return the first item (latest message) or null if no message
})).pipe(
map((message) => ({ roomId, message: message || null })) // Attach roomId to the result
)
);
return combineLatest(observables); // Combine all observables into one array of results
}
2024-09-17 16:02:12 +01:00
async getDirectMessages(input: IDirectMessages) {
try {
const result = await chatDatabase.message
.where('receiverId')
.equals(input.receiverId)
.or('roomId')
.equals(input.roomId)
.toArray()
return ok(result as MessageEntity[])
} catch (e) {
return err(e)
}
}
2024-06-05 10:28:38 +01:00
}