From e2cf4851bdbdc5ad551728f9e6a3f742f4fb848b Mon Sep 17 00:00:00 2001 From: Nick Van Doorn Date: Mon, 4 Mar 2019 01:57:09 -0800 Subject: Inject naive service & use directory --- .../angular-chat/src/app/messaging.service.ts | 47 ++++++++++++---------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/sample-apps/angular-chat/src/app/messaging.service.ts b/sample-apps/angular-chat/src/app/messaging.service.ts index 6c76ca8..40e2728 100644 --- a/sample-apps/angular-chat/src/app/messaging.service.ts +++ b/sample-apps/angular-chat/src/app/messaging.service.ts @@ -1,45 +1,48 @@ import { Injectable } from '@angular/core' -import { Observable } from 'rxjs' - -// TODO use npm/yarn -import { dbFactory, DatabaseConnection } from 'naive-client' +import { Observable, pipe } from 'rxjs' +import { map, tap } from 'rxjs/operators' +import { NaiveService } from './naive.service' import { ChatMessage } from './chat-message.model' -const wsUrl = 'ws://localhost:5001' -const httpUrl = 'http://localhost:5000' - @Injectable({ providedIn: 'root' }) export class MessagingService { - private db: DatabaseConnection - constructor() { - this.db = dbFactory({ wsUrl, httpUrl }) - } + constructor(private db: NaiveService) {} init() { return this.db.init() } - async makeChatRoom(userId: string): Promise { - const chatRoomId = Date.now().toString() - await this.db.write(`/chatRooms/${chatRoomId}`, { - user: 'admin', - message: `Oh no she better don't` - }) + async makeChatRoom(): Promise { + const chatRoomId = `chatRoom-${Date.now().toString()}` + await this.pushToDirectory(chatRoomId) + await this.pushToChatRoom('admin', chatRoomId, 'oh hey') return chatRoomId } + // TODO this is broken because of how path matching + // is implemented + getDirectory(): Observable { + return this.db.toObservable(`/directory`).pipe(map(Object.keys)) + } + getChatRoom(chatRoomId: string): Observable { - return Observable.create(observer => { - this.db.subscribe(`/chatRooms/${chatRoomId}`, data => { - observer.next(Object.values(data)) - }) - }) + return this.db + .toObservable(`/chatRooms/${chatRoomId}`) + .pipe(map(Object.values)) } sendMessage(userId: string, chatRoomId: string, message: string) { + return this.pushToChatRoom(userId, chatRoomId, message) + } + + private pushToDirectory(chatRoomId: string) { + return this.db.write(`/directory/${chatRoomId}`, { created: Date.now() }) + } + + private pushToChatRoom(userId: string, chatRoomId: string, message: string) { return this.db.write(`/chatRooms/${chatRoomId}`, { [Date.now().toString()]: { user: userId, -- cgit v1.2.3