Skip to content

🍔 AI-powered chef assistant that improves your recipes using your own data built with NestJS

License

Notifications You must be signed in to change notification settings

eiberham/superchef

Repository files navigation

Table of Contents

  1. Introduction
  2. Routes
  3. Authentication & Security
  4. Observability & Distributed Tracing
  5. Async Processing with RabbitMQ
  6. Caching (Redis)
  7. User Preferences
  8. AI Recipe Assistant
  9. Project setup
  10. Environment variables
  11. Compile and run the project
  12. Run tests
  13. Deployment
  14. License

SuperChef

superchef

GitHub GitHub code size in bytes GitHub top language GitHub last commit GitHub stars GitHub workflow status

SuperChef is an AI-powered chef assistant designed to analyze existing recipes, suggest meaninful improvements, and help you create better dishes using your current ingredients.

It works on top of your current database, providing practical, cooking-focused recommendations rather than generic advice.

TLDR features:

  • Real world backend concerns
  • Async workflows
  • Security best practices
  • Clean NestJS architecture
  • Pragmatic use of message queue

Routes

All API endpoints are documented using Swagger (OpenAPI).

Once the application is running, the interactive API documentation is available at:

  • GET /apis

The Swagger UI provides request/resoponse schemas, parameters, and example payloads for each endpoint.

Below is a high level overview of the available routes:

VerbResourceDescriptionScopeRole Access
POST/auth/loginSuperchef sign inPublicAdmin, Viewer
POST/auth/refreshToken refreshProtectedAdmin, Viewer
POST/auth/logoutSign outProtectedAdmin, Viewer
GET/ingredientsGet ingredients listProtectedAdmin, Viewer
GET/ingredients/:idGet a single ingredientProtectedAdmin, Viewer
POST/ingredientsCreate an ingredientProtectedAdmin, Viewer
PUT/ingredients/:idUpdate an ingredientProtectedAdmin, Viewer
DELETE/ingredients/:idDelete ingredientProtectedAdmin, Viewer
GET/recipesGet the recipes listProtectedAdmin, Viewer
GET/recipes/:idGet a single recipeProtectedAdmin, Viewer
POST/recipesCreate a recipeProtectedAdmin, Viewer
PUT/recipes/:idUpdate a recipeProtectedAdmin, Viewer
DELETE/recipes/:idDelete a recipeProtectedAdmin, Viewer
GET/usersGet users listProtectedAdmin
GET/users/:idGet a single userProtectedAdmin
POST/usersCreate a userProtectedAdmin
PUT/users/:idUpdate a userProtectedAdmin
DELETE/users/:idDelete a userProtectedAdmin
POST/chatSends a message to the superchef agentProtectedAdmin

Authentication & Security

JWT-based Authentication

  • Stateless authentication using JWT access tokens
  • Tokens are issued on login and required for protected routes
  • Designed to be compatible with API clients and frontends.

Role-Based Access Control (RBAC)

  • Users can have one or more roles
  • Example roles:
    • admin
    • viewer

RBAC is applied at the route level, ensuring fine grained authorization.

Route Protection

  • Global authentication guard ensures all protected routes require a valid JWT.
  • Public routes are explicitly marked.
  • Authorization logic is separated from controllers.

Rate Limiting

  • Built-in rate limiter to protect the API from abuse.
  • Prevents excessive requests to sensitive endpoints
  • Configurable limits per route or globally.

Observability & Distributed Tracing

This project implements a high-level observability pattern using OpenTelemetry and Honeycomb. Instead of traditional isolated logs, we use Distributed Tracing to correlate every log entry with a specific request flow.

Key Features

  • Log Correlation: Every log entry is automatically enriched with a traceId and spanId, allowing for end-to-end debugging.

  • Span Events: Application logs are pushed to Honeycomb as "Span Events," providing a millisecond-accurate timeline of events within a request.

  • Automatic Context Propagation: Tracing context is maintained across asynchronous boundaries and distributed systems (e.g., RabbitMQ).

  • Custom Telemetry Logger: A specialized Logger extends the NestJS ConsoleLogger to handle tracing logic without polluting the Business Logic.

superchef

How to use

The system is designed to be transparent for developers. Simply use the standard NestJS Logger service:

private readonly logger = new Logger(AuthService.name);

async handle() {
  this.logger.log('User logged in'); // Automatically appears in Honeycomb's trace timeline
}

Monitoring Dashboard

Traces, errors, and performance metrics are available in Honeycomb. Search by traceId to see the full "waterfall" view of any operation.

Async Processing with RabbitMQ

Event-driven Architecture

  • RabbitMQ is used to handle async workflows
  • Examples:
    • User registration triggers a welcome email
    • Extensible to notifications

Producers & Consumers Separation

  • API publishes domain events
  • Workers consume and process them independently
  • Designed to be monolith-friendly, without premature microservices.

Caching (Redis)

Superchef uses Redis as an in-memory cache to reduce latency and decrease load on the primary PostgreSQL database.

The cache is applied to read-heavy endpoints following the cache-aside pattern:

  • On read:

    • The application first checks redis.
    • If the data is present, it is returned immediately.
    • If not, the data is fetched from PostgreSQL and stored in Redis with a TTL.
  • On write:

    • Data is persisted synchronously to PostgreSQL.
    • Related cache keys are invalidated to guarantee consistency.

This approach keeps PostgreSQL as the sigle source of thruth while improving response times for frequent reads.

User Preferences

Each user can configure dietary preferences that are stored as JSON object inside the user table. Suported fields:

  • diet: "none" | "vegetarian" | "vegan" | "omnivore"
  • alergies: string[]

AI Recipe Assistant

Superchef includes an AI-powered assistant via the /chat endpoint, that helps users improve existing recipes by suggesting variations, optimizations, or substitutions based on natural language prompts.

The assistant is implemented as a backend agent powered by OpenAI and orchestrated server side.

All suggestions are generated in the context of a real recipe stored in the database.

Stripe Integration

Superchef integrates with Stripe for subscription management, allowing users to subscribe to a basic plan and access enhanced features.

Features

  • Checkout Session Creation: Create Stripe Checkout sessions for subscription purchases
  • Webhook Processing: Handle Stripe webhook events (checkout.session.completed)
  • Subscription Management: Automatically update subscription status and billing periods
  • Customer Management: Create and manage Stripe customers linked to user accounts

Supported Webhook Events

Event Description Action
checkout.session.completed Checkout completed successfully Updates subscription status, billing period, and user access
------------------------------- ------------------------------- ------------------------------------------------------------
customer.subscription.deleted Customer unsubscribed. Updates subscription status, billing period, and user access
------------------------------- ------------------------------- ------------------------------------------------------------
invoice.paid Invoice paid successfully. Updates subscription status, billing period, and user access
------------------------------- ------------------------------- ------------------------------------------------------------
invoice.payment.failed. Invoice Payment Failed Updates subscription status, and notifies the user.

Project setup

$ npm install

Environment variables

Create a .env file in the root of your project and add the following env vars:

DATABASE_URL=
OPENAI_API_KEY=
RESEND_API_KEY=
JWT_SECRET=
LOG_LEVEL=["log", "error", "warn", "debug", "verbose"]
REDIS_HOST=
REDIS_PORT=
REDIS_USERNAME=
REDIS_PASSWORD=
STRIPE_API_KEY=
HONEYCOMB_API_KEY=

Compile and run the project

# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod

Run tests

# unit tests
$ npm run test

Deployment

When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the deployment documentation for more information.

If you are looking for a cloud-based platform to deploy your NestJS application, check out Mau, our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:

$ npm install -g @nestjs/mau
$ mau deploy

With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

🍔 AI-powered chef assistant that improves your recipes using your own data built with NestJS

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published