Skip to content

About

API migrated to API makes in Rails

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Telurify API Nest

CI NestJS TypeScript Prisma PostgreSQL Docker Node.js License

Backend API for Telurify built with NestJS, TypeScript, Prisma, and PostgreSQL.

Purpose

The API exposes seismic activity stored in PostgreSQL and provides the following capabilities:

  • Query paginated seismic events.
  • Filter events by magnitude type and magnitude range.
  • Filter events by date range.
  • Filter events by tsunami status.
  • Query aggregate statistics.
  • Receive user intensity reports.
  • Register web notification devices.
  • Manage devices through a protected administrative token.

Project Status

The following modules are currently implemented:

  • Seismic events.
  • Statistics.
  • Reports.
  • Devices.
  • Administrative authentication through X-Admin-Token.
  • Distributed rate limiting compatible with the Rails Rack::Attack rules.
  • PostgreSQL persistence through Prisma.
  • Docker development and production images.
  • CORS configuration.

Automated contract tests are part of the next compatibility phase with Rails.

Architecture

The project follows a pragmatic hexagonal architecture. NestJS is used as the HTTP delivery and dependency-injection framework, while application use cases remain independent from HTTP concerns.

flowchart LR
    Client[Web / other clients]
    Controller[HTTP Controllers]
    UseCases[Application Use Cases]
    Ports[Domain Ports]
    PrismaAdapter[Prisma Repository Adapter]
    Prisma[Prisma Client]
    Postgres[(PostgreSQL / Neon)]
    RedisAdapter[Redis Adapter]
    Redis[(Redis / Upstash)]

    Client --> Controller
    Controller --> UseCases
    UseCases --> Ports
    Ports --> PrismaAdapter
    PrismaAdapter --> Prisma
    Prisma --> Postgres
    Controller -. rate limiting .-> RedisAdapter
    RedisAdapter -.-> Redis
Loading

Layers

Layer Responsibility
presentation HTTP controllers, parameters, status codes, and response serialization.
application Use cases and operation coordination.
domain Internal ports and contracts independent from Prisma and Express.
infrastructure Concrete implementations for PostgreSQL and external services.
shared Cross-cutting services such as configuration and Prisma.

Project Structure

src/
├── modules/
│   ├── devices/
│   ├── reports/
│   └── sismos/
│       ├── application/
│       ├── domain/
│       ├── infrastructure/
│       └── presentation/
├── shared/
│   └── database/
├── app.module.ts
└── main.ts
prisma/
└── schema.prisma
Dockerfile
Dockerfile.dev
docker-compose.yml

Requirements

  • Docker and Docker Compose.
  • Node.js 24 only when running commands outside Docker.
  • A local PostgreSQL instance or a Neon connection.
  • Redis in production, or to share rate-limit counters between both APIs.

Configuration

Create the local environment file:

cp .env.example .env

Main variables:

Variable Description
PORT API HTTP port. The parallel development port is 3001.
DATABASE_URL Full PostgreSQL or Neon connection URL.
DOCKER_DATABASE_URL PostgreSQL URL used when the API runs inside Docker.
POSTGRES_HOST PostgreSQL host retained from the Rails configuration.
POSTGRES_PORT PostgreSQL port.
USER_DB PostgreSQL username.
PASSWORD_DB PostgreSQL password.
ADMIN_TOKEN Token required to list and delete devices.
REDIS_URL Redis connection URL used by rate limiting.
RACK_ATTACK_REDIS_URL Dedicated rate-limiting Redis URL. Takes precedence over REDIS_URL.
ALLOWED_ORIGIN Allowed CORS origin.

DATABASE_URL takes precedence for Prisma. The POSTGRES_* variables are retained to keep the configuration names compatible with the Rails environment.

When NestJS runs directly on the host machine, use localhost in DATABASE_URL. When it runs inside Docker and connects to the PostgreSQL container exposed by the Rails Compose stack, use host.docker.internal in DOCKER_DATABASE_URL. A Neon URL can be used for both variables.

Important

Never commit .env files or real credentials.

Local Docker Development

The existing Rails API uses port 3000. This API uses port 3001 so both services can run in parallel.

docker compose up --build

The API is available at:

http://localhost:3001

Test endpoint:

curl 'http://localhost:3001/v1/sismos?page=1&per_page=10'

Stop the service:

docker compose down

Source changes are reflected through hot reload because the project is mounted as a volume. Prisma is regenerated automatically when the container starts to prevent stale generated clients in the persistent node_modules volume.

Running Without Docker

Install dependencies:

npm install
npx prisma generate

Start development mode:

npm run start:dev

The local PostgreSQL container must be running first:

docker compose up -d db backend
npm run start:dev

Type-check and build:

npm run typecheck
npm run build

Prisma and the Database

The database already exists and is shared with other services. Therefore, this project must not run destructive migrations or initially assume ownership of the schema.

To update the local Prisma model from an existing database:

npx prisma db pull
npx prisma generate

Important

Do not run prisma migrate dev or prisma migrate reset against a shared database.

Endpoints

All endpoints use the /v1 prefix.

Seismic Events

GET /v1/sismos
GET /v1/sismos/stats

Pagination parameters:

  • page: current page, defaults to 1.
  • per_page: result count, with a maximum of 1000.

Nested filters:

  • filters[mag_type]: comma-separated magnitude types.
  • filters[mag_min]: minimum magnitude.
  • filters[mag_max]: maximum magnitude.
  • filters[date_from]: start date.
  • filters[date_to]: end date.
  • filters[tsunami]: true, false, 1, 0, t, or f.

Example:

curl 'http://localhost:3001/v1/sismos?page=1&per_page=10&filters[mag_type]=mw,ml&filters[mag_min]=2'

The public response structure is compatible with Rails:

{
  "data": [],
  "pagination": {
    "current_page": 1,
    "total": 0,
    "per_page": 10
  }
}

Reports

POST /v1/sismos/:sismo_id/reports

Example:

curl -X POST 'http://localhost:3001/v1/sismos/1/reports' \
  -H 'Content-Type: application/json' \
  -d '{"felt":true,"intensity":"moderate"}'

Valid intensity values:

not_felt, weak, light, moderate, strong, severe

Devices

Register a device:

POST /v1/devices
curl -X POST 'http://localhost:3001/v1/devices' \
  -H 'Content-Type: application/json' \
  -d '{"fcm_token":"token-from-firebase-messaging"}'

List devices:

GET /v1/devices

Delete a device:

DELETE /v1/devices/:id

Administrative operations require:

X-Admin-Token: <ADMIN_TOKEN>

Rate Limiting

Requests are protected by a distributed rate limiter that replicates the Rails Rack::Attack rules:

Rule Limit Scope
Global 60 requests/minute Per IP, all endpoints except /assets
Reports 5 requests/minute Per IP, POST /v1/sismos/:id/reports only
Devices 5 requests/minute Per IP, POST /v1/devices only

Exceeding a limit returns 429 Too Many Requests with a Retry-After header and a JSON error body:

{ "error": "Rate limit exceeded. Try again in 42 seconds." }

Fixed time windows and counters use the same Redis key format as Rails (rack_attack:rack::attack:<window>:<rule>:<ip>), so both APIs share limits when connected to the same Redis instance.

Configuration:

Variable Description
RACK_ATTACK_REDIS_URL Takes precedence when set.
REDIS_URL Used when RACK_ATTACK_REDIS_URL is not set.

In production, one of the two variables is required and the application raises on boot if neither is set. In development, the limiter falls back to an in-memory store, so no local Redis is needed.

Rails Compatibility

Migration validation is performed by running both APIs at the same time:

Service URL
Rails http://localhost:3000
NestJS http://localhost:3001

Each endpoint should be compared for:

  • HTTP status code.
  • JSON structure.
  • Field names.
  • Pagination behavior.
  • Validation errors.
  • Authentication behavior.
  • Missing-resource behavior.

Testing and Quality Checks

npm run typecheck
npm run build

Docker images can be built with:

docker build -f Dockerfile.dev -t telurify-api-nest:development .
docker build -f Dockerfile -t telurify-api-nest:production .

Continuous Integration and Releases

The CI workflow runs on pushes and pull requests targeting main. It performs:

  • Dependency installation with npm ci.
  • Prisma Client generation.
  • Prisma schema validation.
  • Type-checking.
  • Application build.
  • Production Docker image build.

Releases are triggered by SemVer tags:

git tag v0.1.0
git push origin v0.1.0

The release workflow validates the project, publishes the production image to GitHub Container Registry, and creates a GitHub Release with generated notes.

Published image format:

ghcr.io/<owner>/telurify-api-nest:<version>

Stable releases also receive the latest tag. Pre-release tags such as v0.1.0-beta.1 do not update latest.

Vercel Deployment

Vercel ships zero-configuration support for NestJS: it detects src/main.ts and deploys the entire application as a single Vercel Function on Fluid compute. There is no extra entry point, api/ directory, or request rewriting to maintain — the standard Nest bootstrap is all Vercel needs.

Configure these environment variables in the Vercel project (names as read by the code):

Variable Required Notes
DATABASE_URL Yes Use the pooled Neon connection URL.
RACK_ATTACK_REDIS_URL Yes* Takes precedence over REDIS_URL.
REDIS_URL Yes* Required when RACK_ATTACK_REDIS_URL is not set.
ADMIN_TOKEN For admin endpoints Protects GET and DELETE /v1/devices.
ALLOWED_ORIGIN Recommended Comma-separated CORS origins. Defaults to allow all.

*One of the two Redis variables is mandatory in production; the application raises on boot if neither is set. Use an Upstash rediss:// URL, because the in-memory fallback does not work across serverless instances.

Notes:

  • Keep the project's Framework Preset as NestJS (Project Settings → Build and Development) with no custom Build Command or Output Directory. This also prevents Vercel from treating the repository as a container because of the Dockerfile, which remains exclusive to Docker/Compose and GHCR deployments.
  • Prisma Client is generated automatically: the postinstall script runs prisma generate on every install, on Vercel and locally.
  • Vercel sets NODE_ENV=production automatically; PORT is managed by Vercel.
  • The VERCEL environment variable enables trust proxy so rate limiting sees the real client IP. Vercel overwrites X-Forwarded-For to prevent spoofing.
  • Import the repository in Vercel or run npx vercel --prod.
  • Do not use npx vercel dev with this app: its dev runtime transpiles TypeScript with tsx/esbuild, which does not emit design:paramtypes metadata, so Nest dependency injection resolves every constructor as empty and requests fail with Cannot read properties of undefined. Keep using docker compose up, npm run start:dev, or node dist/main.js for local development.
  • To validate the exact production artifact locally: npx vercel build --prod and then node .vercel/output/functions/index.func/src/main.js with the production environment variables.

License

This project is distributed under the MIT License. See LICENSE.

About

API migrated to API makes in Rails

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages