Azure Functions Node.js typescript全局变量

qybjjes1  于 9个月前  发布在  Node.js
关注(0)|答案(1)|浏览(91)

我有一些使用Typescript编码的node.js Azure Functions(httptriggers),我使用jwt token进行保护。在函数开始时验证我的token后,我想全局存储它,以便我可以在所有子函数中使用它。但我希望我的token仅对当前的引用上下文有效。我不想将token作为参数传递给任何可能需要它的函数。
范例:

// I'd like to store it like that, but that isn't thread safe, other user may get the same token
export let globalToken : any;

export async function users(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {

   globalToken = validateToken(request);

   if(request.method === "GET"){
      return { jsonBody: getUsers() };
   }

}

//### In user.service.ts file ###

export const getUsers = () => {

   // so I can use it everywhere like that, without passing it in parameter every time
   return usersData.filter(u => u.userId === globalToken.userId)

}

字符串
有什么建议吗?

wz8daaqr

wz8daaqr1#

我猜您可以使用context.bindingData对象在当前函数调用的上下文中存储和检索数据。让我给予您一段修改后的代码。

export async function users(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
   const globalToken = validateToken(request);

   // u can store the token in the context.bindingData for the current invocation
   context.bindingData.globalToken = globalToken;

   if (request.method === "GET") {
      return { jsonBody: getUsers(context) };
   }
}

export const getUsers = (context: InvocationContext) => {
   // Retrieve the token from the context.bindingData
   const globalToken = context.bindingData.globalToken;

   // Use th token as wanted
   return usersData.filter(u => u.userId === globalToken.userId);
};

字符串

相关问题