Skip to content

BitoGTM/Typescript_examples

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Express TypeScript REST API

A RESTful API built with Express.js and TypeScript, featuring type safety, authentication, authorization, and PostgreSQL database integration.

Features

  • ✅ TypeScript for type safety
  • ✅ Express.js for the web framework
  • ✅ PostgreSQL database with Prisma ORM
  • ✅ JWT-based authentication
  • ✅ Role-based authorization (USER, ADMIN)
  • ✅ Password hashing with bcrypt
  • ✅ RESTful API design
  • ✅ Structured project organization
  • ✅ Error handling middleware
  • ✅ Environment variable configuration

Project Structure

├── src/
│   ├── config/          # Configuration files (database)
│   ├── controllers/     # Request handlers
│   ├── middleware/      # Express middleware (auth)
│   ├── routes/          # Route definitions
│   ├── types/           # TypeScript type definitions
│   ├── utils/           # Utility functions (JWT, password)
│   └── index.ts         # Application entry point
├── prisma/
│   └── schema.prisma    # Prisma schema definition
├── dist/                # Compiled JavaScript (generated)
├── package.json
├── tsconfig.json
└── README.md

Getting Started

Prerequisites

  • Node.js (v16 or higher)
  • npm or yarn
  • PostgreSQL (v12 or higher)

Installation

  1. Install dependencies:
npm install
  1. Set up PostgreSQL database:

    • Install PostgreSQL if you haven't already
    • Create a new database:
    CREATE DATABASE express_typescript_api;
  2. Configure environment variables: Create a .env file in the root directory:

    # Server
    PORT=3000
    NODE_ENV=development
    
    # Database
    DATABASE_URL="postgresql://username:password@localhost:5432/express_typescript_api?schema=public"
    
    # JWT
    JWT_SECRET=your-super-secret-jwt-key-change-in-production
    JWT_EXPIRES_IN=7d

    Replace username, password, and database name with your PostgreSQL credentials.

  3. Set up Prisma:

    # Generate Prisma Client
    npm run prisma:generate
    
    # Run database migrations
    npm run prisma:migrate
  4. Start the development server:

npm run dev

The server will start on http://localhost:3000 (or the PORT specified in your .env file).

Available Scripts

  • npm run dev - Start development server with hot reload
  • npm run build - Compile TypeScript to JavaScript
  • npm start - Run the compiled JavaScript
  • npm run lint - Run ESLint
  • npm run prisma:generate - Generate Prisma Client
  • npm run prisma:migrate - Run database migrations
  • npm run prisma:studio - Open Prisma Studio (database GUI)

API Endpoints

Authentication (Public)

  • POST /api/auth/register - Register a new user
  • POST /api/auth/login - Login user
  • GET /api/auth/me - Get current user (requires authentication)

Users (Protected - requires authentication)

  • GET /api/users - Get all users
  • GET /api/users/:id - Get user by ID
  • PUT /api/users/:id - Update a user (can update own profile or admin)
  • DELETE /api/users/:id - Delete a user (can delete own account or admin)

Example Requests

1. Register a new user:

curl -X POST http://localhost:3000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123"
  }'

Response:

{
  "success": true,
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "user": {
      "id": 1,
      "name": "John Doe",
      "email": "john@example.com",
      "role": "USER"
    }
  }
}

2. Login:

curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "password123"
  }'

3. Get current user (requires token):

curl http://localhost:3000/api/auth/me \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

4. Get all users (requires token):

curl http://localhost:3000/api/users \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

5. Get user by ID (requires token):

curl http://localhost:3000/api/users/1 \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

6. Update a user (requires token):

curl -X PUT http://localhost:3000/api/users/1 \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Jane Doe",
    "email": "jane@example.com"
  }'

7. Delete a user (requires token):

curl -X DELETE http://localhost:3000/api/users/1 \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Authentication

The API uses JWT (JSON Web Tokens) for authentication. After registering or logging in, you'll receive a token that should be included in subsequent requests:

Authorization: Bearer YOUR_TOKEN_HERE

Authorization Rules

  • Users can:

    • View all users
    • View their own profile
    • Update their own profile
    • Delete their own account
  • Admins can:

    • Do everything users can do
    • Update any user's profile
    • Delete any user's account

Database Schema

The application uses Prisma ORM with PostgreSQL. The main model is:

User:

  • id (Int, Primary Key, Auto-increment)
  • name (String)
  • email (String, Unique)
  • password (String, Hashed)
  • role (Enum: USER, ADMIN)
  • createdAt (DateTime)
  • updatedAt (DateTime)

Security Features

  • ✅ Passwords are hashed using bcrypt (10 salt rounds)
  • ✅ JWT tokens for stateless authentication
  • ✅ Role-based access control (RBAC)
  • ✅ Protected routes with authentication middleware
  • ✅ Authorization checks for user operations

Environment Variables

Variable Description Default
PORT Server port 3000
NODE_ENV Environment mode development
DATABASE_URL PostgreSQL connection string Required
JWT_SECRET Secret key for JWT signing Required
JWT_EXPIRES_IN Token expiration time 7d

Next Steps

  • Add input validation middleware (e.g., Joi, Zod)
  • Add rate limiting
  • Add request logging (e.g., Winston, Morgan)
  • Add unit and integration tests
  • Add API documentation (Swagger/OpenAPI)
  • Add email verification
  • Add password reset functionality
  • Add refresh tokens

License

ISC

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors