tokenRefresh, crear y editar productos con img funcionando
This commit is contained in:
@@ -57,13 +57,20 @@ export class AuthController {
|
||||
@Patch('refresh')
|
||||
//@RequirePermissions('auth:refresh-token')
|
||||
async refreshToken(@Req() req: Request,@Body() refreshTokenDto: RefreshTokenDto) {
|
||||
console.log("Pepe");
|
||||
console.log(req['user']);
|
||||
//console.log(refreshTokenDto);
|
||||
|
||||
return null
|
||||
|
||||
// console.log("Pepeeeee");
|
||||
// console.log(req['user']);
|
||||
// console.log("refreshTokenDto",refreshTokenDto);
|
||||
// console.log(typeof refreshTokenDto);
|
||||
|
||||
// return await this.authService.refreshToken(refreshTokenDto);
|
||||
const data = await this.authService.refreshToken(refreshTokenDto,req['user'].sub);
|
||||
// console.log("data",data);
|
||||
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {tokens: data}
|
||||
}
|
||||
|
||||
// @Public()
|
||||
|
||||
@@ -261,8 +261,9 @@ export class AuthService {
|
||||
}
|
||||
|
||||
//Refresh User Access Token
|
||||
async refreshToken(dto: RefreshTokenDto): Promise<RefreshTokenInterface> {
|
||||
const { user_id } = dto;
|
||||
async refreshToken(dto: RefreshTokenDto,user_id:number): Promise<RefreshTokenInterface> {
|
||||
// const { user_id } = dto;
|
||||
// const user_id = 1;
|
||||
|
||||
const session = await this.drizzle
|
||||
.select()
|
||||
@@ -274,16 +275,22 @@ export class AuthService {
|
||||
),
|
||||
);
|
||||
|
||||
// console.log(session.length);
|
||||
|
||||
if (session.length === 0) throw new NotFoundException('session not found');
|
||||
const user = await this.findUserById(dto.user_id);
|
||||
const user = await this.findUserById(user_id);
|
||||
if (!user) throw new NotFoundException('User not found');
|
||||
|
||||
// Genera token
|
||||
const tokens = await this.generateTokens(user);
|
||||
const decodeAccess = this.decodeToken(tokens.access_token);
|
||||
const decodeRefresh = this.decodeToken(tokens.refresh_token);
|
||||
|
||||
// Actualiza session
|
||||
await this.drizzle
|
||||
.update(sessions)
|
||||
.set({ sessionToken: tokens.refresh_token, expiresAt: decodeRefresh.exp })
|
||||
.where(eq(sessions.userId, dto.user_id));
|
||||
.where(eq(sessions.userId, user_id));
|
||||
|
||||
return {
|
||||
access_token: tokens.access_token,
|
||||
|
||||
@@ -39,15 +39,10 @@ export class CreateProductDto {
|
||||
status: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsInt({
|
||||
message: 'userID must be a number',
|
||||
})
|
||||
// @IsOptional()
|
||||
@IsOptional()
|
||||
userId: number;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString({
|
||||
message: 'urlImg must be a string',
|
||||
})
|
||||
@IsOptional()
|
||||
urlImg: string;
|
||||
}
|
||||
|
||||
@@ -52,43 +52,34 @@ export class UsersController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
// @Roles('admin')
|
||||
@ApiOperation({ summary: 'Create a new product' })
|
||||
@ApiResponse({ status: 201, description: 'Product created successfully.' })
|
||||
@ApiResponse({ status: 500, description: 'Internal server error.' })
|
||||
@UseInterceptors(FilesInterceptor('urlImg'))
|
||||
async create(
|
||||
@Req() req: Request,
|
||||
@Body() createUserDto: CreateProductDto,
|
||||
@UploadedFiles() files: Express.Multer.File[],
|
||||
@Query('roleId') roleId?: string,
|
||||
) {
|
||||
const data = await this.inventoryService.create(createUserDto)
|
||||
const id = Number(req['user'].id);
|
||||
const data = await this.inventoryService.create(files,createUserDto,id)
|
||||
return { message: 'User created successfully', data };
|
||||
}
|
||||
|
||||
@Patch('/id/:id')
|
||||
// @Roles('admin')
|
||||
@ApiOperation({ summary: 'Update a product' })
|
||||
@ApiResponse({ status: 200, description: 'Product updated successfully.' })
|
||||
@ApiResponse({ status: 404, description: 'Product not found.' })
|
||||
async update(@Param('id') id: string, @Body() UpdateProductDto: UpdateProductDto) {
|
||||
const data = await this.inventoryService.update(id, UpdateProductDto);
|
||||
return { message: 'User updated successfully', data };
|
||||
}
|
||||
|
||||
@Patch('/upload')
|
||||
@ApiOperation({ summary: 'Update a product' })
|
||||
@ApiResponse({ status: 200, description: 'Product uploaded successfully.'})
|
||||
@ApiResponse({ status: 404, description: 'Product not found.' })
|
||||
@ApiResponse({ status: 500, description: 'Internal server error.' })
|
||||
@UseInterceptors(FilesInterceptor('urlImg'))
|
||||
async uploadFile(@Req() req: Request, @UploadedFiles() files: Express.Multer.File[], @Body() body: any) {
|
||||
// Aquí puedes acceder a los campos del formulario
|
||||
// console.log('Archivos:', files);
|
||||
async uploadFile(
|
||||
@Req() req: Request,
|
||||
@UploadedFiles() files: Express.Multer.File[],
|
||||
@Body() body: any
|
||||
) {
|
||||
const id = Number(req['user'].id);
|
||||
// console.log(req['user'].id)
|
||||
// console.log('Otros campos del formulario:', body);
|
||||
const result = await this.inventoryService.saveImages(files,body,id);
|
||||
|
||||
// const result = ['result']
|
||||
|
||||
return { data: result };
|
||||
}
|
||||
|
||||
|
||||
@@ -187,63 +187,92 @@ export class InventoryService {
|
||||
|
||||
// Rest of the service remains the same
|
||||
async create(
|
||||
createProductDto: CreateProductDto
|
||||
file: Express.Multer.File[],
|
||||
createProductDto: CreateProductDto,
|
||||
userId: number,
|
||||
): Promise<any> {
|
||||
|
||||
let gallery: string[] = [];
|
||||
|
||||
|
||||
await Promise.all(file.map(async (f, index) => {
|
||||
const fileName = `${index + 1}-${f.originalname}`;
|
||||
gallery.push(fileName);
|
||||
}));
|
||||
|
||||
console.log(gallery);
|
||||
|
||||
|
||||
// Start a transaction
|
||||
return await this.drizzle.transaction(async (tx) => {
|
||||
|
||||
const productValue = {
|
||||
title: createProductDto.title,
|
||||
description: createProductDto.description,
|
||||
price: createProductDto.price,
|
||||
address: createProductDto.address,
|
||||
status: createProductDto.status,
|
||||
urlImg: gallery[0],
|
||||
stock: createProductDto.stock,
|
||||
userId: userId,
|
||||
gallery: gallery
|
||||
}
|
||||
console.log(productValue);
|
||||
|
||||
|
||||
const [newProduct] = await tx
|
||||
.insert(products)
|
||||
.values({
|
||||
title: createProductDto.title,
|
||||
description: createProductDto.description,
|
||||
price: createProductDto.price,
|
||||
address: createProductDto.address,
|
||||
urlImg: createProductDto.urlImg,
|
||||
stock: createProductDto.stock,
|
||||
status: createProductDto.status,
|
||||
userId: createProductDto.userId
|
||||
})
|
||||
.values(productValue)
|
||||
.returning();
|
||||
|
||||
const productId = newProduct.id;
|
||||
const picturesPath = join(__dirname, '..', '..', '..', '..', 'web', 'public', 'uploads', 'inventory',userId.toString() , productId.toString());
|
||||
// Crea el directorio si no existe
|
||||
await mkdir(picturesPath, { recursive: true });
|
||||
|
||||
await Promise.all(file.map(async (f, index) => {
|
||||
const fileName = `${index + 1}-${f.originalname}`;
|
||||
const filePath = join(picturesPath, fileName);
|
||||
await writeFile(filePath, f.buffer);
|
||||
}));
|
||||
|
||||
return newProduct
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
async update(id: string, updateProductDto: UpdateProductDto): Promise<Product> {
|
||||
const productId = parseInt(id);
|
||||
// console.log(updateProductDto);
|
||||
// async update(id: string, updateProductDto: UpdateProductDto): Promise<Product> {
|
||||
// const productId = parseInt(id);
|
||||
// // console.log(updateProductDto);
|
||||
|
||||
// Check if exists
|
||||
await this.findOne(id);
|
||||
// // Check if exists
|
||||
// await this.findOne(id);
|
||||
|
||||
// Prepare update data
|
||||
const updateData: any = {};
|
||||
if (updateProductDto.title) updateData.title = updateProductDto.title;
|
||||
if (updateProductDto.description) updateData.description = updateProductDto.description;
|
||||
if (updateProductDto.price) updateData.price = updateProductDto.price;
|
||||
if (updateProductDto.address) updateData.address = updateProductDto.address;
|
||||
if (updateProductDto.status) updateData.status = updateProductDto.status;
|
||||
if (updateProductDto.stock) updateData.stock = updateProductDto.stock;
|
||||
if (updateProductDto.urlImg) updateData.urlImg = updateProductDto.urlImg;
|
||||
// // Prepare update data
|
||||
// const updateData: any = {};
|
||||
// if (updateProductDto.title) updateData.title = updateProductDto.title;
|
||||
// if (updateProductDto.description) updateData.description = updateProductDto.description;
|
||||
// if (updateProductDto.price) updateData.price = updateProductDto.price;
|
||||
// if (updateProductDto.address) updateData.address = updateProductDto.address;
|
||||
// if (updateProductDto.status) updateData.status = updateProductDto.status;
|
||||
// if (updateProductDto.stock) updateData.stock = updateProductDto.stock;
|
||||
// if (updateProductDto.urlImg) updateData.urlImg = updateProductDto.urlImg;
|
||||
|
||||
const [updatedProduct] = await this.drizzle.update(products).set(updateData).where(eq(products.id, productId)).returning();
|
||||
return updatedProduct
|
||||
// Return updated user
|
||||
// return this.findOne(id);
|
||||
}
|
||||
// const [updatedProduct] = await this.drizzle.update(products).set(updateData).where(eq(products.id, productId)).returning();
|
||||
// return updatedProduct
|
||||
// // Return updated user
|
||||
// // return this.findOne(id);
|
||||
// }
|
||||
|
||||
/**
|
||||
* Guarda una imagen en el directorio de imágenes.
|
||||
* @param file - El archivo de imagen a guardar.
|
||||
* @returns La ruta de la imagen guardada.
|
||||
*/
|
||||
async saveImages(file: Express.Multer.File[], updateProductDto: UpdateProductDto, id: number): Promise<Product> {
|
||||
const productId = parseInt(id.toString());
|
||||
async saveImages(file: Express.Multer.File[], updateProductDto: UpdateProductDto, userId: number): Promise<Product> {
|
||||
const productId = parseInt(updateProductDto.id);
|
||||
|
||||
// Construye la ruta al directorio de imágenes.
|
||||
const picturesPath = join(__dirname, '..', '..', '..', '..', 'web', 'public', 'uploads', 'inventory', id.toString());
|
||||
const picturesPath = join(__dirname, '..', '..', '..', '..', 'web', 'public', 'uploads', 'inventory', userId.toString() , productId.toString());
|
||||
|
||||
// --- NUEVA LÓGICA: Borrar el directorio anterior ---
|
||||
try {
|
||||
@@ -278,6 +307,7 @@ export class InventoryService {
|
||||
if (updateProductDto.status) updateData.status = updateProductDto.status;
|
||||
if (updateProductDto.stock) updateData.stock = updateProductDto.stock;
|
||||
if (file && file.length > 0) updateData.gallery = gallery;
|
||||
if (file && file.length > 0) updateData.urlImg = gallery[0];
|
||||
|
||||
const [updatedProduct] = await this.drizzle.update(products).set(updateData).where(eq(products.id, productId)).returning();
|
||||
return updatedProduct;
|
||||
|
||||
Reference in New Issue
Block a user