samedi 25 août 2018

firebase transaction and if-then-else behaviour

I have some changes in my requirements:

Not only Create/Request/Cancel an entire Offer but do some actions on Offer's details:

Here is an offer in the activeOffers list:

activeOffers
    -LKohyZ58cnzn0vCnt9p
        details
            direction: "city"
            seatsCount: 2
            timeToGo: 5
        uid: "-ABSIFJ0vCnt9p8387a"    ---- offering user

A user should be able to 'ask for seats' and if it's successful the Offer record should look like this:

activeOffers
    -LKohyZ58cnzn0vCnt9p
        details
            direction: "city"
            seatsCount: 1   ----- reduced count
            timeToGo: 5
        uid: "-ABSIFJ0vCnt9p8387a"
    deals
        -GHFFJ0vCnt9p8345b   -----   the userId of asking user
            seatsCount: 1
            status: "asked"

But I have 3 problems after executing the source shown below:

(as shown above offer has 2 seats and a user asks for 1 seat)

  1. After execution in my log I have BOTH "Reducing seats count by 1" and "Not enought seats"... i.e: the 'then' and 'else' part of 'if-then-else' :o

  2. function result is [] - i.e. no deal created.

  3. I'm not sure how to do the TODO: part - to add child (the new deal object) under dealsRef using asking userId as KEY because I think I don't need an autogenerated key here.

input data has the following structure:

data
    "uid": "-GHFFJ0vCnt9p8345b",    ----- the userId of asking user
    "id": "-LKohyZ58cnzn0vCnt9p",    ----- the id of offer
    "details":
        "seatsCount": 1

And here is my code:

dealSeats = function(data) {

const TAG = '[dealSeats]: ';

var details = data.details;
var info = data.info;

var entryRef = db.ref('activeOffers/' + data.id);
var entryDetailsRef = entryRef.child('details');
var seatsCountRef = entryDetailsRef.child('seatsCount');

var success = false;
return seatsCountRef.transaction((current)=>{
    var value = current;
    if (value >= details.seatsCount) {
        success = true;
        value = value - details.seatsCount;
        console.log(TAG + 'Reducing seats count by ' + details.seatsCount);
    } else {
        console.log(TAG + 'Not enought seats');
    }
    return value;
})
.then(()=>{
    var deal = [];
    if (success) {
        console.log(TAG + 'Succes');
        deal.seatsCount = details.seatsCount;
        deal.status = 'asked';
    // TODO: here should add the new deal to dealsRef
        return deal;
    } else {
        console.log(TAG + 'Failure');
        return deal;
    }
})

}

Aucun commentaire:

Enregistrer un commentaire