Get a single document by foreign key in using RxJs

2019-06-05 13:22发布

问题:

I've written a query that looks like this:

getPaymentByBookingId(id: string): Observable<Payment> {
    return this.afs.collection<Payment>('payments', ref => ref.where('bookingId', '==', id).limit(1))
        .valueChanges()
        .pipe(
            flatMap(array => from(array)),
            first()
        );
}

Where a Payment object has a unique reference to a Booking id. I want to find the Payment for a given ID.

This seems like quite a convoluted way to right this query.

Is there a simpler way to do this - including if there is a code smell here that makes this hard?

回答1:

You can do it solely using Javascript native array API .find(), and it will save you a couple lines of code:

getPaymentByBookingId(id: string): Observable<Payment> {
    return this.afs.collection<Payment>('payments')
        .valueChanges()
        .pipe(
            map(allPayments=>allPayments.find(payment=>payment.bookingId === id))
        );
}

Or you can use the .first() operator and supply its first-met condition:

getPaymentByBookingId(id: string): Observable<Payment> {
    return this.afs.collection<Payment>('payments')
        .valueChanges()
        .pipe(
            flatMap(array => from(array)),
            first(eachPayment => eachPayment.bookingId === id)
        );
}

Note that there is a fundamental difference in how the filtering works behind the scene. I personally prefer the Javascript's native function, as I feel it's kinda redundant to transform the observable using from(array) just so that it is emitting the array sequence one by one.

Also note that by doing ref => ref.where('bookingId', '==', id), you filtering actually happens at query level (aka not at client side). If you are confident that the number of payments retrieved won't be big, then it's fine to let the client side do the filtering; else its always better to offload the processing part to the server.



回答2:

A little bit simpler is:

getPaymentByBookingId(id: string): Observable<Payment> {
    return this.afs.collection<Payment>('payments', ref => ref.where('bookingId', '==', id).limit(1))
        .valueChanges()
        .pipe(
            map(array => array[0]),
        );
}

this will returned undefined if the payment is not found.