Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
843 changes: 674 additions & 169 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,15 @@
"dependencies": {
"@prisma/adapter-pg": "^7.4.1",
"@prisma/client": "^7.4.1",
"@supabase/supabase-js": "^2.101.0",
"bcrypt": "^6.0.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.6",
"dotenv": "^17.3.1",
"express": "^5.2.1",
"jsonwebtoken": "^9.0.3",
"morgan": "^1.10.1",
"multer": "^2.1.1",
"nodemon": "^3.1.14",
"pg": "^8.19.0",
"swagger-jsdoc": "^6.2.8",
Expand All @@ -41,6 +43,7 @@
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/multer": "^2.1.0",
"@types/node": "^25.3.2",
"@types/swagger-jsdoc": "^6.0.4",
"@types/swagger-ui-express": "^4.1.8",
Expand All @@ -50,4 +53,4 @@
"typescript": "^5.9.3",
"vitest": "^4.1.0"
}
}
}
8 changes: 1 addition & 7 deletions prisma.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,12 @@
// npm install --save-dev prisma dotenv
import "dotenv/config";
import { defineConfig } from "prisma/config";

const directUrl = process.env["DIRECT_URL"];
if (!directUrl) {
throw new Error("La variable de entorno DIRECT_URL es requerida y no está definida");
}

export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: directUrl,
url: process.env["DIRECT_URL"] || "",
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "Products" ADD COLUMN "image_url" VARCHAR(500);

-- AlterTable
ALTER TABLE "Users" ADD COLUMN "avatar_url" VARCHAR(500);
2 changes: 2 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ model Users {
email String @unique @db.VarChar(100)
password_hash String @db.VarChar(255)
phone String? @db.VarChar(20)
avatar_url String? @db.VarChar(500)
status Boolean @default(true)
created_at DateTime @default(now()) @db.Timestamptz
updated_at DateTime @updatedAt @db.Timestamptz
Expand Down Expand Up @@ -136,6 +137,7 @@ model Products {
fk_store Int
name String @db.VarChar(100)
description String? @db.Text
image_url String? @db.VarChar(500)
price Decimal @db.Decimal(10, 2) //Precio fijo del producto
offer_price Decimal? @db.Decimal(10, 2) //Precio del producto en oferta
visible Boolean @default(true)
Expand Down
10 changes: 10 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { validateEnv } from './config/env.config.js'
validateEnv() // Si falta algo, el servidor no arranca
import express from "express";
import morgan from "morgan";
import cors from "cors";
Expand Down Expand Up @@ -27,6 +29,10 @@ import { setupSwagger } from "./config/swagger.config.js";

import distanceRoutes from "./modules/global/distances/routes/distance.routes.js";

import productImageRoutes from './modules/images/routes/product-image.routes.js';
import userImageRoutes from './modules/images/routes/user-image.routes.js';
import storeImageRoutes from './modules/images/routes/store-image.routes.js';

const app = express();

//Para debug en consola de las peticiones
Expand Down Expand Up @@ -70,6 +76,10 @@ app.use("/api/orders", orderRouter);
// Rutas de distancias
app.use("/api/distances", distanceRoutes);

app.use('/products', productImageRoutes)
app.use('/users', userImageRoutes)
app.use('/stores', storeImageRoutes)

// Ruta no encontrada — va ANTES del errorHandler
app.use((req, _res, next) => {
next(new NotFoundError(`Ruta ${req.method} ${req.path} no encontrada`));
Expand Down
22 changes: 22 additions & 0 deletions src/config/env.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const requiredEnvVars = [
'DATABASE_URL',
'DIRECT_URL',
'JWT_SECRET',
'SUPABASE_URL',
'SUPABASE_SERVICE_ROLE_KEY',
'SUPABASE_BUCKET_PRODUCTS',
'SUPABASE_BUCKET_USERS',
'SUPABASE_BUCKET_STORES',
]

export function validateEnv() {
const missing = requiredEnvVars.filter(key => !process.env[key])

if (missing.length > 0) {
console.error('❌ Faltan las siguientes variables de entorno:')
missing.forEach(key => console.error(` - ${key}`))
process.exit(1)

Check failure on line 18 in src/config/env.config.js

View workflow job for this annotation

GitHub Actions / test

tests/unit/commerce/filter-store-product.test.js

Error: process.exit unexpectedly called with "1" ❯ validateEnv src/config/env.config.js:18:13 ❯ src/app.js:2:12 ❯ tests/unit/commerce/filter-store-product.test.js:3:1

Check failure on line 18 in src/config/env.config.js

View workflow job for this annotation

GitHub Actions / test

tests/unit/product/filter-product.test.js

Error: process.exit unexpectedly called with "1" ❯ validateEnv src/config/env.config.js:18:13 ❯ src/app.js:2:12 ❯ tests/unit/product/filter-product.test.js:3:1

Check failure on line 18 in src/config/env.config.js

View workflow job for this annotation

GitHub Actions / test

tests/e2e/product/products.test.js

Error: process.exit unexpectedly called with "1" ❯ validateEnv src/config/env.config.js:18:13 ❯ src/app.js:2:12 ❯ tests/e2e/product/products.test.js:4:1

Check failure on line 18 in src/config/env.config.js

View workflow job for this annotation

GitHub Actions / test

tests/e2e/users.test.js

Error: process.exit unexpectedly called with "1" ❯ validateEnv src/config/env.config.js:18:13 ❯ src/app.js:2:12 ❯ tests/e2e/users.test.js:4:1

Check failure on line 18 in src/config/env.config.js

View workflow job for this annotation

GitHub Actions / test

tests/e2e/tags.test.js

Error: process.exit unexpectedly called with "1" ❯ validateEnv src/config/env.config.js:18:13 ❯ src/app.js:2:12 ❯ tests/e2e/tags.test.js:3:1

Check failure on line 18 in src/config/env.config.js

View workflow job for this annotation

GitHub Actions / test

tests/e2e/stores.test.js

Error: process.exit unexpectedly called with "1" ❯ validateEnv src/config/env.config.js:18:13 ❯ src/app.js:2:12 ❯ tests/e2e/stores.test.js:4:1

Check failure on line 18 in src/config/env.config.js

View workflow job for this annotation

GitHub Actions / test

tests/e2e/session.test.js

Error: process.exit unexpectedly called with "1" ❯ validateEnv src/config/env.config.js:18:13 ❯ src/app.js:2:12 ❯ tests/e2e/session.test.js:4:1

Check failure on line 18 in src/config/env.config.js

View workflow job for this annotation

GitHub Actions / test

tests/e2e/categories.test.js

Error: process.exit unexpectedly called with "1" ❯ validateEnv src/config/env.config.js:18:13 ❯ src/app.js:2:12 ❯ tests/e2e/categories.test.js:3:1
}

console.log('✅ Variables de entorno validadas correctamente')
}
18 changes: 18 additions & 0 deletions src/config/supabase.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import 'dotenv/config'
import { createClient } from '@supabase/supabase-js'

let supabase

export function getSupabase() {
if (supabase) return supabase

const url = process.env.SUPABASE_URL
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY

if (!url || !serviceRoleKey) {
throw new Error('Falta configurar SUPABASE_URL y SUPABASE_SERVICE_ROLE_KEY')
}

supabase = createClient(url, serviceRoleKey)
return supabase
}
18 changes: 7 additions & 11 deletions src/lib/prisma.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import "dotenv/config";
import pkg from '@prisma/client';
import { PrismaPg } from "@prisma/adapter-pg";
import pg from "pg";
import { PrismaClient } from '@prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'
import pg from 'pg'

const { PrismaClient } = pkg;
const { Pool } = pg;
const { Pool } = pg

const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
})

const adapter = new PrismaPg(pool);
const adapter = new PrismaPg(pool)

export const prisma = new PrismaClient({
adapter,
});
export const prisma = new PrismaClient({ adapter })
16 changes: 16 additions & 0 deletions src/middlewares/auth.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ForbiddenError } from '../lib/errors.js'

/**
* Verifica que el usuario autenticado tenga uno de los roles permitidos.
* Debe usarse DESPUÉS de authenticate.
* @param {...string} roles - Roles permitidos (ej: 'ADMIN', 'SELLER')
*/
export const requireRole = (...roles) => (req, res, next) => {
if (!req.user) {
return next(new ForbiddenError('Usuario no autenticado'))
}
if (!roles.includes(req.user.role)) {
return next(new ForbiddenError('No tenés permisos para realizar esta acción'))
}
next()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
12 changes: 12 additions & 0 deletions src/middlewares/errorHandler.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AppError } from "../lib/errors.js";
import { IMAGE } from "../utils/contants/image.constant.js";

/**
* Middleware global de manejo de errores.
Expand Down Expand Up @@ -51,6 +52,17 @@ export const errorHandler = (err, req, res, next) => {
});
}

// Mapear errores de multer
if (err?.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({
error: {
code: 413,
message: `Archivo muy grande. Tamaño máximo: ${IMAGE.MAX_SIZE} MB.`
}
});
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


// Error inesperado — loguear internamente pero no exponer detalles al cliente
console.error(`[ERROR INESPERADO] ${req.method} ${req.path}`, err);

Expand Down
11 changes: 5 additions & 6 deletions src/middlewares/pagination.middleware.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import paginationConstants from "../utils/contants/pagination.contant.js";
const { DEFAULT_PAGE, DEFAULT_LIMIT, MAX_LIMIT } = paginationConstants;
import { PAGINATION } from "../utils/contants/pagination.constant.js";

export const parsePagination = (req, res, next) => {
const rawPage = req.query.page;
const rawLimit = req.query.limit;

const page =
rawPage === undefined
? DEFAULT_PAGE
? PAGINATION.DEFAULT_PAGE
: Number(rawPage);

const limit =
rawLimit === undefined
? DEFAULT_LIMIT
? PAGINATION.DEFAULT_LIMIT
: Number(rawLimit);

const errors = [];
Expand All @@ -29,10 +28,10 @@ export const parsePagination = (req, res, next) => {
field: "limit",
message: "limit debe ser un entero positivo"
});
} else if (limit > MAX_LIMIT) {
} else if (limit > PAGINATION.MAX_LIMIT) {
errors.push({
field: "limit",
message: `limit no puede ser mayor a ${MAX_LIMIT}`
message: `limit no puede ser mayor a ${PAGINATION.MAX_LIMIT}`
});
}

Expand Down
15 changes: 15 additions & 0 deletions src/middlewares/upload.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import multer from 'multer'
import { ValidationError } from '../lib/errors.js'
import { IMAGE } from '../utils/contants/image.constant.js'

export const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: IMAGE.MAX_SIZE_MB },
fileFilter: (req, file, cb) => {
if (IMAGE.ALLOWED_TYPES.includes(file.mimetype)) {
cb(null, true)
} else {
cb(new ValidationError('Formato no permitido. Usá JPG, PNG o WEBP.'))
}
}
})
Comment thread
CrisNAC marked this conversation as resolved.
Resolved
39 changes: 39 additions & 0 deletions src/modules/images/controllers/product-image.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as productImageService from '../services/product-image.service.js'

export async function getProductImage(req, res, next) {
try {
const image_url = await productImageService.getProductImage(req.params.id)
return res.json({ image_url })
} catch (error) {
next(error)
}
}

export async function uploadProductImage(req, res, next) {
try {
if (!req.file) return res.status(400).json({ message: 'No se recibió ningún archivo' })
const image_url = await productImageService.upsertProductImage(req.params.id, req.file, req.user)
return res.status(201).json({ image_url })
} catch (error) {
next(error)
}
}

export async function updateProductImage(req, res, next) {
try {
if (!req.file) return res.status(400).json({ message: 'No se recibió ningún archivo' })
const image_url = await productImageService.upsertProductImage(req.params.id, req.file, req.user)
return res.status(200).json({ image_url })
} catch (error) {
next(error)
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

export async function deleteProductImage(req, res, next) {
try {
await productImageService.removeProductImage(req.params.id, req.user)
return res.status(200).json({ message: 'Imagen eliminada correctamente' })
} catch (error) {
next(error)
}
}
39 changes: 39 additions & 0 deletions src/modules/images/controllers/store-image.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as storeImageService from '../services/store-image.service.js'

export async function getStoreImage(req, res, next) {
try {
const logo = await storeImageService.getStoreImage(req.params.id)
return res.json({ logo })
} catch (error) {
next(error)
}
}

export async function uploadStoreImage(req, res, next) {
try {
if (!req.file) return res.status(400).json({ message: 'No se recibió ningún archivo' })
const logo = await storeImageService.upsertStoreImage(req.params.id, req.file, req.user)
return res.status(201).json({ logo })
} catch (error) {
next(error)
}
}

export async function updateStoreImage(req, res, next) {
try {
if (!req.file) return res.status(400).json({ message: 'No se recibió ningún archivo' })
const logo = await storeImageService.upsertStoreImage(req.params.id, req.file, req.user)
return res.status(200).json({ logo })
} catch (error) {
next(error)
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

export async function deleteStoreImage(req, res, next) {
try {
await storeImageService.removeStoreImage(req.params.id, req.user)
return res.status(200).json({ message: 'Logo eliminado correctamente' })
} catch (error) {
next(error)
}
}
39 changes: 39 additions & 0 deletions src/modules/images/controllers/user-image.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as userImageService from '../services/user-image.service.js'

export async function getUserImage(req, res, next) {
try {
const avatar_url = await userImageService.getUserImage(req.params.id)
return res.json({ avatar_url })
} catch (error) {
next(error)
}
}

export async function uploadUserImage(req, res, next) {
try {
if (!req.file) return res.status(400).json({ message: 'No se recibió ningún archivo' })
const avatar_url = await userImageService.upsertUserImage(req.params.id, req.file, req.user)
return res.status(201).json({ avatar_url })
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} catch (error) {
next(error)
}
}

export async function updateUserImage(req, res, next) {
try {
if (!req.file) return res.status(400).json({ message: 'No se recibió ningún archivo' })
const avatar_url = await userImageService.upsertUserImage(req.params.id, req.file, req.user)
return res.status(200).json({ avatar_url })
} catch (error) {
next(error)
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

export async function deleteUserImage(req, res, next) {
try {
await userImageService.removeUserImage(req.params.id, req.user)
return res.status(200).json({ message: 'Avatar eliminado correctamente' })
} catch (error) {
next(error)
}
}
Loading
Loading