A comprehensive NestJS backend application that provides weather information through REST and GraphQL interfaces, with robust features including:
- Third-party weather API integration
- User authentication
- Favorite locations management
- Caching mechanisms
- Rate limiting
- Background job synchronization
- Backend Framework: NestJS
- Database: PostgreSQL
- ORM: TypeORM
- Caching: Redis
- Authentication: JWT
- API Types: REST & GraphQL
- Job Queue: Bull
- Rate Limiting: NestJS Throttler
- Node.js (v20.x or later)
- npm (v10.x or later)
- PostgreSQL (v12.x or higher)
- Redis
PORT: Server listening port (default: 8080)CLIENT: Frontend application URL
JWT_SECRET: Secret key for JWT token generationACCESS_TOKEN_VALIDITY_DURATION_IN_SEC: Token expiration time
DATABASE_HOST: PostgreSQL database hostDATABASE_PORT: Database portDATABASE_USER: Database usernameDATABASE_PASS: Database passwordDATABASE_NAME: Database name
WEATHER_API_KEY: WeatherAPI.com API keyWEATHER_API_CURRENT_CITY_URL: Current weather endpointWEATHER_API_CITY_FORECAST_URL: Forecast endpoint
REDIS_URL: Complete Redis connection URLREDIS_HOST: Redis server hostREDIS_PORT: Redis server portREDIS_USER: Redis usernameREDIS_PASS: Redis passwordREDIS_DB: Redis database numberREDIS_TTL: Cache time-to-live (default: 1 minute)
-
PUBLIC_RATE_LIMIT_TTL: Public endpoints time-to-live (default: 1 minute) -
PUBLIC_RATE_LIMIT: Public endpoints rate limit -
AUTH_RATE_LIMIT_TTL: Authenticated endpoints time-to-live (default: 1 minute) -
AUTH_RATE_LIMIT: Authenticated endpoints rate limit -
WEATHER_RATE_LIMIT_TTL: Weather query endpoints time-to-live (default: 1 minute) -
WEATHER_RATE_LIMIT: Weather query endpoints rate limit -
FORECASE_RATE_LIMIT_TTL: Forecast query endpoints time-to-live (default: 1 minute) -
FORECASE_RATE_LIMIT: Forecast query endpoints rate limit -
Separate rate limits for:
- Public endpoints
- Authenticated routes (locations endpoints are protected)
- Weather-specific endpoints
- Forecast endpoints
WEATHER_SYNC_CRON: Cron schedule for weather data synchronization
- Clone the repository
git clone https://github.com/mr-georgie/weatherapi.git
cd weatherapi- Install dependencies
npm install- Create .env file
cp .env.sample .env
# Edit .env with your specific configurations# Generate migrations
npm run migration:generate
# Run migrations
npm run migration:run
# Revert last migration
npm run migration:revert# Development mode
npm run start:dev
# Production mode
npm run start:prod# Run unit tests
npm run test
# Run test coverage
npm run test:cov- Swagger documentation available at:
http://localhost:8080/api- GraphQL Playground:
http://localhost:8080/graphql-
Motivation: Provide flexible API access
-
Implementation:
- GraphQL for weather data fetching
- REST for authentication and location management
-
Benefits:
- Precise Data Retrieval:
- Weather forecast data is large and complex
- GraphQL allows clients to request exactly the data they need
- Prevents over-fetching or under-fetching of information
- Significant bandwidth savings
- Lower data transfer costs
- Flexible Schema Design
- Precise Data Retrieval:
-
Sample Query
query {
getCurrentCityWeather(city: "London") {
# Client can select only required fields
location {
name
country
lat
lon
region
tz_id
}
current {
temp_c
}
}
}-
Why REST for Authentication:
- More straightforward session management
- Industry standard for auth flows
- Better support for HTTP-only cookies
- Clearer security headers handling
- Simpler implementation of token-based auth
- More intuitive error handling for auth failures
- Simpler request/response cycle
- Easier to implement middleware for auth check
-
Why REST for Location Management:
- Natural fit for CRUD operations
- Clear HTTP method mapping:
- POST: Create new location
- GET: Retrieve locations
- DELETE: Remove location
- Approach: Redis-based caching with differentiated TTL
- Rationale:
- Shorter TTL for current weather (smaller dataset)
- Longer TTL for forecast data
- Performance Optimization:
- Reduced external API calls
- Improved response times
- Cost-effective API usage
- Authentication Mechanism: JWT-based
- Security Enhancements:
- Password hashing
- UUID for primary keys (prevents IDOR)
- Soft deletion of records
- Recommended HTTP-only cookies for production
- Input Sanitization:
- Transform inputs to lowercase
- DTO validation
- Technology: Bull job queue
- Purpose:
- Periodic weather data synchronization
- Configurable cron jobs
- Efficient background processing
- Type Safety:
- Extensive use of interfaces
- Enums to replace magic strings
- Modularization:
- Dependency Injection (DI)
- Service-specific exception handling
- Logging:
- Comprehensive logging
- Improved debugging
- Enhanced monitoring capabilities
- Functionality:
- Centralized environment variable management
- Default value setting
- Graceful error handling during configuration
- Focus Areas:
- Core services (Weather Service)
- API data services
- Authentication flows
- Purpose:
- Ensure core functionality
- Validate critical components
- Implementation: Standard API response object
- Benefits:
- Consistent response structure
- Easier client-side parsing
- Improved error handling
- Implement HTTP-only cookies
- Add token rotation and refresh mechanisms
- Integrate with log management systems
- Implement Caching invalidation
- Implement more comprehensive test coverage
- Add advanced caching strategies
- Authentication on GraphQL endpoints
- Implement advanced GraphQL features