Files
doneit-web/src/app/module/chat/data/repository/message/message-local-data-source.service.ts
T
Peter Maquiran 41c63b6c56 remove duplicate
2024-09-01 12:57:33 +01:00

76 lines
2.6 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 { combineLatest, from, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class MessageLocalDataSourceService extends DexieRepository<MessageTable, MessageEntity> implements IMessageLocalRepository {
constructor() {
super(chatDatabase.message, MessageTableSchema)
this.setAllSenderToFalse();
}
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
}
}