22 lines
774 B
TypeScript
22 lines
774 B
TypeScript
import { Injectable, NestMiddleware } from '@nestjs/common';
|
|
import { Request, Response, NextFunction } from 'express';
|
|
import * as fs from 'fs';
|
|
import * as path from 'path';
|
|
import { ConfigService } from '@nestjs/config';
|
|
|
|
@Injectable()
|
|
export class UploadsStaticMiddleware implements NestMiddleware {
|
|
private rootDir = '/tmp';
|
|
|
|
constructor(config: ConfigService) {
|
|
const dir = path.resolve(config.get<string>('UPLOAD_DIR', './data/uploads'));
|
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
this.rootDir = dir;
|
|
}
|
|
|
|
use(req: Request, res: Response, next: NextFunction): void {
|
|
if (!req.path.startsWith('/uploads')) return next();
|
|
const express = require('express');
|
|
return express.static(this.rootDir)(req, res, next);
|
|
}
|
|
} |