-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathNFSClientAdapter.ts
91 lines (75 loc) · 2.63 KB
/
NFSClientAdapter.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { Readable } from 'node:stream';
import {
AccessLevel,
LifecycleInit,
Inject,
SingletonProto,
} from '@eggjs/tegg';
import { EggAppConfig, EggLogger } from 'egg';
import FSClient from 'fs-cnpm';
import { AppendResult, NFSClient, UploadOptions, UploadResult, DownloadOptions } from '../common/typing.js';
@SingletonProto({
name: 'nfsClient',
accessLevel: AccessLevel.PUBLIC,
})
export class NFSClientAdapter implements NFSClient {
@Inject()
private logger: EggLogger;
@Inject()
private config: EggAppConfig;
private _client: any;
get client() {
return this._client;
}
url?(key: string): string;
@LifecycleInit()
protected async init() {
// NFS interface https://github.com/cnpm/cnpmjs.org/wiki/NFS-Guide
if (this.config.nfs.client) {
this._client = this.config.nfs.client;
} else {
if (this.config.env === 'prod') {
throw new Error('[NFSAdapter] Can\'t use local fs NFS on production env');
}
// try to use fs-cnpm, don't use it on production env
this.logger.warn('[NFSAdapter] Don\'t use local fs NFS on production env, store on %s', this.config.nfs.dir);
this._client = new FSClient({ dir: this.config.nfs.dir });
}
if (typeof this._client.url === 'function') {
this.url = this._client.url.bind(this._client);
}
}
async appendBytes(bytes: Uint8Array, options: UploadOptions): Promise<AppendResult> {
if (this._client.appendBytes) {
return await this._client.appendBytes(bytes, options);
}
return await this._client.appendBuffer(bytes, options);
}
async createDownloadStream(key: string): Promise<Readable | undefined> {
return await this._client.createDownloadStream(key);
}
async readBytes(key: string): Promise<Uint8Array | undefined> {
return await this._client.readBytes(key);
}
async remove(key: string): Promise<void> {
return await this._client.remove(key);
}
async upload(filePath: string, options: UploadOptions): Promise<UploadResult> {
if (this.config.nfs.removeBeforeUpload) {
await this.remove(options.key);
}
return await this._client.upload(filePath, options);
}
async uploadBytes(bytes: Uint8Array, options: UploadOptions): Promise<UploadResult> {
if (this.config.nfs.removeBeforeUpload) {
await this.remove(options.key);
}
if (this._client.uploadBytes) {
return await this._client.uploadBytes(bytes, options);
}
return await this._client.uploadBuffer(bytes, options);
}
async download(key: string, filePath: string, options: DownloadOptions): Promise<void> {
return await this._client.download(key, filePath, options);
}
}