npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@hiqaody/create-backend-pg

v1.1.9

Published

NestJS backend template with PostgreSQL and TypeORM

Downloads

10

Readme

@hiqaody/create-backend-pg

npm version License: MIT Node.js Version NestJS TypeScript PostgreSQL

🚀 Générateur de backend NestJS + PostgreSQL prêt pour la production

Créez une API REST complète avec authentification, base de données et bonnes pratiques en moins de 2 minutes

Démarrage RapideDocumentationExemplesSupport


✨ Pourquoi choisir ce template ?

  • 🎯 Configuration zéro : PostgreSQL + TypeORM préconfigurés
  • 🔒 Sécurité intégrée : Helmet, CORS, validation des données
  • 📦 Architecture modulaire : Structure NestJS optimale
  • 🧪 Tests inclus : Jest configuré pour tests unitaires et E2E
  • 🐳 Docker ready : Déploiement conteneurisé simplifié
  • TypeScript strict : Typage fort et autocomplétion
  • 🔄 Hot reload : Développement rapide avec watch mode
  • 📝 ESLint + Prettier : Code formaté automatiquement

🚀 Démarrage Rapide

Prérequis

  • Node.js ≥ 20.0.0
  • PostgreSQL ≥ 12
  • npm ou yarn

Installation

Option 1 : Mode interactif (Recommandé)

npx @hiqaody/create-backend-pg

Option 2 : Mode rapide

npx @hiqaody/create-backend-pg mon-api
cd mon-api
npm install
npm run start:dev

Option 3 : Avec npm create

npm create @hiqaody/backend-pg mon-api

Configuration guidée

Le CLI vous accompagne étape par étape :

🎯 Bienvenue dans le générateur NestJS + PostgreSQL

📝 Configuration du projet
→ Nom du projet : mon-api
→ Description : Mon API REST

🗄️  Configuration PostgreSQL
→ Hôte : localhost
→ Port : 5432
→ Utilisateur : postgres
→ Mot de passe : ********
→ Base de données : mon_api_db

⚙️  Configuration application
→ Port : 3000
→ Environnement : development

✅ Projet créé avec succès !

📁 Architecture du Projet

mon-api/
├── 📂 src/
│   ├── 📂 config/                    # Configuration centralisée
│   │   ├── configuration.module.ts
│   │   └── env.validation.ts
│   ├── 📂 database/                  # Module base de données
│   │   ├── database.module.ts
│   │   ├── database.service.ts
│   │   └── migrations/
│   ├── 📂 common/                    # Utilitaires partagés
│   │   ├── decorators/
│   │   ├── filters/
│   │   ├── guards/
│   │   ├── interceptors/
│   │   └── pipes/
│   ├── 📂 health/                    # Module Health (nest g resource)
│   │   ├── health.controller.ts
│   │   ├── health.controller.spec.ts
│   │   ├── health.service.ts
│   │   ├── health.service.spec.ts
│   │   └── health.module.ts
│   ├── 📂 users/                     # Exemple module (nest g resource)
│   │   ├── 📂 dto/
│   │   │   ├── create-user.dto.ts
│   │   │   └── update-user.dto.ts
│   │   ├── 📂 entities/
│   │   │   └── user.entity.ts
│   │   ├── users.controller.ts
│   │   ├── users.controller.spec.ts
│   │   ├── users.service.ts
│   │   ├── users.service.spec.ts
│   │   └── users.module.ts
│   ├── app.module.ts                 # Module racine
│   ├── app.controller.ts
│   ├── app.service.ts
│   └── main.ts                       # Point d'entrée
├── 📂 test/
│   ├── app.e2e-spec.ts
│   ├── jest-e2e.json
│   └── setup.ts
├── 📂 docker/
│   ├── Dockerfile
│   ├── docker-compose.yml
│   └── .dockerignore
├── .env                              # Variables d'environnement
├── .env.example                      # Template de configuration
├── .gitignore
├── .prettierrc
├── eslint.config.mjs
├── nest-cli.json
├── package.json
├── tsconfig.json
├── tsconfig.build.json
└── README.md

🎯 Fonctionnalités

🏗️ Backend Complet

  • Framework NestJS : Architecture modulaire et scalable
  • TypeORM : ORM puissant avec migrations automatiques
  • PostgreSQL : Base de données relationnelle robuste
  • Validation : class-validator pour validation des DTOs
  • Configuration : @nestjs/config avec validation de schéma
  • Logging : Winston pour logs structurés

🔐 Sécurité

  • Helmet : Protection des headers HTTP
  • CORS : Configuration cross-origin sécurisée
  • Rate limiting : Protection contre les attaques DDoS
  • Validation des entrées : Sanitisation automatique
  • Variables d'environnement : Gestion sécurisée des secrets
  • JWT prêt : Secret généré automatiquement

🧪 Tests & Qualité

  • Jest : Framework de test complet
  • Tests E2E : Tests d'intégration configurés
  • Couverture de code : Rapports détaillés
  • ESLint : Linting avec règles NestJS
  • Prettier : Formatage automatique du code
  • Husky : Git hooks pour qualité du code

🐳 DevOps

  • Docker : Configuration multi-stage optimisée
  • Docker Compose : Orchestration locale
  • Health checks : Endpoints de santé intégrés
  • CI/CD ready : Templates GitHub Actions
  • Migrations : Gestion des schémas de base de données

🛠️ Commandes Disponibles

Développement

| Commande | Description | |----------|-------------| | npm run start | Démarre l'application | | npm run start:dev | Mode développement avec hot-reload | | npm run start:debug | Mode debug | | npm run start:prod | Mode production |

Build & Production

| Commande | Description | |----------|-------------| | npm run build | Compile le projet | | npm run format | Formate le code avec Prettier | | npm run lint | Vérifie le code avec ESLint | | npm run lint:fix | Corrige automatiquement les erreurs |

Tests

| Commande | Description | |----------|-------------| | npm test | Lance les tests unitaires | | npm run test:watch | Tests en mode watch | | npm run test:cov | Tests avec couverture | | npm run test:debug | Tests en mode debug | | npm run test:e2e | Tests end-to-end |

Base de données

| Commande | Description | |----------|-------------| | npm run typeorm migration:generate -- -n NomMigration | Génère une migration | | npm run typeorm migration:run | Exécute les migrations | | npm run typeorm migration:revert | Annule la dernière migration | | npm run db:seed | Peuple la base de données | | npm run db:reset | Réinitialise la base |


🔧 Configuration

Variables d'environnement

Le fichier .env est automatiquement généré avec des valeurs sécurisées :

# Application
NODE_ENV=development
APP_PORT=3000
APP_HOST=localhost
APP_NAME=mon-api

# Database
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=votre_mot_de_passe_secure
POSTGRES_DB=mon_api_db
POSTGRES_SSL=false
POSTGRES_SYNC=false

# JWT (généré automatiquement avec crypto.randomBytes)
JWT_SECRET=votre_secret_jwt_ultra_securise
JWT_EXPIRES_IN=1h

# Logging
LOG_LEVEL=debug

# CORS
CORS_ORIGIN=http://localhost:3001

Configuration TypeORM

// src/database/database.module.ts
TypeOrmModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: (config: ConfigService) => ({
    type: 'postgres',
    host: config.get('POSTGRES_HOST'),
    port: config.get<number>('POSTGRES_PORT'),
    username: config.get('POSTGRES_USER'),
    password: config.get('POSTGRES_PASSWORD'),
    database: config.get('POSTGRES_DB'),
    entities: [__dirname + '/../**/*.entity{.ts,.js}'],
    migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
    synchronize: config.get('NODE_ENV') === 'development',
    logging: config.get('NODE_ENV') === 'development',
  }),
  inject: [ConfigService],
})

💡 Exemples d'Utilisation

Créer un module CRUD complet

# Générer un module avec tous les fichiers
nest g resource users

# Options proposées
? What transport layer do you use? REST API
? Would you like to generate CRUD entry points? Yes

Résultat :

src/users/
├── dto/
│   ├── create-user.dto.ts
│   └── update-user.dto.ts
├── entities/
│   └── user.entity.ts
├── users.controller.ts
├── users.controller.spec.ts
├── users.service.ts
├── users.service.spec.ts
└── users.module.ts

Note importante : Les modules générés avec nest g resource sont créés directement à la racine de src/, pas dans un sous-dossier modules/. C'est la convention standard recommandée par NestJS pour une meilleure organisation et découverte des modules.

Créer une entité avec relations

// src/users/entities/user.entity.ts
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
import { Post } from '../../posts/entities/post.entity';

@Entity('users')
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ unique: true })
  email: string;

  @Column()
  password: string;

  @Column({ nullable: true })
  firstName: string;

  @Column({ nullable: true })
  lastName: string;

  @Column({ default: true })
  isActive: boolean;

  @OneToMany(() => Post, post => post.author)
  posts: Post[];

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

Créer un DTO avec validation

// src/users/dto/create-user.dto.ts
import { IsEmail, IsString, MinLength, MaxLength, IsOptional } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsString()
  @MinLength(8)
  @MaxLength(100)
  password: string;

  @IsString()
  @IsOptional()
  @MaxLength(50)
  firstName?: string;

  @IsString()
  @IsOptional()
  @MaxLength(50)
  lastName?: string;
}

Utiliser le service dans un controller

// src/users/users.controller.ts
import { Controller, Get, Post, Body, Param, Delete, Put } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
  }

  @Get()
  findAll() {
    return this.usersService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.usersService.findOne(id);
  }

  @Put(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.usersService.update(id, updateUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.usersService.remove(id);
  }
}

🐳 Déploiement Docker

Développement local

# Démarrer tous les services
docker-compose up -d

# Voir les logs
docker-compose logs -f

# Arrêter les services
docker-compose down

Production

# Build optimisé
docker build -t mon-api:latest .

# Lancer le conteneur
docker run -p 3000:3000 --env-file .env mon-api:latest

🔍 Health Checks

Le template inclut des endpoints de santé :

# Vérifier l'état de l'application
curl http://localhost:3000/health

# Réponse
{
  "status": "ok",
  "info": {
    "database": { "status": "up" },
    "memory_heap": { "status": "up" },
    "memory_rss": { "status": "up" }
  }
}

🆘 Dépannage

Erreur de connexion PostgreSQL

Problème : Error: connect ECONNREFUSED

Solutions :

# Vérifier que PostgreSQL est démarré
sudo systemctl status postgresql

# Ou avec Homebrew (macOS)
brew services list

# Ou avec Docker
docker ps | grep postgres

# Tester la connexion
psql -h localhost -U postgres -d mon_api_db

Port déjà utilisé

Problème : Error: listen EADDRINUSE: address already in use :::3000

Solution :

# Trouver le processus qui utilise le port
lsof -i :3000

# Tuer le processus
kill -9 <PID>

# Ou changer le port dans .env
APP_PORT=3001

Migrations échouées

Problème : Erreurs lors de l'exécution des migrations

Solutions :

# Réinitialiser la base de données
npm run db:reset

# Supprimer et recréer la base
dropdb mon_api_db && createdb mon_api_db

# Exécuter les migrations à nouveau
npm run typeorm migration:run

Variables d'environnement manquantes

Problème : Configuration validation error

Solution :

# Copier le template
cp .env.example .env

# Éditer avec vos valeurs
nano .env

📚 Ressources

Documentation officielle

Guides et tutoriels


🤝 Contribution

Les contributions sont les bienvenues !

  1. Fork le projet
  2. Créez votre branche (git checkout -b feature/AmazingFeature)
  3. Committez vos changements (git commit -m 'Add: Amazing feature')
  4. Push vers la branche (git push origin feature/AmazingFeature)
  5. Ouvrez une Pull Request

📝 Changelog

Version 1.0.0 (2025-01-20)

  • ✨ Générateur CLI interactif
  • 🔒 Configuration sécurisée par défaut
  • 🐳 Support Docker complet
  • 🧪 Tests unitaires et E2E
  • 📝 Documentation complète

📄 Licence

Ce projet est sous licence MIT. Voir le fichier LICENSE pour plus de détails.


👨‍💻 Auteur

Jacquinot


⭐ Support

Si ce projet vous aide, n'hésitez pas à lui donner une étoile sur GitHub !

🚀 Créez votre backend professionnel en 2 minutes !

Star on GitHub