Skip to content

User Management API

This example walks you through building a LightTs API to manage users, complete with a controller, service, validator, JWT authentication, CORS, and PostgreSQL integration. It’s a practical way to see how LightTs’s modular structure and CLI streamline development.

  1. Initialize Project

    Terminal window
    lts init user-api
  2. Add Features

    Terminal window
    lts add database
    lts add validation
    lts add jwt
    lts add cors

    Select PostgreSQL for the database and enable migrations.

  3. Generate User Module

    Terminal window
    lts g resource user

    This creates src/modules/user/ with user.controller.ts, user.service.ts, and user.schema.ts.

  4. Configure Database

    Set up the database connection and entity.

  5. Define Routes

    Create secure, validated routes for user operations.

  • Directoryuser-api/
  • Directorysrc/
    • Directorycore/
      • cors.core.ts
      • logger.core.ts
    • Directorydatabase/
      • Directoryentities/
        • user.entity.ts
      • index.ts
    • Directorymodules/
      • Directoryuser/
        • user.controller.ts
        • user.service.ts
        • user.schema.ts
    • Directorymiddleware/
      • auth.middleware.ts
    • config.ts
    • routes.ts
  • index.ts
src/config.ts
export const { db, auth } = {
db: {
user: process.env.DB_USER,
name: process.env.DB_NAME,
pwd: process.env.DB_PWD,
host: process.env.DB_HOST,
port: process.env.DB_PORT ? parseInt(process.env.DB_PORT) : 5432
},
auth: {
salt: 10,
jwt: {
access: {
secret: process.env.ACCESS_JWT_SECRET,
expiresIn: '15m'
},
refresh: {
secret: process.env.REFRESH_JWT_SECRET,
expiresIn: '30d'
}
}
},
};
  1. Set Environment Variables

    Create a .env file:

    Terminal window
    # database
    DB_HOST=localhost
    DB_PORT=5432
    DB_USER=postgres
    DB_PASSWORD=password
    DB_NAME=my_api_db
    # jwt
    ACCESS_JWT_SECRET=your-secret
  2. Run Migrations

    Terminal window
    npm run migrate
  3. Start the Server

    Terminal window
    npm run dev
  4. Test the API

    Use Postman or curl to test:

    • POST /api/users with a valid JWT and body: { "name": "John Doe", "email": "[email protected]", "password": "secure123" }
    • GET /api/users with a valid JWT
  • Customization: Edit files in src/modules/user/ and src/database/ to suit your needs.
  • Security: Use a secure ACCESS_JWT_SECRET and set synchronize: false in production.
  • Scalability: Add more entities or services to expand the API.