Files
doneit-web/src/app/module/chat/data/repository/message/message-local-data-source.service.ts
T
Peter Maquiran 1b9b4600ab fix chat bold
2024-09-02 12:33:43 +01:00

91 lines
3.0 KiB
TypeScript

import { Injectable } from '@angular/core';
import { liveQuery } from 'Dexie';
import { MessageEntity } from '../../../../../core/chat/entity/message';
import { DexieRepository } from 'src/app/infra/repository/dexie/dexie-repository.service';
import { Observable as DexieObservable, PromiseExtended } from 'Dexie';
import { MessageTable, MessageTableSchema } from 'src/app/infra/database/dexie/instance/chat/schema/message';
import { chatDatabase } from 'src/app/infra/database/dexie/service';
import { IMessageLocalRepository } from 'src/app/core/chat/repository/message/message-local-repository';
import { BehaviorSubject, combineLatest, from, Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class MessageLocalDataSourceService extends DexieRepository<MessageTable, MessageEntity> implements IMessageLocalRepository {
private creatingSubject : BehaviorSubject<MessageTable> = new BehaviorSubject<MessageTable>(null);
constructor() {
super(chatDatabase.message, MessageTableSchema)
this.setAllSenderToFalse();
}
private onCreatingHook() {
chatDatabase.message.hook('creating', (primaryKey, obj, transaction) => {
console.log('A new friend is being added:', obj);
});
}
// onCreateObservable() {
// return this.creatingSubject.asObservable().pipe(
// filter(e => e?.sender?.wxFullName)
// )
// }
async setAllSenderToFalse() {
try {
await chatDatabase.transaction('rw', chatDatabase.message, async () => {
// Perform the update operation within the transaction
await chatDatabase.message.toCollection().modify({ sending: false });
});
} catch (error) {
console.error('Error updating messages:', error);
}
}
getItems(roomId: string): PromiseExtended<MessageEntity[]> {
return chatDatabase.message.where('roomId').equals(roomId).sortBy('$id') as any
}
getItemsLive(roomId: string): DexieObservable<MessageEntity[]> {
return liveQuery(() => chatDatabase.message.where('roomId').equals(roomId).sortBy('$id') as any)
}
async getOfflineMessages () {
try {
const allMessages = await chatDatabase.message
.filter(msg => typeof msg.id !== 'string' && msg.sending == false)
.toArray();
return allMessages as MessageEntity[];
} catch (error) {
console.error('Error fetching messages:', error);
}
}
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
}
}