0

When I try to carry out a transaction on firestore, it throws me an error Unexpected token admin on the below code

exports.issueBook = functions.https.onCall(async(data, context) => {
    if (!(context.auth && context.auth.token.admin)) {
        throw new functions.https.HttpsError(
            'unauthenticated',
            'only authenticated Admins can Issue Books'
        );
    }

    memberData = {
        name: data.issueData.memberName,
        no: data.issueData.memberNo,
        role: data.issueData.memberRole,
    }
    transactionData = {
        books: data.issueData.books,
        creation: new Date(),
        member: memberData,
    }

    var keys = Object.keys(transactionData.books);
    var date = new Date();
    transactionData.books["takenDate"] = date;
    date.setDate(date.getDate() + 7);
    var dueDate = date;
    if (transactionData.memberRole == "student") {
        transactionData.books["dueDate"] = dueDate;
    }

    const membeRef = admin.firestore().collection('users').doc(transactionData.member.no);
    var memberDoc = await membeRef.get();
    if (!memberDoc.exists) {
        try {
            await memberRef.set({
                name: data.issueData.memberName,
                no: data.issueData.memberNo,
                email: data.issueData.memberEmail,
                role: data.issueData.memberRole,
                created: data.issueData.created,
                totalBooks: 5,
            })
        } catch (error) {
            console.log(error);
            throw new functions.https.HttpsError(
                'unknown',
                'New user cannot be created at the moment due to some unknown reasons. Please try again'
            );
        }
    } else {
        if (memberDoc.data().role == 'student' && keys.length > memberDoc.data().totalBooks) {
            throw new functions.https.HttpsError(
                'failed-precondition',
                'Student cannot have more than 5 Books'
            );
        }
    }

    var transactionBooks = [];

    try {
        keys.forEach(docNo => {
            book = await admin.firestore().collection('books').where("no", "==", docNo).limit(1);
            transactionBooks.push(book);
        })
    } catch (error) {
        console.log(error);
        throw new functions.https.HttpsError(
            'unknown',
            'Book Data cannot be read at the moment. Please try again'
        );
    }

    return admin.firestore().runTransaction(transaction => {
            return transaction.get(memberRef).then(doc => {
                var transactionRef = admin.firestore().collection('transactions').doc();
                var transId = '';
                // write Transaction
                transaction.set(transactionRef, transactionData)
                    .then(() => { transId = transactionRef.id })
                    .catch(error => {
                        console.log(error);
                        throw new functions.https.HttpsError(
                            'unknown',
                            'New user cannot be created at the moment due to some unknown reasons. Please try again'
                        )
                    })

                transaction.set(memberRef, {
                    transactionId: transId
                }, { merge: true })

                transaction.update(membeRef, {
                    totalBooks: totalBooks - keys.length
                });

                transactionBooks.forEach(transBook => {
                    transaction.update(transBook, {
                        status: false
                    })
                })


            })
        })
        .then(result => {
            console.log(result);
            return { message: 'Issued' };
        })
        .catch(error => {
            console.log(error);
            return error;
        });
});

Here is the Error I got while deploying the CF

=== Deploying to 'library-1be0e'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> functions@ lint /home/abibv/Downloads/Development/PDL Library/Nec-it-Library-PWA/functions
> eslint .


/home/abibv/Downloads/Development/PDL Library/Nec-it-Library-PWA/functions/index.js
  150:26  error  Parsing error: Unexpected token admin

✖ 1 problem (1 error, 0 warnings)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/abibv/.npm/_logs/2020-04-13T02_13_51_548Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code1

Having trouble? Try firebase [command] --help

this is the try block which throws the error

try {
        keys.forEach(docNo => {
            book = await admin.firestore().collection('books').where("no", "==", docNo).limit(1);
            transactionBooks.push(book);
        })
    } catch (error) {
        console.log(error);
        throw new functions.https.HttpsError(
            'unknown',
            'Book Data cannot be read at the moment. Please try again'
        );
    }

What is the reason for this Error? Thanks in Advance.

Jerry_0x04bc
  • 41
  • 1
  • 10

1 Answers1

1

You are trying to use await inside a function that is not declared async. The function is the anonymous function/lambda that you're passing to forEach. The async on the outer function doesn't matter at all here. async/await doesn't work with nested lambda functions.

Consider some ideas on how to work with async/await in forEach loops: Using async/await with a forEach loop

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thank's. That solved my problem. But now, I've got another issue, `/home/abibv/Downloads/Development/PDL Library/Nec-it-Library-PWA/functions/index.js 166:21 error Each then() should return a value or throw promise/always-return ✖ 1 problem (1 error, 0 warnings)` – Jerry_0x04bc Apr 13 '20 at 02:58
  • If you have a new problem, please post it separately and explain what's now not working the way you expect. – Doug Stevenson Apr 13 '20 at 03:14
  • On Stack Overflow, if you find an answer to be helpful, it's customary to accept it as correct by clicking the checkbox to the left of the answer, so the person giving the answer can get credit for it. – Doug Stevenson Apr 13 '20 at 03:35
  • 1
    I'm a newbie here. Thanks for the advice. – Jerry_0x04bc Apr 13 '20 at 03:37