Implementación de un sistema de inventario con NestJS, Supabase, JWT y Swagger
Este manual cubre el desarrollo completo de una API RESTful para gestión de inventario utilizando el framework NestJS con Supabase como backend.
src/
├── app.module.ts # Módulo raíz
├── main.ts # Punto de entrada
├── auth/ # Autenticación JWT
│ ├── auth.module.ts
│ ├── auth.service.ts
│ ├── auth.controller.ts
│ ├── strategies/ # Estrategias Passport
│ └── guards/ # Guards de autenticación
├── products/ # Módulo de productos
│ ├── products.module.ts
│ ├── products.service.ts
│ ├── products.controller.ts
│ └── dto/ # Data Transfer Objects
├── supabase/ # Cliente Supabase
├── users/ # Módulo de usuarios
└── shared/ # Utilidades comunes
# Instalar Nest CLI globalmente
npm install -g @nestjs/cli
# Crear nuevo proyecto
nest new inventario-api
cd inventario-api
# Instalar dependencias principales
npm install @supabase/supabase-js @nestjs/config @nestjs/jwt @nestjs/passport passport passport-jwt
npm install @nestjs/swagger swagger-ui-express bcrypt dotenv cors
npm install --save-dev @types/passport-jwt @types/bcrypt
# Generar módulos básicos
nest generate module auth
nest generate service auth
nest generate controller auth
nest generate module products
nest generate service products
nest generate controller products
nest generate module users
nest generate service users
nest generate controller users
# Crear directorios adicionales
mkdir src/supabase src/dto
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createClient } from '@supabase/supabase-js';
@Module({
providers: [
{
provide: 'SUPABASE_CLIENT',
inject: [ConfigService],
useFactory: (config: ConfigService) => {
const supabaseUrl = config.get('SUPABASE_URL');
const supabaseKey = config.get('SUPABASE_KEY');
return createClient(supabaseUrl, supabaseKey);
},
},
],
exports: ['SUPABASE_CLIENT'],
})
export class SupabaseModule {}
# Supabase Configuration
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-anon-key
# JWT Configuration
JWT_SECRET=miSuperSecretoComplejo123
JWT_EXPIRES_IN=30d
# App Configuration
PORT=3000
NODE_ENV=development
create table products (
id bigint generated by default as identity primary key,
name text not null,
description text,
price numeric not null,
stock integer default 0,
category_id bigint references categories(id),
created_at timestamp with time zone default now(),
updated_at timestamp with time zone default now()
);
import { Module } from '@nestjs/common';
import { ProductsService } from './products.service';
import { ProductsController } from './products.controller';
import { SupabaseModule } from '../supabase/supabase.module';
@Module({
imports: [SupabaseModule],
controllers: [ProductsController],
providers: [ProductsService],
})
export class ProductsModule {}
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectSupabase } from '../supabase/supabase.decorator';
import { SupabaseClient } from '@supabase/supabase-js';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';
@Injectable()
export class ProductsService {
constructor(@InjectSupabase() private readonly supabase: SupabaseClient) {}
async create(createProductDto: CreateProductDto) {
const { data, error } = await this.supabase
.from('products')
.insert(createProductDto)
.select()
.single();
if (error) throw new Error(error.message);
return data;
}
async findAll(query: any) {
let queryBuilder = this.supabase
.from('products')
.select('*');
if (query.search) {
queryBuilder = queryBuilder.ilike('name', `%${query.search}%`);
}
if (query.minPrice) {
queryBuilder = queryBuilder.gte('price', query.minPrice);
}
if (query.maxPrice) {
queryBuilder = queryBuilder.lte('price', query.maxPrice);
}
if (query.categoryId) {
queryBuilder = queryBuilder.eq('category_id', query.categoryId);
}
const { data, error } = await queryBuilder;
if (error) throw new Error(error.message);
return data;
}
async findOne(id: string) {
const { data, error } = await this.supabase
.from('products')
.select('*')
.eq('id', id)
.single();
if (error) throw new NotFoundException(`Product with ID ${id} not found`);
return data;
}
async update(id: string, updateProductDto: UpdateProductDto) {
const { data, error } = await this.supabase
.from('products')
.update(updateProductDto)
.eq('id', id)
.select()
.single();
if (error) throw new NotFoundException(`Product with ID ${id} not found`);
return data;
}
async remove(id: string) {
const { data, error } = await this.supabase
.from('products')
.delete()
.eq('id', id)
.select()
.single();
if (error) throw new NotFoundException(`Product with ID ${id} not found`);
return data;
}
}
import { Controller, Get, Post, Body, Param, Put, Delete, Query, UseGuards } from '@nestjs/common';
import { ProductsService } from './products.service';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
@ApiTags('products')
@ApiBearerAuth()
@Controller('products')
export class ProductsController {
constructor(private readonly productsService: ProductsService) {}
@Post()
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Create a new product' })
@ApiResponse({ status: 201, description: 'Product created' })
create(@Body() createProductDto: CreateProductDto) {
return this.productsService.create(createProductDto);
}
@Get()
@ApiOperation({ summary: 'Get all products' })
@ApiResponse({ status: 200, description: 'List of products' })
findAll(@Query() query: any) {
return this.productsService.findAll(query);
}
@Get(':id')
@ApiOperation({ summary: 'Get product by ID' })
@ApiResponse({ status: 200, description: 'Product found' })
@ApiResponse({ status: 404, description: 'Product not found' })
findOne(@Param('id') id: string) {
return this.productsService.findOne(id);
}
@Put(':id')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Update product' })
@ApiResponse({ status: 200, description: 'Product updated' })
update(@Param('id') id: string, @Body() updateProductDto: UpdateProductDto) {
return this.productsService.update(id, updateProductDto);
}
@Delete(':id')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Delete product' })
@ApiResponse({ status: 200, description: 'Product deleted' })
remove(@Param('id') id: string) {
return this.productsService.remove(id);
}
}
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './strategies/jwt.strategy';
import { SupabaseModule } from '../supabase/supabase.module';
@Module({
imports: [
SupabaseModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secret: configService.get('JWT_SECRET'),
signOptions: {
expiresIn: configService.get('JWT_EXPIRES_IN'),
},
}),
inject: [ConfigService],
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [JwtStrategy, PassportModule],
})
export class AuthModule {}
import { Injectable } from '@nestjs/common';
import { InjectSupabase } from '../supabase/supabase.decorator';
import { SupabaseClient } from '@supabase/supabase-js';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
@Injectable()
export class AuthService {
constructor(
@InjectSupabase() private readonly supabase: SupabaseClient,
private jwtService: JwtService,
) {}
async validateUser(email: string, password: string): Promise {
const { data: user, error } = await this.supabase
.from('users')
.select('*')
.eq('email', email)
.single();
if (error || !user) return null;
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return null;
return user;
}
async login(user: any) {
const payload = {
sub: user.id,
email: user.email,
role: user.role
};
return {
access_token: this.jwtService.sign(payload),
};
}
}
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Configuración de Swagger
const config = new DocumentBuilder()
.setTitle('Inventory API with Supabase')
.setDescription('API para gestión de inventario usando Supabase')
.setVersion('1.0')
.addBearerAuth(
{ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
'JWT',
)
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
// Habilitar CORS
app.enableCors();
// Validación global
app.useGlobalPipes(new ValidationPipe());
await app.listen(process.env.PORT || 3000);
}
bootstrap();
Accede a la documentación generada en:
GET http://localhost:3000/api
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';
import { ProductsModule } from './products/products.module';
import { UsersModule } from './users/users.module';
import { SupabaseModule } from './supabase/supabase.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
SupabaseModule,
AuthModule,
ProductsModule,
UsersModule,
],
})
export class AppModule {}
NODE_ENV=production
PORT=8080
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-service-role-key
JWT_SECRET=productionSecretKey!987
JWT_EXPIRES_IN=1h
FROM node:18-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . .
RUN npm run build
EXPOSE 8080
CMD ["node", "dist/main"]