@celljs/core 3.1.1 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1 +1,1107 @@
1
- # Cell - Core Component
1
+ # Cell - Core Component
2
+
3
+ ## 概览
4
+
5
+ Cell 核心组件是一个轻量级的应用框架,用于构建现代化的应用程序。通过依赖注入、AOP 面向切面编程、配置属性、日志等功能,提供了一套简单易用的 API 接口,支持类对象的注册、解析和生命周期管理。Cell 核心组件是基于 [InversifyJS](https://github.com/inversify/InversifyJS) 构建的,支持 TypeScript 语言。
6
+
7
+ ## 特性
8
+
9
+ - 依赖注入
10
+ - 面向切面编程
11
+ - 配置属性
12
+ - 日志
13
+
14
+ ## 安装
15
+
16
+ 使用 npm 安装 Cell 核心组件:
17
+
18
+ ```bash
19
+ npm install @celljs/core
20
+ ```
21
+
22
+ 或者使用 yarn:
23
+
24
+ ```bash
25
+ yarn add @celljs/core
26
+ ```
27
+
28
+ ## 快速开始
29
+
30
+ 以下是一个简单的依赖注入示例,展示如何使用 Cell 核心组件将一个类对象注入到 IoC 容器中:
31
+
32
+ ```typescript
33
+ import { Component } from '@celljs/core';
34
+
35
+ @Component()
36
+ export class HelloWorld {
37
+ greet() {
38
+ return 'Hello, World!';
39
+ }
40
+ }
41
+ ```
42
+
43
+
44
+ 然后,在另一个对象中使用 `@Autowired` 注解来注入 `HelloWorld` 类对象:
45
+
46
+ ```typescript
47
+ import { Autowired, ApplicationFactory } from '@celljs/core';
48
+ import { HelloWorld } from './hello-world';
49
+
50
+ export class SampleService {
51
+ @Autowired()
52
+ helloWorld: HelloWorld;
53
+
54
+ run() {
55
+ console.log(this.helloWorld.greet());
56
+ }
57
+ }
58
+ ```
59
+
60
+ 接着,在 IoC 容器模块中注册 `HelloWorld` 和 `SampleService` 类对象:
61
+
62
+ ```typescript
63
+ import { ApplicationFactory } from '@celljs/core';
64
+ import { HelloWorld } from './hello-world';
65
+ import { SampleService } from './sample-service';
66
+
67
+ export const SampleModule = autoBind();
68
+ ```
69
+
70
+ 最后,通过 `ApplicationFactory` 创建应用实例,加载 IoC 容器模块,组装成一个完整的 IoC 容器:
71
+
72
+ ```typescript
73
+ import { ApplicationFactory } from '@celljs/core';
74
+ import { SampleService } from './sample-service';
75
+ import { SampleModule } from './sample-module';
76
+
77
+ (async () => {
78
+ const appProps = {};
79
+ const app = await ApplicationFactory.create(appProps, SampleModule);
80
+ app.start();
81
+ })();
82
+
83
+ ```
84
+
85
+ ## 依赖注入
86
+
87
+ Cell 核心组件提供了依赖注入功能,支持将类对象注入到 IoC 容器中,并在其他类对象中使用 `@Autowired` 注解来注入依赖对象。以下是一个简单的依赖注入示例:
88
+
89
+ ```typescript
90
+ import { Component, Autowired } from '@celljs/core';
91
+
92
+ @Component()
93
+ export class HelloWorld {
94
+ greet() {
95
+ return 'Hello, World!';
96
+ }
97
+ }
98
+
99
+ @Component()
100
+ export class SampleService {
101
+ @Autowired()
102
+ helloWorld: HelloWorld;
103
+
104
+ run() {
105
+ console.log(this.helloWorld.greet());
106
+ }
107
+ }
108
+ ```
109
+
110
+ ## 属性注入
111
+
112
+ Cell 核心组件支持属性注入功能,通过 `@Value` 注解可以将配置属性注入到类对象中。以下是一个简单的属性注入示例:
113
+
114
+ ```typescript
115
+ import { Component, Value } from '@celljs/core';
116
+
117
+ @Component()
118
+ export class SampleService {
119
+ @Value('app.name')
120
+ appName: string;
121
+
122
+ run() {
123
+ console.log(`App Name: ${this.appName}`);
124
+ }
125
+ }
126
+ ```
127
+
128
+ 可以被注入的属性是在应用启动时通过 `ApplicationFactory` 的 `create` 方法传入的 `appProps` 对象中定义的。例如:
129
+
130
+ ```typescript
131
+ import { ApplicationFactory } from '@celljs/core';
132
+ import { SampleService } from './sample-service';
133
+
134
+ (async () => {
135
+ const appProps = {
136
+ app: { name: 'MyApp' }
137
+ };
138
+ const app = await ApplicationFactory.create(appProps, SampleModule);
139
+ app.start();
140
+ })();
141
+ ```
142
+
143
+ 属性注入时,可以使用 `.` 来访问嵌套属性,例如 `@Value('app.name')`。
144
+
145
+ 除此之外,`@Value` 的字符串才是支持 EL 表达式的,底层是基于 [jexl](https://github.com/TomFrost/jexl) 实现的。例如:
146
+
147
+ ```typescript
148
+ import { Component, Value } from '@celljs/core';
149
+
150
+ @Component()
151
+ export class SampleService {
152
+
153
+ // 对象访问
154
+ @Value('app.name')
155
+ appName: string;
156
+
157
+ // 三元表达式
158
+ @Value('app.name == "MyApp" ? "Hello, MyApp!" : "Hello, World!"')
159
+ greeting: string;
160
+
161
+ // 提供默认值
162
+ @Value('app.version ?: "1.0.0"')
163
+ appVersion: string;
164
+
165
+ // 数学运算
166
+ @Value('app.port + 1')
167
+ port: number;
168
+
169
+ // 逻辑运算
170
+ @Value('app.debug && app.env == "dev"')
171
+ debug: boolean;
172
+
173
+ // 数组访问
174
+ @Value('app.tags[0]')
175
+ tag: string;
176
+
177
+ // 数组过滤
178
+ @Value('employees[.age >= 30 && .age < 40]')
179
+ middleAgedEmployees: Employee[];
180
+
181
+ // 变换
182
+ // 假如定义如下两个变换:
183
+ // jexl.addTransform('split', (val, char) => val.split(char))
184
+ // jexl.addTransform('lower', (val) => val.toLowerCase())
185
+ @Value('"Pam Poovey"|lower|split(' ')[1]')
186
+ lastName: string;
187
+
188
+ // 函数调用
189
+ // 假如定义如下函数:
190
+ // jexl.addFunction('min', Math.min)
191
+ @Value('min(3, 5)')
192
+ min: number;
193
+
194
+ }
195
+ ```
196
+
197
+ ## IoC 容器
198
+
199
+ Cell 核心组件提供了一个轻量级的 IoC 容器,用于管理类对象的生命周期和依赖关系。通过 `@Component` 注解可以将类对象注册到 IoC 容器中,通过 `@Autowired` 注解可以在其他类对象中注入依赖对象。
200
+
201
+ IoC 容器底层实现是基于 [InversifyJS](https://github.com/inversify/InversifyJS) 的,提供了一套简单易用的 API 接口,支持类对象的注册、解析和生命周期管理。借鉴 Spring Framework 的设计理念,提供了一套类似 Spring 的装饰器,例如 `@Component`、`@Autowired`、`@Value` 等。
202
+
203
+ IoC 容器是由一些列容器模块组成的,每个容器模块是由一些类对象组成的,通过 `@Component` 注解注册到容器模块。为了方便注册类对象到容器模块中,Cell 核心组件提供了 `autoBind` 方法,可以自动注册类对象到容器模块中。`autoBind` 通过文件模块依赖分析,自动注册类对象到容器模块中,无需手动注册。
204
+
205
+ 以下是一个简单的 IoC 容器示例:
206
+
207
+ ```typescript
208
+ import { Component, Autowired, ApplicationFactory } from '@celljs/core';
209
+
210
+ @Component()
211
+ export class HelloWorld {
212
+ greet() {
213
+ return 'Hello, World!';
214
+ }
215
+ }
216
+
217
+ @Component()
218
+ export class SampleService {
219
+ @Autowired()
220
+ helloWorld: HelloWorld;
221
+
222
+ run() {
223
+ console.log(this.helloWorld.greet());
224
+ }
225
+ }
226
+
227
+ export const SampleModule = autoBind();
228
+ ```
229
+
230
+ `autoBind` 方法还提供一些列的回调函数,用于自定义注册行为。例如:
231
+
232
+ ```typescript
233
+ import { autoBind } from '@celljs/core';
234
+
235
+ export const SampleModule = autoBind((bind, unbind, isBound, rebind) => {
236
+ bind(HelloWorld).toSelf().inSingletonScope();
237
+ bind(SampleService).toSelf().inSingletonScope();
238
+ });
239
+ ```
240
+
241
+ Cell 核心组件还提供了 `ContainerFactory`,用于创建 IoC 容器实例。例如:
242
+
243
+ ```typescript
244
+ import { ContainerFactory } from '@celljs/core';
245
+ import { SampleModule } from './sample-module';
246
+
247
+ (async () => {
248
+ const container = await ContainerFactory.create(SampleModule);
249
+ const sampleService = container.get(SampleService);
250
+ sampleService.run();
251
+ })();
252
+ ```
253
+
254
+ 除了使用 `@Autowired` 装饰器来注入依赖对象,还可以使用 `ContainerUtil` 工具类来手动获取容器中的对象。例如:
255
+
256
+ ```typescript
257
+ import { ContainerUtil } from '@celljs/core';
258
+ import { SampleService } from './sample-service';
259
+
260
+ @Component()
261
+ export class SampleService {
262
+
263
+ run() {
264
+ const helloWorld = ContainerUtil.get(HelloWorld);
265
+ console.log(this.helloWorld.greet());
266
+ }
267
+ }
268
+ ```
269
+
270
+ 注意:`ContainerUtil` 工具类只能容器加载完后才能使用,否则会报错。
271
+
272
+ ## 配置属性
273
+
274
+ Cell 核心组件提供了配置属性功能,支持将配置属性注入到类对象中。通过 `@Value` 注解可以将配置属性注入到类对象中,支持 EL 表达式。
275
+
276
+ 配置属性是在应用启动时通过 `ApplicationFactory` 的 `create` 方法传入的 `appProps` 对象中定义的。例如:
277
+
278
+ ```typescript
279
+ import { ApplicationFactory } from '@celljs/core';
280
+ import { SampleService } from './sample-service';
281
+
282
+ (async () => {
283
+ const appProps = {
284
+ app: { name: 'MyApp' }
285
+ };
286
+ const app = await ApplicationFactory.create(appProps, SampleModule);
287
+ app.start();
288
+ })();
289
+ ```
290
+
291
+ 除此之外,还提供了一个 `ConfigProvider` 接口,用于加载配置文件。Cell 核心组件提供了一个默认实现,开发者也可以自定义实现替换掉默认实现。例如:
292
+
293
+ ```typescript
294
+ import { ConfigProvider } from '@celljs/core';
295
+
296
+ @Component({ id: ConfigProvider, rebind: true })
297
+ export class MyConfigProvider implements ConfigProvider {
298
+ get<T>(key: string, defaultValue?: T): T {
299
+ return process.env[key] || defaultValue;
300
+ }
301
+ }
302
+ ```
303
+
304
+ 除了前面介绍的使用 `@Value` 注解来注入配置属性,还可以使用 `ConfigUtil` 工具类来手动获取配置属性。例如:
305
+
306
+ ```typescript
307
+ import { ConfigUtil } from '@celljs/core';
308
+ import { SampleService } from './sample-service';
309
+
310
+ @Component()
311
+ export class SampleService {
312
+
313
+ run() {
314
+ const appName = ConfigUtil.get('app.name');
315
+ console.log(`App Name: ${appName}`);
316
+ }
317
+ }
318
+ ```
319
+
320
+ ## 装饰器
321
+
322
+ Cell 核心组件提供了一套类似 Spring 的装饰器,用于注册类对象到 IoC 容器中。以下是一些常用的装饰器:
323
+
324
+ - `@Component`:注册类对象到 IoC 容器中。
325
+ - `@Autowired`:注入依赖对象。
326
+ - `@Value`:注入配置属性。
327
+ - `@PostConstruct`:在类对象初始化后执行。
328
+ - `@PreDestroy`:在类对象销毁前执行。
329
+ - `@Service`:注册服务对象到 IoC 容器中。是 `@Component` 的别名。
330
+ - `@Inject`:注入依赖对象。是 `InversifyJS` 的 `inject` 的别名。
331
+ - `@Injectable`:标识类对象是可注入的。是 `InversifyJS` 的 `injectable` 的别名。
332
+ - `@Named`:指定注入对象的名称。是 `InversifyJS` 的 `named` 的别名。
333
+ - `@Optional`:标识注入对象是可选的。是 `InversifyJS` 的 `optional` 的别名。
334
+ - `@Tagged`:标识注入对象是标记的。是 `InversifyJS` 的 `tagged` 的别名。
335
+ - `@TargetName`:指定注入对象的名称。是 `InversifyJS` 的 `targetName` 的别名。
336
+ - `@Unmanaged`:标识类对象是不受管理的。是 `InversifyJS` 的 `unmanaged` 的别名。
337
+ - `@Aspect`:定义切面对象。提供 AOP 编程的能力。
338
+ - `@AutowiredProvider`:注入依赖提供者,通过依赖提供者对象,获取一类对象列表,支持排序能力。
339
+ - `@Constant`:注册常量对象到 IoC 容器中。
340
+ - `@Decorate`:装饰类对象。是 `InversifyJS` 的 `decorate` 的别名。
341
+
342
+ 除此之外,还提供了一些装饰器,用于在非托管类对象中使用(当然,也可以直接使用 `ContainerUtil` 工具类来手动获取容器中的对象),例如在前端的 React 类组件中使用。以下是一些常用的非托管类对象的装饰器:
343
+
344
+ - `@Autowired`:注入依赖对象。
345
+ - `@Value`:注入配置属性。
346
+ - `@AutowiredProvider`:注入依赖提供者,通过依赖提供者对象,获取一类对象列表,支持排序能力。
347
+
348
+ 例如:
349
+
350
+ ```tsx
351
+ import { Autowired, Value } from '@celljs/core/lib/common/annotation/detached';
352
+
353
+ export class SampleComponent extends React.Component {
354
+
355
+ @Autowired()
356
+ sampleService: SampleService;
357
+
358
+ @Value('app.name')
359
+ appName: string;
360
+
361
+ render() {
362
+ return <div>{this.appName}</div>;
363
+ }
364
+ }
365
+ ```
366
+
367
+ ## @Component 装饰器
368
+
369
+ `@Component` 装饰器用于注册类对象到 IoC 容器中。该装饰器有以下属性:
370
+
371
+ - `id`:类对象的标识符,可以是一个或多个。
372
+ - `scope`:类对象的作用域,默认是 `Scope.Singleton`。
373
+ - `name`:类对象的名称。
374
+ - `tag`:类对象的标签。
375
+ - `default`:是否是默认的类对象。当给定的服务标识符有多个绑定可用时,可以通过设置 `default` 属性来指定默认的类对象。当通过服务标识符获取单个对象时,则返回默认对象。
376
+ - `when`:一个函数,用于判断是否应该创建该类对象。如果返回 `true`,则创建该类对象;否则不创建。
377
+ - `rebind`:是否重新绑定类对象。默认是 `false`。
378
+ - `proxy`:是否使用代理类对象。默认是 `false`。当为 `true` 时,可以被 AOP 切面拦截。
379
+ - `sysTags`:系统标签,用于标识类对象。在 AOP 切面中,可以通过系统标签来拦截类对象。
380
+ - `onActivation`:在类对象激活时执行的回调函数。
381
+
382
+ 例如:
383
+
384
+ ```typescript
385
+ import { Component, Scope } from '@celljs/core';
386
+
387
+ @Component({ id: 'HelloWorld', scope: Scope.Singleton })
388
+ export class HelloWorld {
389
+ greet() {
390
+ return 'Hello, World!';
391
+ }
392
+ }
393
+ ```
394
+
395
+ 当 `id` 属性是一个数组时,表示一个类对象有多个标识符。例如:
396
+
397
+ ```typescript
398
+ import { Component } from '@celljs/core';
399
+
400
+ @Component({ id: ['HelloWorld', 'Hello'] })
401
+ export class HelloWorld {
402
+ greet() {
403
+ return 'Hello, World!';
404
+ }
405
+ }
406
+ ```
407
+
408
+ 当不设置 `id` 属性时,则默认使用类作为标识符。例如:
409
+
410
+ ```typescript
411
+ import { Component } from '@celljs/core';
412
+
413
+ @Component()
414
+ export class HelloWorld {
415
+ greet() {
416
+ return 'Hello, World!';
417
+ }
418
+ }
419
+ ```
420
+
421
+ 无论有没有设置 `id` 属性,装饰器所在的类永远都是一个标识符,都可以通过该类获取到类对象。例如:
422
+
423
+ ```typescript
424
+ import { Component } from '@celljs/core';
425
+
426
+ @Component()
427
+ export class HelloWorld {
428
+ greet() {
429
+ return 'Hello, World!';
430
+ }
431
+ }
432
+
433
+ @Component()
434
+ export class SampleService {
435
+ @Autowired()
436
+ helloWorld: HelloWorld;
437
+
438
+ run() {
439
+ console.log(this.helloWorld.greet());
440
+ }
441
+ }
442
+ ```
443
+
444
+ ## @Autowired 装饰器
445
+
446
+ `@Autowired` 装饰器用于注入依赖对象。该装饰器有以下属性:
447
+
448
+ - `id`:类对象的标识符。
449
+ - `multi`:是否是多个依赖对象。默认是根据属性类型是否为数组,自动判断,在某些情况下,需要强制指定为 `true`。
450
+ - `detached`:是否是非托管类对象。默认是 `false`。
451
+
452
+ 例如:
453
+
454
+ ```typescript
455
+ import { Autowired } from '@celljs/core';
456
+
457
+ @Component()
458
+ export class SampleService {
459
+ @Autowired({ id: HelloWorld })
460
+ helloWorld: HelloWorld;
461
+
462
+ run() {
463
+ console.log(this.helloWorld.greet());
464
+ }
465
+ }
466
+ ```
467
+
468
+ 当不设置 `id` 属性时,则默认使用属性类型作为标识符。例如:
469
+
470
+ ```typescript
471
+ import { Autowired } from '@celljs/core';
472
+
473
+ @Component()
474
+ export class SampleService {
475
+ @Autowired()
476
+ helloWorld: HelloWorld;
477
+
478
+ run() {
479
+ console.log(this.helloWorld.greet());
480
+ }
481
+ }
482
+ ```
483
+
484
+ 当一个标识在容器中存在多个对象时,可以把属性类型定义为数组,表示是多个依赖对象。例如:
485
+
486
+ ```typescript
487
+ import { Autowired } from '@celljs/core';
488
+
489
+ @Component()
490
+ export class SampleService {
491
+ @Autowired()
492
+ helloWorlds: HelloWorld[];
493
+
494
+ run() {
495
+ console.log(this.helloWorlds.map(helloWorld => helloWorld.greet()));
496
+ }
497
+ }
498
+ ```
499
+
500
+ 当一个标识在容器中存在多个对象时,也可以通过 `@AutowiredProvider` 装饰器来注入依赖提供者对象,通过依赖提供者对象,获取一类对象列表,支持排序能力。例如:
501
+
502
+ ```typescript
503
+ import { AutowiredProvider } from '@celljs/core';
504
+
505
+ @Component()
506
+ export class SampleService {
507
+ @AutowiredProvider({ id: HelloWorld })
508
+ helloWorldProvider: Provider<HelloWorld>;
509
+
510
+ run() {
511
+ const helloWorlds = this.helloWorldProvider.sortSync();
512
+ console.log(helloWorlds.map(helloWorld => helloWorld.greet()));
513
+ }
514
+ }
515
+ ```
516
+
517
+ 在使用 esbuild 编译的项目中,由于编译后的代码中没有类型信息,所以无法自动判断是否是多个依赖对象,需要强制指定为 `true`, 或者使用 `@AutowiredProvider` 装饰器。
518
+
519
+ ## @Value 装饰器
520
+
521
+ `@Value` 装饰器用于注入配置属性。该装饰器有以下属性:
522
+
523
+ - `el`:配置属性的 EL 表达式。
524
+ - `detached`:是否是非托管类对象。默认是 `false`。
525
+
526
+ 例如:
527
+
528
+ ```typescript
529
+ import { Value } from '@celljs/core';
530
+
531
+ @Component()
532
+ export class SampleService {
533
+ @Value('app.name')
534
+ appName: string;
535
+
536
+ run() {
537
+ console.log(`App Name: ${this.appName}`);
538
+ }
539
+ }
540
+ ```
541
+
542
+ ## @Constant 装饰器
543
+
544
+ `@Constant` 装饰器用于注册常量对象到 IoC 容器中。该装饰器有以下属性:
545
+
546
+ - `id`:常量对象的标识符。
547
+ - `constantValue`:常量对象的值。
548
+ - `rebind`:是否重新绑定常量对象。默认是 `false`。
549
+
550
+ 例如:
551
+
552
+ ```typescript
553
+ import { Constant } from '@celljs/core';
554
+
555
+ @Constant('app.name', 'MyApp')
556
+ @Constant('app.version', '1.0.0')
557
+ export default class {
558
+ }
559
+
560
+ @Component()
561
+ export class SampleService {
562
+ @Autowired('app.name')
563
+ name: string;
564
+
565
+ @Autowired('app.version')
566
+ version: string;
567
+ ```
568
+
569
+ ## @PostConstruct 装饰器
570
+
571
+ `@PostConstruct` 装饰器用于在类对象初始化后执行。例如:
572
+
573
+ ```typescript
574
+ import { Component, PostConstruct } from '@celljs/core';
575
+
576
+ @Component()
577
+ export class SampleService {
578
+ @PostConstruct()
579
+ init() {
580
+ console.log('SampleService initialized.');
581
+ }
582
+ }
583
+ ```
584
+
585
+ ## @PreDestroy 装饰器
586
+
587
+ `@PreDestroy` 装饰器用于在类对象销毁前执行。例如:
588
+
589
+ ```typescript
590
+ import { Component, PreDestroy } from '@celljs/core';
591
+
592
+ @Component()
593
+ export class SampleService {
594
+ @PreDestroy()
595
+ destroy() {
596
+ console.log('SampleService destroyed.');
597
+ }
598
+ }
599
+ ```
600
+
601
+ ## @Named 装饰器
602
+
603
+ `@Named` 装饰器用于指定注入对象的名称。例如:
604
+
605
+ ```typescript
606
+ import { Autowired, Named } from '@celljs/core';
607
+
608
+ @component({ name: 'HelloWorld' })
609
+ export class HelloWorld {
610
+ greet() {
611
+ return 'Hello, World!';
612
+ }
613
+ }
614
+
615
+ @Component()
616
+ export class SampleService {
617
+ @Autowired()
618
+ @Named('HelloWorld')
619
+ helloWorld: HelloWorld;
620
+
621
+ run() {
622
+ console.log(this.helloWorld.greet());
623
+ }
624
+ }
625
+ ```
626
+
627
+ ## @Tagged 装饰器
628
+
629
+ `@Tagged` 装饰器用于标识注入对象是标记的。例如:
630
+
631
+ tag?: { tag: string | number | symbol, value: any };
632
+
633
+
634
+ ```typescript
635
+ import { Autowired, Tagged } from '@celljs/core';
636
+
637
+ @Component({ tag: { tag: 'tag1', value: 'HelloWorld' } })
638
+ export class HelloWorld {
639
+ greet() {
640
+ return 'Hello, World!';
641
+ }
642
+ }
643
+
644
+ @Component()
645
+ export class SampleService {
646
+ @Autowired()
647
+ @Tagged('tag1', 'HelloWorld')
648
+ helloWorld: HelloWorld;
649
+
650
+ run() {
651
+ console.log(this.helloWorld.greet());
652
+ }
653
+ }
654
+ ```
655
+
656
+ ## @Optional 装饰器
657
+
658
+ `@Optional` 装饰器用于标识注入对象是可选的。当类属性添加了一个 `@Autowired` 注解时,如果没有找到对应的类对象,会抛出一个异常。如果添加了一个 `@Optional` 注解,当没有找到对应的类对象时,会设置属性值为 `undefined`。例如:
659
+
660
+ ```typescript
661
+ import { Autowired, Optional } from '@celljs/core';
662
+
663
+ @Component()
664
+ export class SampleService {
665
+ @Autowired()
666
+ @Optional()
667
+ helloWorld: HelloWorld;
668
+
669
+ run() {
670
+ console.log(this.helloWorld?.greet());
671
+ }
672
+ }
673
+ ```
674
+
675
+ ## @Aspect 装饰器
676
+
677
+ `@Aspect` 装饰器用于定义切面对象。提供 AOP 编程的能力。继承了 `@Component` 装饰器的所有属性。再此之上,添加了 `pointcut` 属性,用于指定切点。该装饰器有以下属性:
678
+
679
+ - `id`:类对象的标识符。相较于 `@Component` 装饰器,`id` 属性不是数组,只能是一个标识符。
680
+ - `pointcut`:切点。默认是 `COMPONENT_TAG`。表示拦截所以使用 `@Component` 装饰器注册的类对象。也可以自定义切点,例如 `AOP_TAG`。
681
+
682
+ 例如:
683
+
684
+ ```typescript
685
+ import { MethodBeforeAdvice, Autowired, Aspect, AfterReturningAdvice, Value, ConfigUtil, Injectable } from '@celljs/core';
686
+ import { AccessDecisionManager, MethodSecurityMetadataContext, ResourceNameResolver, SecurityMetadataSource, SECURITY_EXPRESSION_CONTEXT_KEY } from './access-protocol';
687
+ import { AOP_POINTCUT } from '@celljs/web';
688
+ import { SecurityContext } from '../context';
689
+ import { AuthorizeType } from '../../common';
690
+ import { Context } from '@celljs/web/lib/node';
691
+
692
+ const pointcut = ConfigUtil.getRaw().cell.security.aop?.pointcut || AOP_POINTCUT;
693
+
694
+ @Injectable()
695
+ export abstract class AbstractSecurityMethodAdivice {
696
+
697
+ @Autowired(AccessDecisionManager)
698
+ protected readonly accessDecisionManager: AccessDecisionManager;
699
+
700
+ @Autowired(SecurityMetadataSource)
701
+ protected readonly securityMetadataSource: SecurityMetadataSource;
702
+
703
+ @Autowired(ResourceNameResolver)
704
+ protected readonly resourceNameResolver: ResourceNameResolver;
705
+
706
+ @Value('cell.security.enabled')
707
+ protected readonly enabled: boolean;
708
+
709
+ protected needAccessDecision(method: string | number | symbol) {
710
+ return this.enabled && typeof method === 'string' && SecurityContext.getCurrent();
711
+ }
712
+ }
713
+
714
+ @Aspect({ id: MethodBeforeAdvice, pointcut })
715
+ export class SecurityMethodBeforeAdivice extends AbstractSecurityMethodAdivice implements MethodBeforeAdvice {
716
+
717
+ async before(method: string | number | symbol, args: any[], target: any): Promise<void> {
718
+ if (this.needAccessDecision(method)) {
719
+ const ctx: MethodSecurityMetadataContext = { method: method as string, args, target, authorizeType: AuthorizeType.Pre, grant: 0 };
720
+ const securityMetadata = await this.securityMetadataSource.load(ctx);
721
+ const resouces = await this.resourceNameResolver.resolve(ctx);
722
+ for (const resource of resouces) {
723
+ securityMetadata.resource = resource;
724
+ await this.accessDecisionManager.decide(securityMetadata);
725
+ }
726
+ }
727
+ }
728
+
729
+ }
730
+
731
+ @Aspect({ id: AfterReturningAdvice, pointcut })
732
+ export class SecurityAfterReturningAdvice extends AbstractSecurityMethodAdivice implements AfterReturningAdvice {
733
+
734
+ async afterReturning(returnValue: any, method: string | number | symbol, args: any[], target: any): Promise<void> {
735
+ if (this.needAccessDecision(method)) {
736
+ const oldCtx = Context.getAttr<MethodSecurityMetadataContext>(SECURITY_EXPRESSION_CONTEXT_KEY);
737
+ const newCtx = { method: method as string, args, target, returnValue, authorizeType: AuthorizeType.Post, grant: oldCtx.grant };
738
+ const securityMetadata = await this.securityMetadataSource.load(newCtx);
739
+ const resouces = await this.resourceNameResolver.resolve(newCtx);
740
+ for (const resource of resouces) {
741
+ securityMetadata.resource = resource;
742
+ await this.accessDecisionManager.decide(securityMetadata);
743
+ }
744
+ }
745
+ }
746
+
747
+ }
748
+ ```
749
+
750
+
751
+ ## 其他装饰器
752
+
753
+ 其他非常用的装饰器,可以参考 [InversifyJS](https://github.com/inversify/InversifyJS)。
754
+
755
+
756
+ ## AOP 面向切面编程
757
+
758
+ Cell 核心组件提供了 AOP 面向切面编程的能力,支持在类对象的方法执行前、执行后、执行异常时执行一些操作。通过 `@Aspect` 装饰器可以定义切面对象,通过 `MethodBeforeAdvice`、`AfterReturningAdvice`、`AfterThrowsAdvice` 接口可以定义通知对象。
759
+
760
+ AOP 能力涉及一下接口:
761
+
762
+ - `MethodBeforeAdvice`:在方法执行前执行。
763
+ - `AfterReturningAdvice`:在方法执行后执行。
764
+ - `AfterThrowsAdvice`:在方法执行异常时执行。
765
+
766
+ 可以使用 `@Aspect` 装饰器定义切面对象,通过 `pointcut` 属性指定切点。例如:
767
+
768
+ ```typescript
769
+ import { MethodBeforeAdvice, Autowired, Aspect, AfterReturningAdvice, Value, ConfigUtil, Injectable } from '@celljs/core';
770
+
771
+ const pointcut = 'test';
772
+
773
+ @Component({ id: MethodBeforeAdvice, pointcut })
774
+ export class TestMethodBeforeAdvice implements MethodBeforeAdvice {
775
+
776
+ async before(method: string | number | symbol, args: any[], target: any): Promise<void> {
777
+ console.log('before');
778
+ }
779
+
780
+ }
781
+
782
+ @Component({ id: AfterReturningAdvice, pointcut })
783
+ export class TestAfterReturningAdvice implements AfterReturningAdvice {
784
+
785
+ async afterReturning(returnValue: any, method: string | number | symbol, args: any[], target: any): Promise<void> {
786
+ console.log('after');
787
+ }
788
+
789
+ }
790
+
791
+ @Component({ id: AfterThrowsAdvice, pointcut })
792
+ export class TestAfterThrowsAdvice implements AfterThrowsAdvice {
793
+
794
+ async afterThrows(error: any, method: string | number | symbol, args: any[], target: any): Promise<void> {
795
+ console.log('throws');
796
+ }
797
+
798
+ }
799
+ ```
800
+
801
+ 上面的示例表示定义了一个切面对象,通过 `pointcut` 属性指定切点为 `test`。当一个类对象的方法执行前、执行后、执行异常时,会执行相应的操作。其中,切点为 `test`,表示拦截所有使用 `@Component` 装饰器注册的类对象,且 sysTag 为 `test`。
802
+
803
+
804
+ ## 搭建应用
805
+
806
+ Cell 核心组件提供了一个轻量级的应用框架,用于搭建应用程序。通过 `Application` 接口可以定义应用程序,通过 `ApplicationLifecycle` 接口可以定义应用程序的生命周期。通过 `ApplicationLifecycle` 接口可以定义应用程序的生命周期。通过 `ApplicationStateService` 接口可以定义应用程序的状态管理。通过 `ApplicationFactory` 可以创建应用实例。
807
+
808
+ 一般使用 ApplicationFactory 创建应用实例,加载 IoC 容器模块,组装成一个完整的 IoC 容器。例如:
809
+
810
+ ```typescript
811
+ import { ApplicationFactory } from '@celljs/core';
812
+ import { SampleService } from './sample-service';
813
+ import { SampleModule } from './sample-module';
814
+
815
+ (async () => {
816
+ const appProps = {
817
+ app: { name: 'MyApp' }
818
+ };
819
+ const app = await ApplicationFactory.create(appProps, SampleModule);
820
+ app.start();
821
+ })();
822
+ ```
823
+
824
+ 在应用程序中,可以通过 `ApplicationLifecycle` 接口定义应用程序的生命周期。例如:
825
+
826
+ ```typescript
827
+ import { ApplicationLifecycle, Application } from '@celljs/core';
828
+
829
+ export class SampleLifecycle implements ApplicationLifecycle {
830
+ onStart(app: Application): Promise<void> {
831
+ return Promise.resolve();
832
+ }
833
+
834
+ onStop(app: Application): void {
835
+ console.log('Application stopped.');
836
+ }
837
+ }
838
+ ```
839
+
840
+ 另外,在 browser 和 node 目录下,提供了 `Application` 的实现,可以直接使用。
841
+
842
+ ## 目录结构说明
843
+
844
+ ```shell
845
+ .
846
+ ├── browser # 浏览器端应用
847
+ │ ├── application # 前端应用程序
848
+ │ ├── browser.ts # 与浏览器相关的工具方法
849
+ │ ├── index.ts # 导出模块
850
+ │ ├── shell # 前端应用程序启动入口
851
+ │ └── static-module.ts # 静态加载类型的 IoC 容器模块
852
+ ├── common # 公共模块
853
+ │ ├── annotation # 装饰器定义目录
854
+ │ ├── aop # AOP 相关
855
+ │ ├── application # 后端应用程序
856
+ │ ├── config # 配置属性
857
+ │ ├── constants.ts # 常量定义
858
+ │ ├── container # IoC 容器
859
+ │ ├── el # EL 表达式
860
+ │ ├── error # 错误处理
861
+ │ ├── index.ts # 导出模块
862
+ │ ├── logger # 日志
863
+ │ ├── provider # 依赖提供者
864
+ │ ├── static-module.ts # 静态加载类型的 IoC 容器模块
865
+ │ ├── test # 测试
866
+ │ └── utils # 工具方法
867
+ ├── node # Node.js 端应用
868
+ │ ├── application # 后端应用程序
869
+ │ ├── constants.ts # 常量定义
870
+ │ ├── context # 上下文
871
+ │ ├── index.ts # 导出模块
872
+ │ ├── static-module.ts # 静态加载类型的 IoC 容器模块
873
+ │ └── utils # 工具方法
874
+ └── package.spec.ts # 单元测试
875
+ ```
876
+
877
+ ## 错误类型
878
+
879
+ Cell 核心组件提供了一些常用的错误类型,用于处理异常情况。
880
+
881
+ - `CustomError`:自定义错误类型。
882
+ - `IllegalArgumentError`:非法参数错误。
883
+ - `IllegalStateError`:非法状态错误。
884
+ - `InvalidMimeTypeError`:无效的 MIME 类型错误。
885
+
886
+ 例如:
887
+
888
+ ```typescript
889
+ import { IllegalArgumentError } from '@celljs/core';
890
+
891
+ if (condition) {
892
+ throw new IllegalArgumentError('Invalid argument.');
893
+ }
894
+ ```
895
+
896
+ 由于 JS 的运行时提供的错误类型无法通过 `instanceof` 运算符来判断,所以 Cell 核心组件提供了 `CustomError` 基类,用于自定义错误类型。所以建议自定义错误类型都继承自 `CustomError` 基类。
897
+
898
+ ## 日志
899
+
900
+ Cell 核心组件提供了日志功能,支持日志级别、日志格式、日志输出等功能。通过 `Logger` 接口可以定义日志对象,通过 `TraceIdProvider` 接口可以定义跟踪 ID 提供者。
901
+
902
+ 日志级别有以下几种:
903
+
904
+ - `verbose`:详细信息。
905
+ - `debug`:调试信息。
906
+ - `info`:信息。
907
+ - `warn`:警告。
908
+ - `error`:错误。
909
+
910
+ 例如:
911
+
912
+ ```typescript
913
+ import { Logger } from '@celljs/core';
914
+
915
+ @Component()
916
+ export class SampleService {
917
+
918
+ @Autowired(Logger)
919
+ logger: Logger;
920
+
921
+ run() {
922
+ this.logger.info('Info message.');
923
+ this.logger.error('Error message.');
924
+ }
925
+ }
926
+ ```
927
+
928
+ 其中,默认提供的日志输出为 `console`,为了支持不同类对象,注入的日志对象都是互相独立的,可以通过 `setContext` 方法设置上下文信息。例如:
929
+
930
+ ```typescript
931
+ import { Logger } from '@celljs/core';
932
+
933
+ @Component()
934
+ export class SampleService {
935
+
936
+ @Autowired(Logger)
937
+ logger: Logger;
938
+
939
+ run() {
940
+ this.logger.setContext('SampleService');
941
+ this.logger.info('Info message.');
942
+ this.logger.error('Error message.');
943
+ }
944
+ }
945
+ ```
946
+
947
+ 开发者也可以根据自己的需求,自定义 `Logger` 接口的实现,替换掉默认的实现。例如:
948
+
949
+ ```typescript
950
+ import { Component } from '@celljs/core';
951
+
952
+ @Component({ id: Logger, rebind: true })
953
+ export class MyLogger implements Logger {
954
+ // TODO
955
+ }
956
+ ```
957
+
958
+
959
+ ## 上下文能力
960
+
961
+ Cell 核心组件提供了上下文能力,支持应用程序上下文、请求上下文、会话上下文等。通过 `Context` 类可以设置和获取上下文信息。
962
+
963
+ 上下文信息有以下几种:
964
+
965
+ - `App`:应用程序上下文。
966
+ - `Request`:请求上下文。
967
+ - `Session`:会话上下文。
968
+
969
+
970
+ ```typescript
971
+ import { Context, AttributeScope } from '@celljs/core';
972
+
973
+ Context.setAttr('key', 'value', AttributeScope.Request);
974
+ const value = Context.getAttr('key', AttributeScope.Request);
975
+ ```
976
+
977
+
978
+ 上下文运行可以保证上下文信息在函数执行期间有效。例如:
979
+
980
+ ```typescript
981
+ import { Context } from '@celljs/core';
982
+
983
+ Context.run(async () => {
984
+ Context.setAttr('key', 'value1', AttributeScope.Request);
985
+ const value = Context.getAttr('key', AttributeScope.Request);
986
+ console.log(value); // value1
987
+ });
988
+
989
+ Context.run(() => {
990
+ Context.setAttr('key', 'value2', AttributeScope.Request);
991
+ const value = Context.getAttr('key', AttributeScope.Request);
992
+ console.log(value); // value2
993
+ });
994
+ ```
995
+
996
+ ## 常用工具类和方法
997
+
998
+ Cell 核心组件提供了一些常用的工具类和方法,用于处理一些常见的问题。
999
+
1000
+ - `AnnotationUtil`:注解工具类。
1001
+ - `Assert`:断言工具类。
1002
+ - `Async`:异步工具类。
1003
+ - `Cancellation`:取消工具类。
1004
+ - `ClassUtil`:类工具类。
1005
+ - `Disposable`:可释放工具类。
1006
+ - `Emitter`:事件工具类。
1007
+ - `Event`:事件工具类。
1008
+ - `GlobalUtil`:全局工具类。
1009
+ - `MetadataUtil`:元数据工具类。
1010
+ - `Prioritizeable`:优先级工具类。
1011
+ - `PromiseUtil`:Promise 工具类。
1012
+ - `ProxyUtil`:代理工具类。
1013
+ - `Types`:类型工具类。
1014
+ - `UrlUtil`:URL 工具类。
1015
+ - `generateUUUID`:生成 UUID。
1016
+ - `OS`:操作系统工具类。
1017
+ - `MimeTypeUtil`:MIME 类型工具类。
1018
+ - `MimeType`:MIME 类型。
1019
+
1020
+ 例如:
1021
+
1022
+ ```typescript
1023
+ import { Assert } from '@celljs/core';
1024
+
1025
+ Assert.isTrue(condition, 'Invalid argument.');
1026
+ ```
1027
+
1028
+ ## EL 表达式
1029
+
1030
+ Cell 核心组件支持 EL 表达式,EL 表达式是一种简单、易读的模板语言,可以用于在模板中动态生成内容。通过 `ExpressionCompiler` 接口可以编译 EL 表达式,通过 `ExpressionHandler` 接口可以处理 EL 表达式。
1031
+
1032
+ 有以下核心接口:
1033
+
1034
+ - `ExpressionCompiler`:编译 EL 表达式。
1035
+ - `ExpressionHandler`:处理 EL 表达式。
1036
+ - `ExpressionContext`:EL 表达式上下文。
1037
+ - `ContextInitializer`:上下文初始化器。
1038
+ - `ExpressionContextProvider`:EL 表达式上下文提供者。
1039
+ - `JexlEngineProvider`:Jexl 引擎提供者。
1040
+
1041
+ 例如:
1042
+
1043
+ ```typescript
1044
+ import { ExpressionHandler } from '@celljs/core';
1045
+
1046
+ @Component()
1047
+ export class SampleService {
1048
+
1049
+ @Autowired(ExpressionHandler)
1050
+ expressionHandler: ExpressionHandler;
1051
+
1052
+ run() {
1053
+ const result = this.expressionHandler.handle('Hello, ${name}!', { name: 'World' });
1054
+ console.log(result); // Hello, World!
1055
+ }
1056
+ }
1057
+ ```
1058
+
1059
+ 可以为 EL 表达式添加新的上下文变量、函数、变换器等。例如:
1060
+
1061
+ ```typescript
1062
+ import { ContextInitializer } from '@celljs/core';
1063
+
1064
+ @Component(ContextInitializer)
1065
+ export class CoreContextInitializer implements ContextInitializer {
1066
+
1067
+ @Autowired(JexlEngineProvider)
1068
+ protected readonly jexlEngineProvider: JexlEngineProvider<any>;
1069
+
1070
+ initialize(ctx: ExpressionContext): void {
1071
+ if (typeof process !== 'undefined') {
1072
+ ctx.env = { ...process.env, _ignoreEl: true };
1073
+ }
1074
+ const jexlEngine = this.jexlEngineProvider.provide();
1075
+ jexlEngine.addTransform('replace',
1076
+ (val: string, searchValue: string | RegExp, replaceValue: string) => val && val.replace(new RegExp(searchValue, 'g'), replaceValue));
1077
+ jexlEngine.addTransform('regexp', (pattern: string, flags?: string) => new RegExp(pattern, flags));
1078
+ const expressionHandler = ContainerUtil.get<ExpressionHandler>(ExpressionHandler);
1079
+ jexlEngine.addTransform('eval', (text: string) => expressionHandler.handle(text));
1080
+ }
1081
+
1082
+ priority = 500;
1083
+
1084
+ }
1085
+ ```
1086
+
1087
+ 应用的属性配置默认支持 EL 表达式模版字符串,例如:
1088
+
1089
+ ```typescript
1090
+ import { ApplicationFactory } from '@celljs/core';
1091
+
1092
+ (async () => {
1093
+ const appProps = {
1094
+ app: { name: 'MyApp' },
1095
+ env: '${env}',
1096
+ version: '${version}',
1097
+ appVersion: '${app.name}-${version}',
1098
+ appVersion2: '${app.name}-${version}-${env}',
1099
+ };
1100
+ const app = await ApplicationFactory.create(appProps, SampleModule);
1101
+ app.start();
1102
+ })();
1103
+ ```
1104
+
1105
+ ## 许可证
1106
+
1107
+ 本项目采用 MIT 许可证。