Files
api/src/tenants/tenants.controller.ts
T

105 lines
2.8 KiB
TypeScript
Raw Normal View History

2026-07-23 10:25:32 +03:30
import {
BadRequestException,
2026-07-23 10:25:32 +03:30
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
UploadedFile,
2026-07-23 10:25:32 +03:30
UseGuards,
UseInterceptors,
2026-07-23 10:25:32 +03:30
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { FileInterceptor } from '@nestjs/platform-express';
2026-07-23 10:25:32 +03:30
import { ProductType } from '@prisma/client';
import { diskStorage } from 'multer';
import { extname } from 'path';
2026-07-23 10:25:32 +03:30
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import {
AVATARS_DIR,
ensureUploadsDirs,
publicApiBase,
} from '../uploads/uploads.util';
2026-07-23 10:25:32 +03:30
import { CreateTenantDto } from './dto/create-tenant.dto';
import { UpdateTenantDto } from './dto/update-tenant.dto';
import { TenantsService } from './tenants.service';
const IMAGE_MIME = /^image\/(jpeg|png|gif|webp|svg\+xml)$/i;
2026-07-23 10:25:32 +03:30
@Controller('tenants')
@UseGuards(JwtAuthGuard)
export class TenantsController {
constructor(
private readonly tenantsService: TenantsService,
private readonly config: ConfigService,
) {}
2026-07-23 10:25:32 +03:30
@Get()
findAll(@Query('product') product?: ProductType) {
return this.tenantsService.findAll(product);
}
@Post('upload-avatar')
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: (_req, _file, cb) => {
ensureUploadsDirs();
cb(null, AVATARS_DIR);
},
filename: (_req, file, cb) => {
const safeExt = extname(file.originalname).toLowerCase() || '.png';
const name = `avatar_${Date.now()}_${Math.random().toString(36).slice(2, 8)}${safeExt}`;
cb(null, name);
},
}),
limits: { fileSize: 2 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
if (!IMAGE_MIME.test(file.mimetype)) {
cb(new BadRequestException('فقط تصویر (jpg/png/gif/webp/svg) مجاز است') as any, false);
return;
}
cb(null, true);
},
}),
)
uploadAvatar(@UploadedFile() file: Express.Multer.File) {
if (!file) {
throw new BadRequestException('فایل ارسال نشده است');
}
const base = publicApiBase(this.config);
return { url: `${base}/uploads/avatars/${file.filename}` };
}
2026-07-23 10:25:32 +03:30
@Get(':id')
findOne(@Param('id') id: string) {
return this.tenantsService.findOne(id);
}
@Post()
create(
@Body() dto: CreateTenantDto,
@CurrentUser() user: { id: string },
) {
return this.tenantsService.create(dto, user.id);
}
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateTenantDto,
@CurrentUser() user: { id: string },
) {
return this.tenantsService.update(id, dto, user.id);
}
@Delete(':id')
remove(@Param('id') id: string, @CurrentUser() user: { id: string }) {
return this.tenantsService.remove(id, user.id);
}
}