这是我尝试调用上下文以使用身份验证令牌但显示错误的云函数。
exports.checkCollege = functions.https.onCall((data,context)=>{
if(context.auth.token.moderator !== true){
return{
error:"Request not authorized. User must be a moderator to fulfill the request."
};
}
const email = data.email;
return grantModeratorRole(email).then(()=>{
return {
result: `Request fulfilled! ${email} email is now a moderator!`
}
})
})
正在显示这种类型的错误:
src/index.ts:65:10 - error TS2532: Object is possibly 'undefined'.
65 if(context.auth.token.moderator !== true){
~~~~~~~~~~~~
Found 1 error.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! functions@ build: `tsc`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the functions@ build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
答案 0 :(得分:0)
上下文对象的TypeScript定义是这样的:
/**
* The interface for metadata for the API as passed to the handler.
*/
export interface CallableContext {
/**
* The result of decoding and verifying a Firebase Auth ID token.
*/
auth?: {
uid: string;
token: firebase.auth.DecodedIdToken;
};
/**
* An unverified token for a Firebase Instance ID.
*/
instanceIdToken?: string;
/**
* The raw request handled by the callable.
*/
rawRequest: Request;
}
如您所见,auth
属性使用问号标记为可选。这意味着它可能是不确定的。 TypeScript告诉您,在访问该案例之前需要检查该案例,以避免在运行时出现错误:
if (context.auth) {
if (context.auth.token.moderator) {
// ...
}
}