### Install Dependencies and Start Development Server Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/README.md Installs project dependencies using Bun and starts the development server with automatic file watching for hot reloads. ```bash bun install # Install dependencies bun run start:dev # Start with file watching # Make changes, changes reload automatically ``` -------------------------------- ### Initial Project Setup Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Clones the repository, navigates into the directory, and installs project dependencies using Bun. ```bash git clone https://github.com/dkb0512/nest-bun-docker.git cd nest-bun-docker bun install ``` -------------------------------- ### Start with Docker Compose Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Starts the application services defined in a docker-compose.yml file. ```bash docker-compose up ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Use these commands to clone the project repository and install all necessary dependencies using Bun. ```bash git clone https://github.com/dkb0512/nest-bun-docker.git cd nest-bun-docker bun install ``` -------------------------------- ### Process Monitoring with PM2 Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Commands for installing, starting, viewing logs, and stopping a Node.js process using the PM2 process manager. ```bash npm install -g pm2 pm2 start ./nest-bun --name "nest-bun" pm2 logs pm2 stop nest-bun ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/README.md Installs project dependencies using the Bun package manager. This is the primary command for setting up the project. ```bash bun install ``` -------------------------------- ### List Installed Packages with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md This command displays a tree of all packages currently installed in your project. ```bash bun pm ls ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Ensures all project dependencies are installed using Bun. Run this command when encountering 'Module not found' errors. ```bash # Ensure dependencies are installed bun install ``` -------------------------------- ### listen() Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/nest-factory.md Starts the HTTP server on the specified port and hostname. ```APIDOC ## listen() listen ### Description Starts the HTTP server on the specified port and hostname. ### Method `listen` ### Parameters #### Path Parameters - **port** (number | string) - Required - Port number for the server - **hostname** (string) - Optional - Hostname to bind to (default: 0.0.0.0) - **listeningListener** (Function) - Optional - Callback when server is listening ### Request Example ```typescript const app = await NestFactory.create(AppModule); await app.listen(3000); ``` With hostname: ```typescript await app.listen(3000, 'localhost'); ``` With callback: ```typescript await app.listen(3000, undefined, () => { console.log('Server is listening'); }); ``` ``` -------------------------------- ### Start Application in Debug Mode Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/PROJECT.md Starts the application with debug mode enabled. Note that this command requires Node.js and the NestJS CLI to be installed. ```bash bun run start:debug ``` -------------------------------- ### JavaScript Fetch API Example Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/app-controller.md Shows how to call the root path endpoint using the browser's Fetch API. This example logs the response text to the console. ```javascript fetch('http://localhost:3000/') .then(response => response.text()) .then(message => console.log(message)); ``` -------------------------------- ### GET / Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/API_SUMMARY.md Handles GET requests to the root endpoint and returns a greeting message. ```APIDOC ## GET / ### Description Handles GET requests to the root endpoint and returns a greeting message. ### Method GET ### Endpoint / ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **message** (string) - A greeting message. #### Response Example { "message": "Hello From Nest-Bun" } ``` -------------------------------- ### HTTP API Endpoint Example Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/README.md Details a single GET endpoint for the project, including its path, response, status, and content type. ```http GET / ├── Returns: "Hello From Nest-Bun" ├── Status: 200 OK ├── Content-Type: text/plain └── No authentication required ``` -------------------------------- ### GET / Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/app-controller.md Handles GET requests to the root path and returns a greeting message by delegating to the AppService. ```APIDOC ## GET / ### Description Handles GET requests to the root path and returns a greeting message. ### Method GET ### Endpoint / ### Parameters None ### Request Body None ### Response #### Success Response (200) - **message** (string) - A greeting message, typically 'Hello From Nest-Bun'. ### Response Example ``` Hello From Nest-Bun ``` ``` -------------------------------- ### Start Application in Development Mode Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/PROJECT.md Use this command to start the NestJS application with Bun, enabling watch mode and hot reloading for a smooth development experience. ```bash bun run start:dev ``` -------------------------------- ### Retrieve Greeting Message using curl Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/endpoints.md Use this command-line example to fetch the greeting message from the root endpoint. It demonstrates a simple GET request to the application. ```bash curl http://localhost:3000/ # Output: Hello From Nest-Bun ``` -------------------------------- ### Install Exact Dependencies with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/configuration.md Installs the exact versions of dependencies as specified in the bun.lockb lock file. This ensures reproducible builds using the Bun package manager. ```bash bun install # Installs exact versions from bun.lockb ``` -------------------------------- ### Production Server Start (Compiled) Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Runs the compiled production application. This can be executed directly as an executable or via a Bun script. ```bash ./nest-bun ``` ```bash bun run start:app ``` -------------------------------- ### Dependency Injection Chain Example Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/nest-factory.md Illustrates the sequence of dependency injection and instantiation that occurs when `NestFactory.create()` is called in a Nest-Bun environment. This process involves scanning modules, building the dependency graph, and injecting instances. ```plaintext NestFactory.create(AppModule) → Instantiate AppService (no dependencies) → Instantiate AppController (depends on AppService) → Inject AppService into AppController constructor → Register routes from AppController → Return application instance ``` -------------------------------- ### HTTP Server Initialization Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/bootstrap.md Starts the HTTP server, binding it to the specified port (3000 in this case). Once listening, the application is ready to handle incoming requests. ```typescript await app.listen(3000); ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Installs the necessary dependencies for testing your NestJS application with Jest. ```bash bun add -D @nestjs/testing jest ts-jest @types/jest ``` -------------------------------- ### Specify Trusted Dependencies in package.json Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/configuration.md Lists dependencies that are allowed to run install scripts during 'bun install'. This is typically used for packages with native bindings or build steps. ```json { "trustedDependencies": [ "@nestjs/core", "protobufjs" ] } ``` -------------------------------- ### Lazy Loading Modules Example Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Example of how to structure your AppModule to import other modules, which can be lazy-loaded for larger applications. ```typescript import { Module } from '@nestjs/common'; import { CatsModule } from './cats/cats.module'; import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ CatsModule, ConfigModule.forRoot(), ], }) export class AppModule {} ``` -------------------------------- ### Unit Test Example Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/API_SUMMARY.md Demonstrates how to unit test components by manually instantiating services and controllers. This approach is suitable for verifying individual component logic. ```typescript const service = new AppService(); const controller = new AppController(service); expect(controller.getBun()).toBe('Hello From Nest-Bun'); ``` -------------------------------- ### Conventional Commit Example Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Example of a commit message following the conventional commits specification. ```bash git commit -m "type(scope): description" Types: feat, fix, docs, style, refactor, perf, test, chore ``` -------------------------------- ### Listen with Callback Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/nest-factory.md Starts the HTTP server on the specified port and executes a callback function once the server is listening. The hostname can be explicitly set to undefined if only the callback is needed. ```typescript await app.listen(3000, undefined, () => { console.log('Server is listening'); }); ``` -------------------------------- ### Root Greeting Endpoint Response Example Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/endpoints.md This is an example of the HTTP response received when accessing the root greeting endpoint. It shows the status code, content type, and the plain text body. ```http HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Content-Length: 19 Hello From Nest-Bun ``` -------------------------------- ### Complete Bootstrap Function Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/bootstrap.md This is the main entry point for a NestJS application. It creates the application instance and starts the HTTP server listening on port 3000. ```typescript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } ootstrap(); ``` -------------------------------- ### Run Development Server with Custom Environment Variables Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Set custom PORT and HOST environment variables when running the development server. This example sets the port to 8080 and the host to localhost. ```bash PORT=8080 HOST=localhost bun run start:dev ``` -------------------------------- ### Check Bun Version Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Display the currently installed version of Bun. This is useful for troubleshooting compatibility issues or ensuring you are using a specific version. ```bash bun --version ``` -------------------------------- ### Start Services with Docker Compose in Background Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Starts all services defined in the docker-compose.yml file in detached mode. The services will run in the background. ```bash docker-compose up -d ``` -------------------------------- ### Run Application with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/README.md Starts the NestJS application using Bun. Provides options for development (watch mode), production, and compiled-app modes. ```bash bun run start:dev ``` ```bash bun run start:prod ``` ```bash bun run start:app ``` -------------------------------- ### AppService getBun() Usage Example (Manual Instantiation) Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/app-service.md Demonstrates how to manually instantiate AppService and call its getBun() method. This is useful for understanding the method's output outside of a NestJS context. ```typescript import { AppService } from './app.service'; // When injected into a controller: const appService = new AppService(); const message = appService.getBun(); console.log(message); // Output: "Hello From Nest-Bun" ``` -------------------------------- ### GET / Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/endpoints.md Returns a greeting message indicating the application is running on Nest-Bun. This is the primary endpoint for checking application status. ```APIDOC ## GET / ### Description Returns a greeting message indicating the application is running on Nest-Bun. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **Body** (string) - Literal string: "Hello From Nest-Bun" ### Response Example ``` HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Content-Length: 19 Hello From Nest-Bun ``` ``` -------------------------------- ### GET / Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/API_SUMMARY.md Retrieves a simple greeting message from the application. ```APIDOC ## GET / ### Description Retrieves a simple greeting message from the application. ### Method GET ### Endpoint / ### Response #### Success Response (200) - Returns: Plain text string "Hello From Nest-Bun" ### Request Example ```bash curl http://localhost:3000/ ``` ### Response Example ``` Hello From Nest-Bun ``` ``` -------------------------------- ### Verify Application with Curl Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/INDEX.md Verifies the running application by sending an HTTP GET request to the root path. ```bash curl http://localhost:3000/ ``` -------------------------------- ### Dockerfile for NestJS with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md This Dockerfile sets up an environment to build and run a NestJS application using Bun. It includes steps for installing dependencies, building the application, and exposing the necessary port. ```dockerfile FROM oven/bun:latest WORKDIR /app COPY package.json bun.lockb ./ RUN bun install COPY src ./src COPY tsconfig.json nest-cli.json ./ RUN bun run build FROM oven/bun:latest WORKDIR /app COPY --from=0 /app/nest-bun ./ EXPOSE 3000 CMD ["./nest-bun"] ``` -------------------------------- ### Curl GET Request to Root Path Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/app-controller.md Demonstrates how to make a GET request to the application's root path using curl. This is useful for testing the endpoint directly from the command line. ```bash curl -X GET http://localhost:3000/ ``` -------------------------------- ### Check for Outdated Packages with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Run this command to identify packages that have newer versions available than what is currently installed. ```bash bun outdated ``` -------------------------------- ### app.listen() API Signature Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/API_SUMMARY.md This is the signature for the `app.listen()` method, used to start the HTTP server. It accepts the port number, an optional hostname, and a callback function. ```typescript listen( port: number, hostname?: string, callback?: () => void ): Promise ``` -------------------------------- ### Check Docker Version Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Displays the installed Docker version. Useful for ensuring compatibility or diagnosing Docker-related issues. ```bash # Check Docker version docker --version ``` -------------------------------- ### Retrieve Greeting Message using Python requests Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/endpoints.md This Python example uses the requests library to fetch the greeting message from the root endpoint. It prints the response text. ```python import requests response = requests.get('http://localhost:3000/') print(response.text) # Hello From Nest-Bun ``` -------------------------------- ### GitHub Actions CI Workflow Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md This workflow automates the build and test process on push or pull request events. It checks out code, sets up Bun, installs dependencies, and runs format, lint, build, and Docker build steps. ```yaml name: Build on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: oven-sh/setup-bun@v1 - run: bun install - run: bun run format --check - run: bun run lint - run: bun run build - name: Test Docker build run: docker build -t nest-bun . ``` -------------------------------- ### Create and Listen on Port Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/nest-factory.md Starts the HTTP server on the specified port. Use this to make your NestJS application accessible over the network. ```typescript const app = await NestFactory.create(AppModule); await app.listen(3000); console.log('Server started'); ``` -------------------------------- ### Reinstall Dependencies with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Remove lock files and node_modules, then reinstall all project dependencies. This can resolve issues caused by corrupted installations or dependency conflicts. ```bash rm -rf bun.lockb node_modules bun install ``` -------------------------------- ### Retrieve Greeting Message using browser JavaScript Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/endpoints.md This asynchronous JavaScript example demonstrates fetching the greeting message directly in a browser environment using the fetch API. ```javascript const response = await fetch('http://localhost:3000/'); const message = await response.text(); console.log(message); // "Hello From Nest-Bun" ``` -------------------------------- ### getBun Method Signature Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/app-controller.md Maps GET requests to the root path ('/'). It delegates the business logic to the injected AppService. ```typescript @Get() getBun(): string ``` -------------------------------- ### AppController Using AppService Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/app-service.md Shows how AppService is injected into AppController using constructor injection and how its getBun() method is called to handle GET requests. ```typescript import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getBun(): string { return this.appService.getBun(); } } ``` -------------------------------- ### Graceful Bootstrap with Error Handling Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/bootstrap.md This example shows a robust way to bootstrap a NestJS application, including a try-catch block to handle potential errors during application creation and listening, logging the error, and exiting the process. ```typescript async function bootstrap() { try { const app = await NestFactory.create(AppModule); await app.listen(3000); console.log('Application listening on port 3000'); } catch (error) { console.error('Failed to bootstrap application:', error); process.exit(1); } } bootstrap(); ``` -------------------------------- ### Build and Run Compiled Application Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/README.md Builds the executable and then runs the compiled application for the fastest startup. ```bash bun run build # Build executable ./nest-bun # Run compiled app ``` -------------------------------- ### Build, Dockerize, and Run Production Application Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/README.md Builds an optimized executable, creates a Docker image, and runs the containerized application, exposing it on port 3000. ```bash bun run build:minify # Create optimized executable docker build -t app . # Build Docker image docker run -p 3000:3000 app # Run container ``` -------------------------------- ### @Get() with Specific Path Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DECORATORS.md Demonstrates how to specify a route path for the @Get() decorator. The full route is formed by combining the @Controller path and the @Get path. ```typescript @Controller('users') export class UsersController { @Get(':id') getUser(@Param('id') id: string) { // ... } } ``` -------------------------------- ### Measure Application Startup Time Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Measures the time it takes for the NestJS application to start up and begin listening on the specified port. This code snippet should be added to your main application file (e.g., src/main.ts). ```typescript // In src/main.ts import { performance } from 'perf_hooks'; const start = performance.now(); async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); const end = performance.now(); console.log(`Startup time: ${(end - start).toFixed(2)}ms`); } ``` -------------------------------- ### Compare Startup Times with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md This comparison shows the difference in startup performance between running a NestJS app in development mode with Bun (transpilation) and running a compiled executable. ```bash # Bun development (with TypeScript transpilation) time bun run start:prod # Example: 450ms startup # Compiled executable (no transpilation) time ./nest-bun # Example: 50ms startup ``` -------------------------------- ### Basic @Get() Decorator Usage Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DECORATORS.md Maps a controller method to handle GET requests to the root path. NestJS automatically combines the @Controller path with the @Get path to form the full route. ```typescript import { Controller, Get } from '@nestjs/common'; @Controller() export class AppController { @Get() getBun(): string { return this.appService.getBun(); } } ``` -------------------------------- ### Compare Build Sizes with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md These commands demonstrate how to build a NestJS application with Bun and compare the resulting binary sizes. A minified build significantly reduces the executable size. ```bash # Standard build bun run build ls -lh ./nest-bun # ~80 MB # Minified build bun run build:minify ls -lh ./nest-bun # ~40 MB ``` -------------------------------- ### Building Release Artifacts Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Commands to build an optimized executable using Bun and create a compressed tar archive for the release. ```bash # Build optimized executable bun run build:minify # Create release archive tar -czf nest-bun-1.0.0.tar.gz ./nest-bun ``` -------------------------------- ### Instantiate and Use AppService Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/API_SUMMARY.md Demonstrates how to directly instantiate AppService and call its methods, or how it can be injected into other classes like controllers. ```typescript import { AppService } from './app.service'; const service = new AppService(); const message = service.getBun(); // "Hello From Nest-Bun" @Controller() export class MyController { constructor(private readonly appService: AppService) {} } ``` -------------------------------- ### Build Docker Image Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Builds a Docker image for the Nest-Bun application. ```bash docker build -t nest-bun:latest . ``` -------------------------------- ### @Get() Decorator Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DECORATORS.md Maps a controller method to handle HTTP GET requests. It can accept an optional path string or an array of strings to define specific routes. ```APIDOC ## @Get() ### Description Maps a controller method to HTTP GET request handlers. ### Method GET ### Endpoint Defined by the combination of the @Controller path and the @Get path. ### Parameters #### Path Parameters - **path** (string | string[]) - Optional - Route path relative to the @Controller path. Defaults to an empty string. ### Request Example ```typescript @Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { // ... } } ``` This would create a route like: GET /users/:id ### Response #### Success Response (200) - The return value of the decorated method is automatically serialized to the HTTP response. #### Response Example ```typescript @Get() getMessage(): string { return 'Hello'; // Sent as plain text } @Get('json') getJson(): {message: string} { return {message: 'Hello'}; // Sent as JSON } ``` ### Behavior - Registers the decorated method as a route handler. - Extracts the HTTP method (GET) from the decorator. - Combines @Controller path with @Get path to form the full route. - Invokes the method when a GET request matches the route. - Serializes the return value to the HTTP response. ### HTTP Status Code - Defaults to HTTP 200. - Can be customized using the @HttpCode() decorator. ```typescript @Get() @HttpCode(201) create(): string { return 'Created'; } ``` ``` -------------------------------- ### Project Directory Structure Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/README.md Illustrates the file and directory layout of the nest-bun-docker project. ```tree nest-bun-docker/ ├── src/ │ ├── main.ts Entry point │ ├── app.module.ts Root module │ ├── app.controller.ts HTTP routes │ └── app.service.ts Business logic ├── package.json Dependencies ├── tsconfig.json TypeScript config └── Dockerfile Docker setup ``` -------------------------------- ### Build Executable with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Compiles and minifies the application into a single executable file using Bun. Use this to build with limited parallelism if encountering 'Out of memory' errors. ```bash # Build with limited parallelism bun build ./src/main.ts --compile --minify --target bun --outfile=nest-bun ``` -------------------------------- ### Return Value Serialization with @Get() Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DECORATORS.md Illustrates how NestJS automatically serializes the return value of a controller method decorated with @Get(). Plain strings are sent as plain text, while objects are sent as JSON. ```typescript @Get() getMessage(): string { return 'Hello'; // Sent as plain text } @Get('json') getJson(): {message: string} { return {message: 'Hello'}; // Sent as JSON } ``` -------------------------------- ### Project Structure Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/PROJECT.md Illustrates the directory layout for the Nest-Bun project, including source files, configuration, and Docker-related files. ```tree nest-bun-docker/ ├── src/ │ ├── main.ts # Application bootstrap entry point │ ├── app.module.ts # Root NestJS module │ ├── app.controller.ts # HTTP request handlers │ └── app.service.ts # Business logic service ├── package.json # Project dependencies and scripts ├── tsconfig.json # TypeScript configuration ├── nest-cli.json # NestJS CLI configuration ├── Dockerfile # Docker containerization ├── docker-compose.yml # Docker Compose configuration └── bun.lockb # Bun dependency lock file ``` -------------------------------- ### Docker Tagging and Rollback Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Demonstrates tagging a Docker image with a specific version and pushing it to a registry, along with a command to run a previous version. ```bash # Tag current build docker tag nest-bun:latest nest-bun:v1.0.0 # Push to registry docker push myregistry/nest-bun:v1.0.0 # Rollback to previous version docker run -p 3000:3000 myregistry/nest-bun:v0.9.0 ``` -------------------------------- ### Run Pre-compiled Application Executable Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/PROJECT.md Executes the pre-compiled application binary located at './nest-bun'. This command is used to run the production-ready application. ```bash bun run start:app ``` -------------------------------- ### Test New Endpoint with Curl Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/INDEX.md Tests a newly added endpoint by sending an HTTP GET request to a specific path. ```bash curl http://localhost:3000/new-path ``` -------------------------------- ### Analyze Bundle Size Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Use this command to analyze the bundled output of your application. ```bash bun build ./src/main.ts --analyze ``` -------------------------------- ### Build Application for Production Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/PROJECT.md Compiles and builds the NestJS application into a standalone Bun executable. The output file will be named './nest-bun'. ```bash bun run build ``` -------------------------------- ### Configure Incremental Compilation Build Times Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/TYPESCRIPT_CONFIG.md Demonstrates the performance impact of incremental compilation. The first build takes standard time, while subsequent builds with no changes or only minor changes are significantly faster due to caching. ```bash # First build: 3 seconds bunx tsc # Second build (no changes): 100ms (cached) bunx tsc # Third build (one file changed): 500ms (incremental) bunx tsc ``` -------------------------------- ### AppService with Singleton Scope Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DECORATORS.md An example of an AppService decorated with @Injectable, intended for singleton scope and managed by the application's dependency injection system. ```typescript @Injectable() export class AppService { constructor() {} getBun(): string { return 'Hello From Nest-Bun'; } } ``` -------------------------------- ### Incremental Strict Checking Progression Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/TYPESCRIPT_CONFIG.md Gradually enable stricter TypeScript checks by activating options one by one, starting with `strictNullChecks` and progressing to `strict`. ```json { "compilerOptions": { "strictNullChecks": true } } ``` ```json { "compilerOptions": { "noImplicitAny": true } } ``` ```json { "compilerOptions": { "strictBindCallApply": true } } ``` ```json { "compilerOptions": { "strict": true } } ``` -------------------------------- ### Configure Server Port and Host with Environment Variables Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/configuration.md Sets the server port and host using environment variables, falling back to default values if not provided. This allows for dynamic configuration at runtime. ```typescript const port = parseInt(process.env.PORT || '3000', 10); const host = process.env.HOST || 'localhost'; const app = await NestFactory.create(AppModule); await app.listen(port, host); ``` -------------------------------- ### Tagging and Releasing Versions Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Commands to create a Git tag for a new version, push it to origin, and create a corresponding release on GitHub. ```bash # Create version tag git tag -a v1.0.0 -m "Release version 1.0.0" git push origin v1.0.0 # Create release in GitHub gh release create v1.0.0 --notes "Initial release" ``` -------------------------------- ### Run Compiled Executable with Custom Environment Variables Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Set custom PORT and HOST environment variables when running the compiled application binary. This allows for dynamic configuration of the server's listening address and port. ```bash PORT=8080 ./nest-bun ``` -------------------------------- ### Bun Build Script for Compilation Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/configuration.md Defines a script in package.json to build the application using Bun's bundler and compiler. It compiles the entry point to a standalone executable. ```json { "scripts": { "build": "bun build ./src/main.ts --compile --target bun --outfile=nest-bun", "build:minify": "bun build ./src/main.ts --compile --minify --target bun --outfile=nest-bun" } } ``` -------------------------------- ### Import Core Decorators from @nestjs/common Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/API_SUMMARY.md Imports essential decorators like Controller, Get, Module, and Injectable from the @nestjs/common package, which are fundamental for building NestJS applications. ```typescript import { Controller, Get, Module, Injectable } from '@nestjs/common'; ``` -------------------------------- ### Other HTTP Method Decorators Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DECORATORS.md Lists common NestJS decorators for mapping controller methods to different HTTP request methods. These decorators follow a similar pattern to @Get(). ```typescript @Post() // POST request @Put() // PUT request @Delete() // DELETE request @Patch() // PATCH request @Head() // HEAD request @Options() // OPTIONS request ``` -------------------------------- ### Clean and Rebuild Project with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Remove previous build artifacts and then rebuild the project using Bun. This is a common step to resolve build failures. ```bash rm -f nest-bun bun run build ``` -------------------------------- ### Add Console Logging with NestJS Logger Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Example of using the NestJS Logger service to log messages within a controller. Ensure the AppController and AppService are correctly set up. ```typescript import { Controller, Get, Logger } from '@nestjs/common'; @Controller() export class AppController { private readonly logger = new Logger(AppController.name); @Get() getBun(): string { this.logger.log('getBun() called'); return this.appService.getBun(); } } ``` -------------------------------- ### Build Application with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/README.md Builds the NestJS application using Bun. Supports both standard and minified build modes. ```bash bun run build ``` ```bash bun run build:minify ``` -------------------------------- ### Build NestJS Application Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/configuration.md Compiles the NestJS application into an executable using Bun. ```bash bun build ./src/main.ts --compile --target bun --outfile=nest-bun ``` -------------------------------- ### Add Health Check Endpoint to NestJS App Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md This TypeScript code adds a '/health' GET endpoint to a NestJS controller. It returns a status and the current timestamp, useful for external monitoring. ```typescript import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getBun(): string { return this.appService.getBun(); } @Get('health') getHealth(): {status: string; timestamp: string} { return { status: 'ok', timestamp: new Date().toISOString(), }; } } ``` -------------------------------- ### Structured Logging Configuration Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Modifies the NestJS application's logger to output structured logs including debug, error, warn, and log levels. Includes a timestamped server start message. ```typescript async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: ['debug', 'error', 'warn', 'log'], }); await app.listen(3000); console.log(`[${new Date().toISOString()}] Server started on port 3000`); } ``` -------------------------------- ### Run Production with Custom Environment Variables Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Set custom PORT and HOST environment variables when running the application in production mode. This overrides the default values and configures the server accordingly. ```bash PORT=8080 HOST=localhost bun run start:prod ``` -------------------------------- ### VS Code Editor Settings for Formatting and Linting Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Configure Visual Studio Code to automatically format code on save and fix ESLint issues. Ensure Prettier and ESLint extensions are installed. ```json { "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.codeActionsOnSave": { "source.fixAll.eslint": true } } ``` -------------------------------- ### Build and Minify NestJS Application Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/configuration.md Compiles and minifies the NestJS application into an executable using Bun. ```bash bun build ./src/main.ts --compile --minify --target bun --outfile=nest-bun ``` -------------------------------- ### Create Nest Application Instance Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/API_SUMMARY.md Used to create and bootstrap a NestJS application instance. Requires importing NestFactory and the root AppModule. ```typescript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; const app = await NestFactory.create(AppModule); ``` -------------------------------- ### Allowing Fallthrough Cases in Switch Statements Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/TYPESCRIPT_CONFIG.md This example demonstrates a switch statement where fallthrough is permitted due to `noFallthroughCasesInSwitch` being set to `false`. This allows cases to execute the code of the subsequent case if no `break` statement is present. ```typescript switch (value) { case 'a': case 'b': doSomething(); break; case 'c': doOther(); // Falls through to default (allowed with false) default: doDefault(); } ``` -------------------------------- ### Build Docker Image with Custom Tag Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Builds the Docker image and tags it with a custom registry and version. Useful for version control and deployment pipelines. ```bash docker build -t myregistry/nest-bun:1.0.0 . ``` -------------------------------- ### Create Application with Static Module Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/nest-factory.md Demonstrates creating a NestJS application instance using a static module class. This is the most common way to define your application's root module. ```typescript @Module({ controllers: [AppController], providers: [AppService], }) export class AppModule {} const app = await NestFactory.create(AppModule); ``` -------------------------------- ### Set Base URL for Module Resolution Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/TYPESCRIPT_CONFIG.md The `baseUrl` option defines the base directory for resolving non-relative module imports. Setting it to `./` allows absolute path imports starting from the project root, simplifying import statements. ```json { "compilerOptions": { "baseUrl": "./" } } ``` ```typescript import { AppService } from 'src/app.service'; ``` -------------------------------- ### Add new route handlers to a NestJS controller Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Define new methods within a controller class and decorate them with HTTP method decorators like @Get(), @Post(), etc., along with route paths. Use decorators like @Param() and @Body() to access request parameters and data. ```typescript @Controller() export class AppController { @Get() getBun(): string { return this.appService.getBun(); } @Get('hello/:name') sayHello(@Param('name') name: string): string { return `Hello ${name}`; } @Post('message') postMessage(@Body() body: {text: string}): {received: string} { return {received: body.text}; } } ``` -------------------------------- ### Project Structure Overview Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/INDEX.md Illustrates the directory and file organization of the NestJS project. Each file serves a specific role in the application's architecture. ```tree src/ ├── main.ts Entry point, bootstraps the application ├── app.module.ts Root module definition ├── app.controller.ts HTTP route handlers └── app.service.ts Business logic service ``` -------------------------------- ### Run Pre-compiled Executable Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/configuration.md Executes the NestJS application using a pre-compiled binary. ```bash ./nest-bun ``` -------------------------------- ### Run Docker Container Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Runs the Docker image as a container, exposing port 3000. ```bash docker run -p 3000:3000 nest-bun:latest ``` -------------------------------- ### Bootstrap Application with AppModule Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/app-module.md Illustrates how to bootstrap a NestJS application using the AppModule. This code is typically found in src/main.ts. ```typescript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Add Production Dependency with Bun Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Use this command to add a package that will be required at runtime. ```bash bun add package-name ``` -------------------------------- ### Handle Application Creation Errors with Async/Await Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/nest-factory.md Implement robust error handling for NestJS application creation and startup using a try...catch block with async/await. This ensures graceful failure and process termination. ```typescript async function bootstrap() { try { const app = await NestFactory.create(AppModule); await app.listen(3000); } catch (error) { console.error('Application initialization failed:', error); process.exit(1); } } ``` -------------------------------- ### Configure Port in Bootstrap Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/bootstrap.md Make the application port configurable using environment variables. Defaults to 3000 if PORT is not set. ```typescript const port = parseInt(process.env.PORT || '3000', 10); await app.listen(port); ``` -------------------------------- ### Run Executable with Debug Output Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Executes the compiled binary with verbose debug output enabled. Useful for troubleshooting runtime issues. ```bash # Run with verbose output BUN_DEBUG=1 ./nest-bun ``` -------------------------------- ### Archiving and Rolling Back Compiled Binaries Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Provides commands for backing up previous compiled binaries and performing a quick rollback by restoring a backup. ```bash # Archive previous builds cp nest-bun nest-bun.backup.v0.9.0 # Quick rollback cp nest-bun.backup.v0.9.0 nest-bun ./nest-bun ``` -------------------------------- ### Create Application with Dynamic Module Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/nest-factory.md Shows how to create a NestJS application using a dynamic module. Dynamic modules allow for more flexible configuration and instantiation of modules. ```typescript const dynamicModule = { module: AppModule, controllers: [AppController], providers: [AppService], }; const app = await NestFactory.create(dynamicModule); ``` -------------------------------- ### NestFactory.create() Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/nest-factory.md Creates a NestJS application instance from a root module. This is the primary method for bootstrapping an HTTP application. ```APIDOC ## NestFactory.create() ### Description Creates a NestJS application instance from a root module. This method is used to bootstrap an HTTP application. ### Method `NestFactory.create(module: Type | DynamicModule, options?: NestApplicationOptions): Promise` ### Parameters #### Module - **module** (Type | DynamicModule) - Required - The root module class or dynamic module configuration. #### Options - **options** (NestApplicationOptions) - Optional - Configuration options for the application, such as CORS, logger, etc. ### Return Type `Promise` - Resolves to a NestJS application instance. ### Usage Example ```typescript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap(); ``` ### Options Parameter Details `NestApplicationOptions` can include: - **cors** (boolean | CorsOptions) - Enable CORS. - **snapshot** (boolean) - Enable snapshot mode. - **preview** (boolean) - Enable preview mode. - **logger** (LoggerService | false) - Custom logger. - **bufferLogs** (boolean) - Buffer logs until app runs. - **abortOnError** (boolean) - Abort if error during init. - **httpsOptions** (HttpsOptions) - HTTPS configuration. ### Example with Options ```typescript const app = await NestFactory.create(AppModule, { logger: ['debug', 'error', 'warn'], cors: true, }); ``` ### Error Scenarios The promise rejects if: - Root module is invalid. - Circular dependency detected. - Required provider not found. - Module initialization throws an error. ``` -------------------------------- ### Application Creation with NestFactory Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/bootstrap.md Creates a NestJS application instance by providing the root module (`AppModule`). This step involves NestJS scanning modules, resolving dependencies, and setting up the application structure. ```typescript const app = await NestFactory.create(AppModule); ``` -------------------------------- ### Run Application on Different Port Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/DEVELOPMENT_GUIDE.md Configure the application to run on an alternative port by setting the PORT environment variable, useful when the default port is occupied. ```bash PORT=3001 bun run start:dev ``` -------------------------------- ### View Logs with Docker Compose Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/BUILD_AND_DEPLOYMENT.md Follows and displays the logs from all services defined in the docker-compose.yml file. Use this for debugging. ```bash docker-compose logs -f ``` -------------------------------- ### Configure Hostname in Bootstrap Source: https://github.com/dkb0512/nest-bun-docker/blob/main/_autodocs/api-reference/bootstrap.md Explicitly bind the application to a specific hostname. Defaults to '0.0.0.0' if not specified. ```typescript await app.listen(3000, 'localhost'); ```