Co-authored-by: Hongtao Lye <codert.sn@gmail.com> Co-authored-by: liuyi <forehalo@gmail.com> Co-authored-by: LongYinan <lynweklm@gmail.com> Co-authored-by: X1a0t <405028157@qq.com> Co-authored-by: JimmFly <yangjinfei001@gmail.com> Co-authored-by: Peng Xiao <pengxiao@outlook.com> Co-authored-by: xiaodong zuo <53252747+zuoxiaodong0815@users.noreply.github.com> Co-authored-by: DarkSky <25152247+darkskygit@users.noreply.github.com> Co-authored-by: Qi <474021214@qq.com> Co-authored-by: danielchim <kahungchim@gmail.com>
31 lines
956 B
TypeScript
31 lines
956 B
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { createWriteStream } from 'node:fs';
|
|
import { mkdir } from 'node:fs/promises';
|
|
import { join } from 'node:path';
|
|
import { pipeline } from 'node:stream/promises';
|
|
|
|
import { Injectable } from '@nestjs/common';
|
|
|
|
import { Config } from '../../config';
|
|
import { FileUpload } from '../../types';
|
|
|
|
@Injectable()
|
|
export class FSService {
|
|
constructor(private readonly config: Config) {}
|
|
|
|
async writeFile(key: string, file: FileUpload) {
|
|
const dest = this.config.objectStorage.fs.path;
|
|
const fileName = `${key}-${randomUUID()}`;
|
|
const prefix = this.config.node.dev
|
|
? `${this.config.https ? 'https' : 'http'}://${this.config.host}:${
|
|
this.config.port
|
|
}`
|
|
: '';
|
|
await mkdir(dest, { recursive: true });
|
|
const destFile = join(dest, fileName);
|
|
await pipeline(file.createReadStream(), createWriteStream(destFile));
|
|
|
|
return `${prefix}/assets/${fileName}`;
|
|
}
|
|
}
|