Firebase 云函数在我使用可调用函数中的'context'时显示错误



这是我尝试调用上下文以使用身份验证令牌的云函数,但它显示错误。

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.

上下文对象的 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) {
// ...
}
}

最新更新