简体   繁体   English

如何使用 Typescript 查询 Firebase?

[英]How do I query Firebase using Typescript?

I have push notifications set up for my app using Firebase Cloud Functions.我使用 Firebase Cloud Functions 为我的应用设置了推送通知。 It works well.它运作良好。 Now I want to update the app's badge count as part of the push notification.现在我想更新应用程序的徽章计数作为推送通知的一部分。 I've read that the only way to do that is via server-side code;我已经读过,唯一的方法是通过服务器端代码; I can't do it locally.我本地做不到。

So I'm trying to get the number of new users from the server and then use that number as the badge count when I send the push notification, but I can't figure out how to go about it.所以我试图从服务器获取新用户的数量,然后在发送推送通知时使用该数字作为徽章计数,但我不知道如何去做。 I've spent three days on this and now I'm hoping someone can point me in the right direction.我已经花了三天的时间,现在我希望有人能指出我正确的方向。

I'm using Firebase functions and Typescript (with VSCode).我正在使用 Firebase 函数和 Typescript(使用 VSCode)。 My course of action is to:我的行动方针是:

  1. get list of userIDs from 'admin' node从'admin'节点获取用户ID列表
  2. iterate over those userIDs on 'user' node to query if user's 'newUser' parameter is true遍历“user”节点上的那些用户 ID 以查询用户的“newUser”参数是否为真
  3. append those results to an array将这些结果附加到数组中
  4. count the array and then send that to the badge on push notification计算数组,然后在推送通知时将其发送到徽章

My 'users' database structure is like so:我的“用户”数据库结构是这样的:

"users": {

  "2NBvNgdNRVe3nccTEDts2Xseboma": {

    "email": "someone@someone.com"

    "newUser": "true",

    "referral": "none",

    ...

  },

  "hjC6os6wzIV1FyULmGxalU3fM7ef": {

    "email": "someoneElse@someone.com"

    "newUser": "false",

    "referral": "Bennett",

    ...

  }

And my 'admin' database is structured like so:我的“管理员”数据库的结构如下:

"admin": {

  "2NBvNgdNRVe3nccTEDts2Xseboma": {

    "email": "someone@someone.com"

    "familyName": "Someone",

    "memberSince": "1529119893",

  },

  "hjC6os6wzIV1FyULmGxalU3fM7ef": {

    "email": "someoneElse@someone.com"

    "familyName": "Someone Else",

    "memberSince": "1529125722",

    ...

  }

Here is my feeble attempt to code this:这是我对此编码的微弱尝试:

exports.getNewUserCount =

functions.database.ref('/users/{userID}/newUser')

    .onUpdate((snapshot, _context) => {

        console.log('test 2')

        // Get a database reference

        const db = admin.database();
        const ref = db.ref('admin');


        return ref.once('value', function(adminSnap) {

            const userData = adminSnap.val()

            console.log('admin key:', adminSnap.key)
            console.log('user data:', userData)

        })

    });

Right now I'm stuck on retrieving the list of users from the admin node (my step #1 above).现在我坚持从管理节点检索用户列表(我上面的第 1 步)。

UPDATE更新

I finally got a list of the users as a snapshot, but I can't figure out how to iterate over them.我终于得到了一个用户列表作为快照,但我不知道如何迭代它们。 How do I turn the snapshot into an array of the user keys?如何将快照转换为用户键数组?

And then once I get the list of user keys, then how do I use that to iterate over the 'users' node to get the list of new users (my step #2 above)?然后一旦我获得了用户密钥列表,那么我如何使用它来遍历“用户”节点以获取新用户列表(我上面的第 2 步)?

And then how to put those new users into an array (my step #3 above), and then get the number of new users for the 'badge' parameter when I send my push notification (my step #4 above)?然后如何将这些新用户放入一个数组中(我上面的第 3 步),然后在我发送推送通知(我上面的第 4 步)时获取“徽章”参数的新用户数?

The problem is that this seems really inefficient.问题是这似乎非常低效。 There has to be a better way to simply get a list of new users.必须有更好的方法来简单地获取新用户列表。 There has to be some sort of query I can perform that will go over my 'users' node, see which ones have 'true' for their 'newUser' node, and get a count of those--instead of my roundabout way of getting a list of user from 'admin' node, then using that list to get a list of 'new users' from the 'users' node, then creating an array and then counting that array, then using that number to send to the 'badge' parameter on my push notification.必须有某种我可以执行的查询将遍历我的“用户”节点,查看哪些对他们的“新用户”节点具有“真”,并计算这些节点的数量——而不是我的迂回获取方式来自“admin”节点的用户列表,然后使用该列表从“users”节点获取“新用户”列表,然后创建一个数组,然后对该数组进行计数,然后使用该数字发送到“徽章” ' 我的推送通知上的参数。

Any thoughts?有什么想法吗? I've been at this for days.我已经在这几天了。

If it helps, I know Swift and the app is iOS.如果有帮助,我知道 Swift 并且该应用程序是 iOS。 Thanks!!谢谢!!

UPDATE #2更新 #2

So I opted to try and just get a snapshot of all users and bypass the 'admin' node altogether.所以我选择尝试只获取所有用户的快照并完全绕过“管理”节点。 Here is the code:这是代码:

const db = admin.database();
const ref = db.ref('users');

return ref.once('value').then((adminSnap) => {

    console.log('admin key:', adminSnap.key)

    // create blank array to store 
    let newUserCount = 0;

    // iterate over adminSnap to get each individual snap
    adminSnap.forEach(function (userSnap) {

        const userData = userSnap.val();
        const userKey = userSnap.key

        // console.log('email?', userData.email, 'user key:', userKey, 'new user?', userData.newUser)

        if (userData.newUser === true) {
            newUserCount++
            console.log('new user:', userKey, userData.newUser, userData.email)
        }
    });

    console.log(newUserCount)
})

This new code works and gives me the number for my badge parameter for when I perform my push notification, but I'm wondering if it's the most efficient way to do things.这段新代码有效,并为我提供了执行推送通知时徽章参数的编号,但我想知道这是否是最有效的处理方式。 Plus, as my database grows in size, won't it tax the server / slow way down?另外,随着我​​的数据库规模的增长,它不会对服务器征税/减慢速度吗? And won't it cost me a lot of bandwidth for my Firebase account?难道我的 Firebase 帐户不会花费我很多带宽吗?

I thought this would be a simple thing to do, but it's turning into a bit of a hassle.我以为这会是一件简单的事情,但它变得有点麻烦。 I'm open to a different way to complete this.我愿意以不同的方式来完成这个。 Thanks!谢谢!

After even more research, I ended up abandoning my original approach.经过更多的研究,我最终放弃了我原来的方法。 I decided to just create a new node on my Firebase database with the new user count and then update it via code from elsewhere.我决定使用新的用户数在我的 Firebase 数据库上创建一个新节点,然后通过其他地方的代码更新它。 It's the simplest approach and will use the least amount of bandwidth.这是最简单的方法,将使用最少的带宽。

Here is my final code:这是我的最终代码:

function sendAlertToiPhone() {

console.log('test E')

// Get a database reference
const db = admin.database();
const ref = db.ref('stats');

ref.child('newUserCount').once('value').then((snapshot) => {

    const newUserCount = snapshot.val()

    console.log('new user count:', newUserCount)

    // send to Phontaine's iPhone 6
    const FCMToken = "blahbehtyblahblah"

    const payload = {
        notification: {
            title: 'New User',
            body: 'Moneypants has a new download.',
            sound: 'default',
            badge: String(newUserCount)
        }
    };

    return admin.messaging().sendToDevice(FCMToken, payload)
        .then(function (response) {
            console.log("Successfully sent message:", response);
        })
        .catch(function (error) {
            console.log("Error sending message:", error);
        });

}).catch(function (err) {
    console.log('new user count error:', err);
})
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 NextJs API、Firebase Firestore、axios 和 TypeScript 从 Firebase 集合中获取数据? - How do I get data from Firebase collection using NextJs API, Firebase Firestore, axios and TypeScript? 如何使用查询从 Firebase 9 js 中删除文档? - How do I delete a document from Firebase 9 js using a query? 如何在 firebase 中编写复合查询? - How do I write a compound query in firebase? 如何遍历键数组并以声明方式使用firebase-query对每个键进行查询? - How can I loop through an array of keys and do query for each using firebase-query in a declarative manner? 我如何在打字稿中使用字典查询linq? - How do I linq like query with Dictionary in typescript? 如何使用 firebase 9 push 来实现这一点? - How do I achieve this using firebase 9 push? 如何在云端功能中查询Firebase数据库? - How do I query a firebase database inside a cloud function? 如果文档中不存在该字段,我该如何处理 firebase 查询? - If the field doesnt exist in the document how do i handle the firebase query? 如何通过属性值查询 firebase 个文档的集合? - How do I query a collection of firebase documents by a properties value? 如何使用 Javascript(或打字稿)Firebase Admin SDK 向数据消息添加分析标签? - How do I add an analytics label to data messages with the Javascript (or typescript) Firebase Admin SDK?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM