Manual Completo de NestJS con Supabase PostgreSQL

Implementación de un sistema de inventario con NestJS, Supabase, JWT y Swagger

🚀 Introducción

Este manual cubre el desarrollo completo de una API RESTful para gestión de inventario utilizando el framework NestJS con Supabase como backend.

💡 Tecnologías Clave

📐 Arquitectura del Proyecto

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

1. Configuración del Proyecto

Creación del Proyecto e Instalación de Dependencias

Terminal
# 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

Estructura de Archivos Básica

Terminal
# 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

2. Conexión a Supabase

Configuración del Cliente Supabase

src/supabase/supabase.module.ts
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 {}

Variables de Entorno

.env
# 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

🔍 Configuración en Supabase Dashboard

  1. Ve a app.supabase.com
  2. Crea un nuevo proyecto
  3. En la página de configuración, encuentra:
    • URL: Config → Project Settings → API
    • Clave anónima: Config → Project Settings → API
  4. Crea la tabla 'products' en el editor SQL

SQL para Crear Tabla de Productos

Supabase SQL Editor
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()
);

3. Implementación del CRUD

Módulo de Productos

src/products/products.module.ts
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 {}

Servicio de Productos

src/products/products.service.ts
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;
  }
}

Controlador de Productos

src/products/products.controller.ts
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);
  }
}

4. Autenticación con JWT

Módulo de Autenticación

src/auth/auth.module.ts
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 {}

Servicio de Autenticación

src/auth/auth.service.ts
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),
    };
  }
}

5. Documentación Automática

Configuración de Swagger

src/main.ts
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();

📚 Documentación Interactiva

Accede a la documentación generada en:

GET http://localhost:3000/api

Swagger UI

6. Configuración Completa

Módulo Principal

src/app.module.ts
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 {}

Variables de Entorno de Producción

.env.production
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

Dockerfile para Producción

Dockerfile
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"]