装饰器导出
midway-faas 体系使用的装饰器和传统 midway web 非常相似,很多是复用的,也有一些是独有的。
装饰器只能修饰 class 、method 和 parameter
当前内置装饰器都从 @midwayjs/decorator 包中导出,即为:
import { Provide, Inject } from '@midwayjs/decorator';
@Func
能力
函数装饰器,用于修饰某个函数入口。
用法
- 1、修饰 class,默认参数为
f.yml中的 handler- a、默认函数为 handler 方法
- 2、修饰 method
// 修饰 class,单函数入口@Func('index.handler')export class IndexHandler {async handler() {}}// 修饰 method,多函数入口export class IndexHandler {@Func('index.handler1')async handler1() {}@Func('index.handler2')async handler2() {}}
@Provide
能力
被 IoC 容器所加载,配合 Inject 使用。
用法
**
- 1、标注一个类,可以被 IoC 容器所扫描到
- 2、参数 id 默认为类名驼峰形式
- 3、可以指定参数 id
@Provide() // 等价于 @Provide('userService')export class UserService {}@Provide('bService') // 可以手动调整export class BookService {}
@Inject
能力
让 IoC 容器注入特定名字的实例,配合 Provide 使用。
用法
**
- 1、标注一个需要注入的属性
- 2、参数 id 默认为属性名,如果传递,则 id 为传递的名字
- 3、id 用于获取对应的 @Provide 修饰的类
@Provide() // 等价于 @Provide('userService')export class UserService {// 默认 id 为属性名@Inject()bookService;// 可以指定 id@Inject('bookService')bService;// 如果对方修改了 ProvideId,则注入需要相应调整@Inject('sService')storeService}@Provide()export class BookService {}@Provide('sService')export class StoreService {}
@Config
能力
注入用户自定义配置。
用法
**
- 1、在
config.*.ts中写上配置,装饰器获取该配置的值
// config.default.tsexport = {buc: {test: 1}}@Func('index.handler')export class IndexHandler {@Config('buc')bucConfig;async handler() {console.log(this.bucConfig.test); // output 1}}
@Init
能力
创建实例时自动调用方法
用法
**
- 1、某个方法上写上装饰器,该方法在实例创建后会自动被调用(异步方法)
- 2、该装饰器只能在类中修饰一次
@Provide()export class UserService {@Init()async init() {}}
@Scope
能力
调整 class 创建的作用域
用法
**
- 1、默认 class 为请求作用域,此装饰器可以调整为其他作用域
@Provide()@Scope(ScopeEnum.Singleton) // 单例,进程唯一export class UserService {}@Provide()@Scope(ScopeEnum.Prototype) // 原型作用域,每次调用都创建export class UserService {}@Provide()@Scope(ScopeEnum.Request) // 请求作用域,默认,单次请求链路唯一export class UserService {}
@Configuration
能力
**
特殊的装饰器,用于配置 IoC 容器本身
用法
**
- 1、用于加载用户配置文件
- 2、用于加载其他扩展包
