-
Notifications
You must be signed in to change notification settings - Fork 568
/
informationService.ts
66 lines (56 loc) 路 1.41 KB
/
informationService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { IInformationService, ScopeEnum } from '../interface';
import {
getCurrentEnvironment,
getUserHome,
isDevelopmentEnvironment,
} from '../util';
import { dirname, join } from 'path';
import { Provide, Inject, Init, Scope } from '../decorator';
import { existsSync, readFileSync } from 'fs';
@Provide()
@Scope(ScopeEnum.Singleton)
export class MidwayInformationService implements IInformationService {
private pkg: Record<string, unknown>;
@Inject()
protected appDir: string;
@Inject()
protected baseDir: string;
@Init()
protected init() {
if (this.baseDir) {
if (!this.appDir) {
this.appDir = dirname(this.baseDir);
}
const pkgPath = join(this.appDir, 'package.json');
if (existsSync(pkgPath)) {
const content = readFileSync(pkgPath, {
encoding: 'utf-8',
});
this.pkg = JSON.parse(content);
} else {
this.pkg = {};
}
} else {
this.pkg = {};
}
}
getAppDir(): string {
return this.appDir;
}
getBaseDir(): string {
return this.baseDir;
}
getHome(): string {
return getUserHome();
}
getPkg(): any {
return this.pkg;
}
getProjectName(): string {
return (this.pkg?.['name'] as string) || '';
}
getRoot(): string {
const isDevelopmentEnv = isDevelopmentEnvironment(getCurrentEnvironment());
return isDevelopmentEnv ? this.getAppDir() : this.getHome();
}
}