Firebase云功能列表用户拥有1000多个用户

mzaanser  于 2023-01-09  发布在  其他
关注(0)|答案(2)|浏览(111)
exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 20 * * *')
    .timeZone('Asia/Seoul') // Users can choose timezone - default is America/Los_Angeles
    .onRun((context) =>
    {
        var allUsers = [];
        return admin.auth().listUsers()
            .then(function (listUsersResult)
            {
                listUsersResult.users.forEach(function (userRecord)
                {
                    // For each user
                    var userData = userRecord.toJSON();
                    allUsers.push(userData.uid);
                    console.log(allUsers);
                });
                //res.status(200).send(JSON.stringify(allUsers));

            }).then(function ()
            {
                allUsers.forEach(function (elem)
                {
                    db.ref(`Data/${elem}/Enter`).update({ test: 0, test2: 0 });
                });
            })
            .catch(function (error)
            {
                console.log("Error listing users:", error);
                //res.status(500).send(error);
            });

    });

通过listUser()得到uid后,我想修改所有用户的uid为键的数据库值,但是listUser()的最大值为1000,如果有好的方法可以得到所有用户的uid,请告诉我

z0qdvdin

z0qdvdin1#

Firebase Admin SDK支持分页以循环浏览所有注册的用户帐户。请按照文档中的说明操作。您需要使用API循环浏览1000个或更少的批。文档中提供的代码示例说明了这一点:

function listAllUsers(nextPageToken) {
  // List batch of users, 1000 at a time.
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
      listUsersResult.users.forEach(function(userRecord) {
        console.log('user', userRecord.toJSON());
      });
      if (listUsersResult.pageToken) {
        // List next batch of users.
        listAllUsers(listUsersResult.pageToken);
      }
    })
    .catch(function(error) {
      console.log('Error listing users:', error);
    });
}
// Start listing users from the beginning, 1000 at a time.
listAllUsers();
xxhby3vn

xxhby3vn2#

补充前面的正确答案。您也可以使用递归返回所有用户记录(UserRecord[])。

import * as FAdmin  from 'firebase-admin/lib/auth'

export const findUnusedUsers = functions.https.onCall((data, context) => {
  return listAllUsers().then(allUsers => {
     return allUsers
  })
})

const listAllUsers = (nextPageToken?: string, accumulatorUsers: FAdmin.auth.UserRecord[] = []): Promise<FAdmin.auth.UserRecord[]> => {
  return admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
      const users = [...accumulatorUsers, ...listUsersResult.users]
      if (listUsersResult.pageToken) {
        return listAllUsers(listUsersResult.pageToken, users)
      } else {
        return users
      }
    })
}

相关问题