Используете классы в функциях firebase? - PullRequest
1 голос
/ 05 мая 2020

Я пишу код для функции firebase, проблема в том, что мне нужно использовать класс, но когда я вызываю метод класса, журнал функций firebase показывает эту ошибку:

ERROR:

ReferenceError: Proverbi is not defined
at exports.getProverbio.functions.https.onRequest (/srv/index.js:48:26)
at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:49:16)
at /worker/worker.js:783:7
at /worker/worker.js:766:11
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickDomainCallback (internal/process/next_tick.js:219:9)

Вот код "index. js":

//firebase deploy --only functions

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.addStanza = functions.https.onRequest(async (req, res) => {
    // Grab the text parameter.
    const nome = req.query.text;
    // Push the new message into the Realtime Database using the Firebase Admin SDK.
    const snapshot = await admin.database().ref('/stanze').push({giocatori: {giocatore:{nome:nome,punteggio:0}}});
    // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
    //res.redirect(200, nome.toString());
    var link = snapshot.toString().split('/');

    res.json({idStanza:link[4]});
});

// Listens for new messages added to /messages/:pushId/original and creates an
//  uppercase version of the message to /messages/:pushId/uppercase

 exports.addFirstPlayer = functions.database.ref('/stanze/{pushId}/giocatori/giocatore/nome')
.onCreate((snapshot, context) => {
  // Grab the current value of what was written to the Realtime Database.
  const nome = snapshot.val();
 // const snapshot3 = snapshot.ref('/stanza/{pushId}/giocatori/giocatore').remove();
  const snapshot2 =  snapshot.ref.parent.parent.remove();
  return snapshot.ref.parent.parent.push({nome:nome,punteggio:0});
});

exports.addPlayer = functions.https.onRequest(async (req, res) => {
  // Grab the text parameter.
  const nome = req.query.text;
  const idStanza = req.query.id;
  // Push the new message into the Realtime Database using the Firebase Admin SDK.
  const snapshot = await admin.database().ref('/stanz/'+idStanza+"/giocatori").push({nome:nome,punteggio:0 });
  // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
  //res.redirect(200, nome.toString());
  res.json({success:{id:idStanza}});
});

exports.getProverbio = functions.https.onRequest(async (req, res) => {
    const difficolta = req.query.difficolta;
    var proverbioClass = new Proverbi(2);
    var p = proverbioClass.getProverbio();
    var proverbio = p.split('-');
    var inizio = proverbio[0];
    var fine = proverbio[1];

    res.json({proverbio:{inizio:inizio,fine:fine,difficolta:difficolta}});
});

Вот код, вызывающий проблему:

exports.getProverbio = functions.https.onRequest(async (req, res) => {
    const difficolta = req.query.difficolta;
    var proverbioClass = new Proverbi(2);
    var p = proverbioClass.getProverbio();
    var proverbio = p.split('-');
    var inizio = proverbio[0];
    var fine = proverbio[1];

    res.json({proverbio:{inizio:inizio,fine:fine,difficolta:difficolta}});
});

Вот код «Proverbi.class»:

class Proverbi{
    constructor(n) {
        this.magicNumber = n;
    }
    getProverbio() {
        var text = "";
        switch (magicNumber) {
            case 1:
                text += ("Chip");
                text += ("-Chop");
                break; 
        }
        return text;
    }
}

Как я могу использовать класс «Proverbi» внутри «index. js»?

1 Ответ

0 голосов
/ 05 мая 2020

Вам необходимо добавить определение вашего класса Proverbi в файл index.js.

Если вы просто собираетесь использовать этот класс в функции getProverbio Cloud, сделайте следующее:

exports.getProverbio = functions.https.onRequest(async (req, res) => {


    class Proverbi {
        constructor(n) {
            this.magicNumber = n;
        }
        getProverbio() {

            var text = "";
            switch (this.magicNumber) {
                case 1:
                    text += ("Chip");
                    text += ("-Chop");
                    break;
            }
            return text;
        }
    }

    const difficolta = req.query.difficolta;
    var proverbioClass = new Proverbi(2);
    var p = proverbioClass.getProverbio();
    var proverbio = p.split('-');
    var inizio = proverbio[0];
    var fine = proverbio[1];

    res.json({ proverbio: { inizio: inizio, fine: fine, difficolta: difficolta } });
});

Если вы хотите использовать класс в других функциях, просто объявите его следующим образом:

class Proverbi {
    constructor(n) {
        console.log(n);
    }
    getProverbio() {
        console.log(this.magicNumber);
        console.log(this.magicNumber);
        var text = "";
        switch (this.magicNumber) {
            case 1:
                text += ("Chip");
                text += ("-Chop");
                break;
        }
        return text;
    }
}

exports.getProverbio = functions.https.onRequest(async (req, res) => {

    const difficolta = req.query.difficolta;
    var proverbioClass = new Proverbi(2);
    var p = proverbioClass.getProverbio();
    var proverbio = p.split('-');
    var inizio = proverbio[0];
    var fine = proverbio[1];

    res.json({ proverbio: { inizio: inizio, fine: fine, difficolta: difficolta } });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...