我有这个功能应该从用户那里获取推荐代码。用户给出一个代码,推荐代码检查它是否存在于数据库中,然后评估是否存在
它与当前用户不匹配,因此不应引用自己和
它与数据库中的代码之一匹配
但是,即使给定的代码在数据库中,此代码也无法找到匹配项。如果推荐代码与当前用户之一匹配,则它可以正常工作并指出即不能推荐自己。
但是,如果推荐代码与推荐系统应该如何工作的另一个用户的代码匹配,它仍然说不匹配。
我怎样才能消除这个错误
export const getID = functions.https.onCall(async(data, context) => {
const db = admin.firestore();
const usersSnapshot = await db.collection("user").get();
const allUIDs = usersSnapshot.docs.map(doc => doc.data().userID);
const userID = context.auth.uid;
const providedID = "cNx7IuY6rZlR9mYSfb1hY7ROFY2";
//db.collection("user").doc(providedID).collection("referrals").doc(userID);
await check();
function check() {
let result;
allUIDs.forEach(idFromDb => {
if (providedID === idFromDb && (idFromDb === userID)) {
result = "ownmatch";
} else if (providedID === idFromDb && (idFromDb !== userID)) {
result = "match";
} else {
result = "nomatch";
}
});
return result;
}
if (check() === "match") {
return {
message: `Match Found`,
};
} else if (check() === "ownmatch") {
return {
message: `Sorry, you can't use your own invite code`,
};
} else {
return {
message: `No User with that ID`
};
}
});
(这不是答案,而是简单的重构。)
这是您的代码当前正在执行的操作(粗略地说,我没有运行它):
const resultMsgs = {
nomatch: 'No User With That ID',
ownmatch: 'Sorry, you can\'t use your own invite code',
match: 'Match Found',
}
function check(uids, providedId, userId) {
let result
uids.forEach(idFromDb => {
if (providedId !== idFromDb) {
result = 'nomatch'
return
}
if (userID === idFromDb) {
result = 'ownmatch'
return
}
result = 'match'
})
return result
}
export const getID = functions
.https
.onCall(async (data, context) => {
const userId = context.auth.uid
const providedId = 'cNx7IuY6rZlR9mYSfb1hY7ROFY2'
const db = admin.firestore()
const user = await db.collection('user').get()
const uids = user.docs.map(doc => doc.data().userId)
const checkResult = check(uids, providedId, userId)
return { message: resultMsgs[checkResult] }
})
(我删除了看似虚假的数据库收集操作。)
您forEach
正在迭代所有uuids
, 但result
将设置为最后一次比较的任何内容。也许这是正确的,但是:
所以:
any
函数。all
函数。map
而不是forEach
,并适当地处理每个结果,无论在您的情况下意味着什么。无论如何,我建议您更干净地分解您的代码。推理和修复会容易得多。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句