Backend API for Telurify built with NestJS, TypeScript, Prisma, and PostgreSQL.
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.
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::Attackrules. - PostgreSQL persistence through Prisma.
- Docker development and production images.
- CORS configuration.
Automated contract tests are part of the next compatibility phase with Rails.
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
| 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. |
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
- 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.
Create the local environment file:
cp .env.example .envMain 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.
The existing Rails API uses port 3000. This API uses port 3001 so both services can run in parallel.
docker compose up --buildThe 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 downSource 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.
Install dependencies:
npm install
npx prisma generateStart development mode:
npm run start:devThe local PostgreSQL container must be running first:
docker compose up -d db backend
npm run start:devType-check and build:
npm run typecheck
npm run buildThe 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 generateImportant
Do not run prisma migrate dev or prisma migrate reset against a shared database.
All endpoints use the /v1 prefix.
GET /v1/sismos
GET /v1/sismos/statsPagination parameters:
page: current page, defaults to1.per_page: result count, with a maximum of1000.
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, orf.
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
}
}POST /v1/sismos/:sismo_id/reportsExample:
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
Register a device:
POST /v1/devicescurl -X POST 'http://localhost:3001/v1/devices' \
-H 'Content-Type: application/json' \
-d '{"fcm_token":"token-from-firebase-messaging"}'List devices:
GET /v1/devicesDelete a device:
DELETE /v1/devices/:idAdministrative operations require:
X-Admin-Token: <ADMIN_TOKEN>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.
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.
npm run typecheck
npm run buildDocker images can be built with:
docker build -f Dockerfile.dev -t telurify-api-nest:development .
docker build -f Dockerfile -t telurify-api-nest:production .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.0The 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 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 theDockerfile, which remains exclusive to Docker/Compose and GHCR deployments. - Prisma Client is generated automatically: the
postinstallscript runsprisma generateon every install, on Vercel and locally. - Vercel sets
NODE_ENV=productionautomatically;PORTis managed by Vercel. - The
VERCELenvironment variable enablestrust proxyso rate limiting sees the real client IP. Vercel overwritesX-Forwarded-Forto prevent spoofing. - Import the repository in Vercel or run
npx vercel --prod. - Do not use
npx vercel devwith this app: its dev runtime transpiles TypeScript with tsx/esbuild, which does not emitdesign:paramtypesmetadata, so Nest dependency injection resolves every constructor as empty and requests fail withCannot read properties of undefined. Keep usingdocker compose up,npm run start:dev, ornode dist/main.jsfor local development. - To validate the exact production artifact locally:
npx vercel build --prodand thennode .vercel/output/functions/index.func/src/main.jswith the production environment variables.
This project is distributed under the MIT License. See LICENSE.