下面是我的firebase函数:
const admin = require('firebase-admin');
const firebase_tools = require('firebase-tools');
const functions = require('firebase-functions');
admin.initializeApp();
exports.deleteUser = functions
.runWith({
timeoutSeconds: 540,
memory: '2GB'
})
.https.onCall((data, context) => {
const userId = context.auth.uid;
var promises = [];
// DELETE DATA
var paths = ['users/' + userId, 'messages/' + userId, 'chat/' + userId, 'like/' + userId];
paths.forEach((path) => {
promises.push(
recursiveDelete(path).then( () => {
return 'success';
}
).catch( (error) => {
console.log('Error deleting user data: ', error);
})
);
});
// DELETE FILES
const bucket = admin.storage().bucket();
var image_paths = ["avatar/" + userId, "avatar2/" + userId, "avatar3/" + userId];
image_paths.forEach((path) => {
promises.push(
bucket.file(path).delete().then( () => {
return 'success';
}
).catch( (error) => {
console.log('Error deleting user data: ', error);
})
);
});
// DELETE USER
promises.push(
admin.auth().deleteUser(userId)
.then( () => {
console.log('Successfully deleted user');
return true;
})
.catch((error) => {
console.log('Error deleting user:', error);
})
);
return Promise.all(promises).then(() => {
return true;
}).catch(er => {
console.error('...', er);
});
});
function recursiveDelete(path, context) {
return firebase_tools.firestore
.delete(path, {
project: process.env.GCLOUD_PROJECT,
recursive: true,
yes: true,
token: functions.config().fb.token
})
.then(() => {
return {
path: path
}
}).catch( (error) => {
console.log('error: ', error);
return error;
});
}
// [END recursive_delete_function]
调用此函数时,如何传入context.auth.id
?
以下是我尝试过的:
async function deleteAccount(userId) {
const deleteUser = firebase.functions().httpsCallable("deleteUser");
deleteUser({ userId }).then((result) => {
console.log(result.data);
});
}
但我得到以下错误:
Unhandled error TypeError: Cannot read property 'uid' of undefined
我知道context.auth.id
在服务器端可用,但在这种情况下,我需要一种方法来传递它。
您不必在可调用的云函数中传递用户的UID。用户必须使用Firebase身份验证登录,其余由Firebase SDK负责。
在调用云函数之前,您是否可以尝试在deleteAccount
函数中记录当前用户,以确保用户登录?此外,context.auth.uid
是调用函数的用户的UID。如果您想访问在函数中传递的userId,请重构代码,如下所示。
deleteUser()
函数将只接受一个参数,该参数是要在Cloud函数中传递的数据。
// not deleteUser({}, { userId })
deleteUser({ userId }).then((result) => {
console.log(result.data);
});
当您在Cloud函数中显式传递任何数据时,可以从data
而不是context
:访问
const { userId } = data;