node.js - Azure 函数 TypeScript 装饰器

标签 node.js typescript azure azure-functions

<强> Recently Azure functions released support for TypeScript :

import { AzureFunction, Context, HttpRequest } from '@azure/functions';

@some_decorator - ???
const httpTrigger: AzureFunction = async function (context: Context, 
req: HttpRequest): Promise<void> {       

}

export default httpTrigger;

我正在寻找一种实现预函数调用的好方法。 例如,前置函数可以在执行相关函数之前进行授权检查或其他必要的操作。

我想知道哪种 TypeScript 装饰器是最好、最干净的选择,但不确定实现。

最佳答案

这是一个很好的问题!

装饰器基本上是包装它们所应用的函数的函数。您可以在 official doc 中阅读有关它们如何工作的更多信息。 .

现在来到 Azure Functions,TypeScript 函数实际上会编译为 JavaScript,然后运行。因此,装饰器可以开箱即用。 :)

Note that you will have to set the experimentalDecorators flag in your tsconfig.json file to true for this to work as mentioned in the docs

这是如何实现您自己的自定义装饰器的简单示例

import { AzureFunction, Context, HttpRequest } from '@azure/functions';

function checkUserId(userId: string) {
  return function(
    target: Object,
    propertyKey: string,
    descriptor: PropertyDescriptor
  ) {
    const originalValue = descriptor.value;

    descriptor.value = async function(...args: any[]) {
      const context: Context = args[0];
      const req: HttpRequest = args[1];

      if (req.headers['x-func-user-id'] !== userId) {
        context.res = {
          status: 403,
          body: 'User not authorized!'
        };
        return;
      }

      // Call the original function
      await originalValue.apply(this, args);
      return;
    };
  };
}

class HttpTrigger {
  @checkUserId('azure-user')
  static async function(context: Context, req: HttpRequest): Promise<void> {
    context.log('HTTP trigger function processed a request.');
    const name = req.query.name || (req.body && req.body.name);

    if (name) {
      context.res = {
        // status: 200, /* Defaults to 200 */
        body: 'Hello ' + (req.query.name || req.body.name) + '! Sup?'
      };
    } else {
      context.res = {
        status: 400,
        body: 'Please pass a name on the query string or in the request body'
      };
    }
  }
}

export default HttpTrigger.function;

你可以像这样测试这个函数

curl --request GET \
  --url 'http://localhost:7071/api/HttpTrigger?name=Azure' \
  --header 'x-func-user-id: azure-user'

关于node.js - Azure 函数 TypeScript 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55299880/

相关文章:

javascript - 找不到模块 : Error: Can't resolve 'vue-confirm-dialog'

javascript - 向映射组件传递和接收多个 props

azure - 有没有办法设置将 Log Analytics 表导出到 Azure SQL 数据库?

spring-boot - Azure 应用程序服务为基于 Spring 启动 Java 8 的 war 返回 404

javascript - jsPDF 保存文件的方法不起作用

javascript - 使用 node.js 将 dataobj 合并在一起

javascript - React 组件的 <img> 中的 .jpg 模块解析失败?

javascript - 如何禁用所有 typescript 类型检查?

javascript - Jest test.each 的类型不正确

python - 无法设置 Azure Data Lake 文件的内容类型