Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
export class DeviceDetailComponent {
constructor(private route: ActivatedRoute, private deviceService: DeviceService) { }
device$ = this.route.params.pipe(this.deviceService.toDevice);
deviceState$ = this.device$.pipe(this.deviceService.toDeviceState);
deviceMeasurements$ = this.device$.pipe(this.deviceService.toMeasurements);
trackMeasurement = (id, rec) => (`${rec.timestamp.seconds}${rec.timestamp.nanoseconds}`);
}
import {Injectable} from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable, combineLatest } from 'rxjs';
import { switchMap, withLatestFrom, map, tap } from 'rxjs/operators';
export interface Device {
id: string;
firstName: string;
lastName: string;
displayName?: string;
}
export interface MeasurementDoc {
timestamp: {
seconds: number;
nanoseconds: number;
};
temperature: number;
bpm: number;
}
export interface DeviceState {
state$: Observable<MeasurementDoc>;
}
export const DEVICES_PATH = 'devices';
@Injectable({
providedIn: 'root'
})
export class DeviceService {
constructor(private af: AngularFirestore) { }
devices$ = this.af.collection<Device>('devices')
.valueChanges();
latestMeasurement = deviceId => this.af
.collection<MeasurementDoc>(
`devices/${deviceId}/measurements`,
ref => ref.orderBy('timestamp', 'desc').limit(1)
)
.valueChanges()
.pipe(
map(([latestReading]) => latestReading)
)
getMeasurements = (deviceId, queryFn?) => this.af.collection(
`devices/${deviceId}/measurements`,
queryFn ? queryFn : ref => ref.orderBy('timestamp', 'desc').limit(500)
).valueChanges()
getDeviceDoc = deviceId => this.af
.doc<Device>(`devices/${deviceId}`)
.valueChanges()
getDeviceState = deviceId => this.latestMeasurement(deviceId);
toDeviceState = (idStream: Observable<{id: string}>) => idStream
.pipe(switchMap(({id}) => this.getDeviceState(id)))
toDevice = (idStream: Observable<{id: string}>): Observable<Device> => idStream
.pipe(switchMap(({id}) => this.getDeviceDoc(id)))
toMeasurements = (queryStream: Observable<{id: string}>) => queryStream
.pipe(switchMap(({id}) => this.getMeasurements(id)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment