Skip to content

DesterLib/dester-api

Repository files navigation

Dester API: A Self-Hosted Media Streaming & Management Server (Under Development)

Welcome to Dester API! If you're looking to build your own self-hosted media experience – a personal haven for your movies, TV shows, music, and photos, all organized and streamed exactly how you like – Dester API aims to be a valuable part of your toolkit.

This project is focused on creating a robust and adaptable backend. We're crafting it to give you a strong foundation to develop your personal media sanctuary, putting you in control of your digital entertainment.

Current Status: This project is currently under active development. Features are being added and may change.

Features

  • Express.js Server: Robust backend framework.
  • Socket.IO Integration: For real-time communication (foundational).
  • TypeScript: For strong typing and improved developer experience.
  • OpenAPI (Swagger) Specification: API-first design with request/response validation using express-openapi-validator.
    • Split YAML specification for better organization (src/openapi/).
    • API documentation served with Scalar UI.
  • Prisma ORM: Modern database toolkit for PostgreSQL (or other supported databases).
  • JWT Authentication: Secure stateless authentication.
    • PIN Support: For profile-level access control (set/verify PIN).
  • Developer Experience (DX): Optimized for a smooth development workflow, including features like a static dev token for easier API testing.
  • Static Dev Token: For easier API testing in development (X-Dev-Token).
  • Developer Experience (DX): Optimized for a smooth development workflow, including features like a static dev token for easier API testing.
  • Security: Foundational security with Helmet.
  • Request Logging: HTTP request logging with Morgan.
  • CORS Enabled: Configurable Cross-Origin Resource Sharing.
  • Health Checks: Endpoint to monitor API and database health.
  • Generated API Client: Foundation for generating client libraries (e.g., typescript-fetch).

Prerequisites

  • Node.js (v16 or higher recommended)
  • pnpm (or npm/yarn)
  • PostgreSQL (or your preferred database supported by Prisma)

Setup

  1. Clone the repository (if you haven't already).

  2. Install dependencies:

    pnpm install
  3. Create a .env file in the root directory. Copy example.env (if one exists) or create it with the following content, adjusting as necessary:

    # Application
    NODE_ENV=development
    PORT=3000
    
    # JWT Authentication
    JWT_SECRET=your-super-secret-key-change-this-in-production # IMPORTANT: Use a strong, unique secret
    JWT_EXPIRES_IN=1d # For production; development environment uses a longer default (365d) hardcoded in auth.ts
    
    # Database (Prisma)
    DATABASE_URL="postgresql://YOUR_DB_USER:YOUR_DB_PASSWORD@localhost:5432/YOUR_DB_NAME" # Replace with your actual connection string
    
    # CORS
    CORS_ORIGIN=http://localhost:3000 # Adjust if your frontend is on a different port/domain

    Ensure your PostgreSQL server is running and accessible with the provided DATABASE_URL.

  4. Set up the database and generate Prisma Client:

    pnpm prisma generate  # Generates Prisma Client based on your schema
    pnpm prisma migrate dev # Creates/applies migrations and creates the database if it doesn't exist

Running the Server

  • Development Mode: Uses nodemon (configured via nodemon.json) to watch for file changes and automatically restart the server. NODE_ENV=development is set via nodemon.json.

    pnpm dev
  • Build for Production: Compiles TypeScript to JavaScript in the dist/ directory.

    pnpm build
  • Run in Production Mode: Starts the server from the compiled JavaScript files. Ensure NODE_ENV=production is set in your production environment.

    pnpm start

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

Accessible Endpoints (Defaults):

  • API Base: http://localhost:3000/api
  • API Documentation (Scalar UI): http://localhost:3000/docs
  • Health Check: http://localhost:3000/api/health

Project Structure

.
├── prisma/                 # Prisma schema, migrations, and seed scripts
│   ├── migrations/
│   └── schema.prisma
├── src/
│   ├── lib/                # Core business logic (auth, health checks, prisma client, etc.)
│   ├── middleware/         # Express middleware (e.g., authentication)
│   ├── openapi/            # OpenAPI specification files (split YAML)
│   │   ├── paths/          # Endpoint definitions
│   │   └── schemas/        # Data model schemas
│   ├── routes/             # API route handlers
│   ├── types/              # TypeScript type definitions (including OpenAPI related types)
│   └── server.ts           # Main application setup and Express server entry point
├── generated-clients/      # Directory for generated API client libraries
├── .env                    # Environment variables (MUST be in .gitignore)
├── nodemon.json            # Nodemon configuration for development
├── openapi.yaml            # Main OpenAPI definition file (references files in src/openapi/)
├── package.json
├── pnpm-lock.yaml
├── tsconfig.json
└── README.md

Database with Prisma

This project uses Prisma as its Object-Relational Mapper (ORM).

  • Schema: Defined in prisma/schema.prisma.
  • Prisma Client: Type-safe database client generated from the schema.
  • Migrations: Managed by Prisma Migrate to keep your database schema in sync with your Prisma schema.

Key Prisma Commands (run with pnpm):

  • prisma studio: Open Prisma Studio (web UI to view/edit data).
  • prisma generate: Regenerate Prisma Client (e.g., after schema changes).
  • prisma migrate dev: Create a new migration based on schema changes and apply it (development).
  • prisma migrate deploy: Apply pending migrations (production).

API Documentation

Interactive API documentation is generated by Scalar from the OpenAPI specification. Access it at: http://localhost:3000/docs (when the server is running).

The OpenAPI specification is defined in openapi.yaml and split into smaller, manageable files under src/openapi/.

Authentication

The API uses JWT (JSON Web Tokens) for authenticating requests.

  1. Register a new user: POST /api/auth/register (Requires email, password, name)

  2. Login to obtain a JWT: POST /api/auth/login (Requires email, password) The response will include an accessToken.

  3. Access protected routes: Include the accessToken in the Authorization header with the Bearer scheme:

    Authorization: Bearer your-access-token-here
    

Development Authentication (X-Dev-Token)

When NODE_ENV is set to development, you can bypass JWT authentication for easier testing by sending a static development token in the X-Dev-Token header.

  • Header Name: X-Dev-Token
  • Static Token Value: b7fc7eea2a11888b269daebe91ffe292 (This is also mentioned in the /docs API description).

This allows you to call protected endpoints without needing to register/login during development.

PIN Management

  • Set/Change PIN: PUT /api/users/me/pin (Requires current password)
  • Verify PIN: POST /api/auth/verify-pin (Requires user to be logged in; verifies their own PIN)

Protected Routes

Most API routes require authentication. Publicly accessible routes typically include:

  • User registration (POST /api/auth/register)
  • User login (POST /api/auth/login)
  • API health check (GET /api/health)
  • API documentation (/docs)

Consult the API documentation at /docs for specifics on which routes require authentication.

Environment Variables

The following environment variables are used (refer to the Setup section for typical values):

  • NODE_ENV: Application environment (development or production).
  • PORT: The port the server will listen on.
  • JWT_SECRET: Secret key for signing JWTs (critical for security).
  • JWT_EXPIRES_IN: Expiration time for JWTs (e.g., 1d, 7h).
  • DATABASE_URL: Connection string for the PostgreSQL database.
  • CORS_ORIGIN: Allowed origin(s) for CORS requests.

TypeScript

This project is written in TypeScript.

  • Configuration: tsconfig.json
  • Type Definitions: Custom types are primarily in src/types/. Prisma generates its own client types.

Contributions and suggestions are welcome!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages