Skip to content

Instantly share code, notes, and snippets.

@robwormald
Created July 25, 2018 19:53
Show Gist options
  • Save robwormald/90335741a0ebea8c22b104aeb0730f30 to your computer and use it in GitHub Desktop.
Save robwormald/90335741a0ebea8c22b104aeb0730f30 to your computer and use it in GitHub Desktop.
@Component({
selector: 'app-device-detail',
templateUrl: './device-detail.component.html',
styleUrls: ['./device-detail.component.css']
})
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}`);
}
@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<MeasurementDoc>(
`devices/${deviceId}/measurements`,
queryFn ? queryFn : ref => ref.orderBy('timestamp', 'desc').limit(61)
).valueChanges()
getDeviceDoc = deviceId => this.af
.doc<Device>(`devices/${deviceId}`)
.valueChanges()
getDeviceState = deviceId => this.latestMeasurement(deviceId);
toDeviceState = (idStream: Observable<{deviceId: string}>) => idStream
.pipe(switchMap(({deviceId}) => this.getDeviceState(deviceId)))
toDevice = (idStream: Observable<{id: string}>): Observable<Device> => idStream
.pipe(switchMap(({id}) => this.getDeviceDoc(id)))
toMeasurements = (queryStream: Observable<{deviceId: string}>) => queryStream
.pipe(switchMap(({deviceId}) => this.getMeasurements(deviceId)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment