### Danet CLI Setup Source: https://github.com/savory/docs/blob/main/src/overview/first-steps.md Commands to install the Danet CLI and create a new Danet project. Requires Deno version 1.24.3 or higher. ```bash deno install --allow-read --allow-write --allow-run --allow-env -n danet jsr:@danet/cli danet new my-danet-project cd my-danet-project ``` -------------------------------- ### Comprehensive Resource Controller Example Source: https://github.com/savory/docs/blob/main/src/fr/overview/controllers.md A complete example of a Danet controller demonstrating various decorators like @Controller, @Post, @Get, @Put, @Delete, @Param, @Body, and @Query for managing 'todo' resources. ```ts import { Controller, Get, Query, Post, Body, Put, Param, Delete, } from 'jsr:@danet/core'; import { CreateTodoDto, UpdateTodoDto, ListAllEntities } from './dto'; @Controller('todo') export class TodoController { @Post() create(@Body() createTodoDto: CreateTodoDto) { return "Cette action ajoute un nouveau todo"; } @Get(':id') findOne(@Param('id') id: string) { return `Cette action retourne un todo #${id}`; } @Put(':id') update(@Param('id') id: string, @Body() updateTodoDto: UpdateTodoDto) { return `Cette action met à jour un todo #${id}`; } @Delete(':id') remove(@Param('id') id: string) { return `Cette action supprime un todo #${id}`; } } ``` -------------------------------- ### GitHub Actions Job Setup Source: https://github.com/savory/docs/blob/main/src/deno-deploy.md This YAML configuration defines a GitHub Actions job that automates the process of checking out the repository, setting up Deno, installing the Danet CLI, bundling the application, and deploying it to Deno Deploy. ```yaml jobs: test: runs-on: ubuntu-latest steps: - name: Setup repo uses: actions/checkout@v3 - name: Setup Deno uses: denoland/setup-deno@004814556e37c54a2f6e31384c9e18e983317366 with: deno-version: v1.x - name: Install Danet CLI run: deno install --allow-read --allow-write --allow-run --allow-env -n danet jsr:@danet/cli - name: Bundle app with danet CLI run: danet bundle run.js - name: Deploy to Deno Deploy uses: denoland/deployctl@v1 with: project: YOUR-PROJECT-NAME entrypoint: run.js root: bundle ``` -------------------------------- ### Install Danet CLI Source: https://github.com/savory/docs/blob/main/src/cli.md Installs the Danet CLI globally using Deno. Requires read, write, run, and environment permissions. ```bash $ deno install --allow-read --allow-write --allow-run --allow-env --global -n danet jsr:@danet/cli ``` -------------------------------- ### Basic Danet Controller with GET Route Source: https://github.com/savory/docs/blob/main/src/overview/controllers.md Demonstrates the creation of a basic controller using the @Controller decorator and defining a GET endpoint with the @Get decorator. This example shows how to group routes with a path prefix and map requests to a specific method. ```ts import { Controller, Get } from 'jsr:@danet/core'; @Controller('todo') export class TodoController { @Get() findAll(): string { return 'This action returns all todo'; } } ``` -------------------------------- ### Basic GitHub Actions Workflow Setup Source: https://github.com/savory/docs/blob/main/src/fr/deno-deploy.md This YAML snippet outlines the initial setup for a GitHub Actions workflow that will deploy to Deno Deploy. It includes the workflow name, the trigger event (push to the main branch), and the required permissions, specifically `id-token: write` for authentication. ```yaml name: Deploy to Deno Deploy on: push: branches: [main] permissions: contents: read id-token: write # Nécessaire pour l'authentification avec Deno Deploy ``` -------------------------------- ### Install Danet CLI Source: https://github.com/savory/docs/blob/main/src/fr/cli.md Installs the Danet CLI using Deno, allowing it to be invoked as the 'danet' command. Requires read, write, run, and environment permissions. ```bash deno install --allow-read --allow-write --allow-run --allow-env -n danet jsr:@danet/cli ``` -------------------------------- ### Basic Controller with GET Route Source: https://github.com/savory/docs/blob/main/src/fr/overview/controllers.md Demonstrates the creation of a basic controller using the `@Controller()` decorator with a prefix and a GET request handler using the `@Get()` decorator. This maps incoming GET requests to the specified path to the `findAll` method. ```ts import { Controller, Get } from 'jsr:@danet/core'; @Controller('todo') export class TodoController { @Get() findAll(): string { return 'Cette action renvoie toutes les tâches à faire'; } } ``` -------------------------------- ### Full Danet Controller Sample Source: https://github.com/savory/docs/blob/main/src/overview/controllers.md A comprehensive example of a Danet controller demonstrating the use of various decorators like @Controller, @Get, @Post, @Put, @Delete, @Param, and @Body. It also shows how to import DTOs and use them for request handling. ```ts import { Controller, Get, Query, Post, Body, Put, Param, Delete, } from 'jsr:@danet/core'; import { CreateTodoDto, UpdateTodoDto, ListAllEntities } from './dto'; @Controller('todo') export class TodoController { @Post() create(@Body() createTodoDto: CreateTodoDto) { return 'This action adds a new todo'; } @Get(':id') findOne(@Param('id') id: string) { return `This action returns a #${id} todo`; } @Put(':id') update(@Param('id') id: string, @Body() updateTodoDto: UpdateTodoDto) { return `This action updates a #${id} todo`; } @Delete(':id') remove(@Param('id') id: string) { return `This action removes a #${id} todo`; } } ``` -------------------------------- ### Installation et création de projet Danet Source: https://github.com/savory/docs/blob/main/src/fr/overview/first-steps.md Installe la CLI Danet et crée un nouveau projet Danet. Nécessite Deno version 1.24.3 ou supérieure. ```bash $ deno install --allow-read --allow-write --allow-run --allow-env -n danet jsr:@danet/cli $ danet new my-danet-project $ cd my-danet-project ``` -------------------------------- ### Running the Danet Application Source: https://github.com/savory/docs/blob/main/src/fr/overview/controllers.md This snippet demonstrates how to obtain a DanetApplication instance by calling the bootstrap function and then start the server by calling the listen method. It includes fetching the port from environment variables. ```ts import { bootstrap } from './bootstrap.ts'; const application = await bootstrap(); await application.listen(Number(Deno.env.get('PORT') || 3000)); ``` -------------------------------- ### Launch Danet Server Source: https://github.com/savory/docs/blob/main/src/fr/openapi/introduction.md Command to start the Danet HTTP server, making the Swagger UI accessible in the browser. ```bash $ deno task launch-server ``` -------------------------------- ### Danet CLI Basic Commands Source: https://github.com/savory/docs/blob/main/src/cli.md Demonstrates basic commands for interacting with the Danet CLI, including showing help, creating new projects, running in development mode, and starting the application. ```bash $ danet --help $ danet new my-danet-project $ cd my-danet-project $ danet develop //run with file watching $ danet start //run without file watching ``` -------------------------------- ### Import EventEmitter Source: https://github.com/savory/docs/blob/main/src/techniques/events.md Demonstrates how to import the EventEmitter and EventEmitterModule from the '@danet/core' package to get started with event handling. ```typescript import { EventEmitterModule, EventEmitter } from 'jsr:@danet/core' ``` -------------------------------- ### Danet CLI Basic Workflow Source: https://github.com/savory/docs/blob/main/src/fr/cli.md Demonstrates the basic workflow for creating and running a new Danet project using the CLI. Includes commands for project creation, navigation, development, and starting the application. ```bash danet --help danet new mon-projet-danet cd mon-projet-danet danet develop //run sans file watching danet start //run sans file watching ``` -------------------------------- ### MongodbItemRepository Example Source: https://github.com/savory/docs/blob/main/src/techniques/databases.md An example of extending the `MongodbRepository` abstract class to create a specific repository for `Item` entities. It shows how to inject the `MongodbService` and set the collection name. ```ts import { Injectable } from 'jsr:@danet/core'; import { Item } from './class.ts'; import { MongodbRepository, MongodbService } from "jsr:@danet/database/mongodb"; @Injectable() export class MongodbItemRepository extends MongodbRepository { constructor(protected service: MongodbService) { super(service, 'items'); } } ``` -------------------------------- ### Topic Matching Examples Source: https://github.com/savory/docs/blob/main/src/websockets/controllers.md Illustrates various patterns for matching incoming WebSocket message topics using Danet's underlying router. ```typescript - '/user/:name' - '/posts/:id/comment/:comment_id' - '/api/animal/:type?' - '/post/:date{[0-9]+}/:title{[a-z]+}' ``` -------------------------------- ### Dependency Injection Example Source: https://github.com/savory/docs/blob/main/src/fr/overview/injectables.md Illustrates how dependency injection works in Danet by injecting TodoService into a controller's constructor. ```ts constructor(private todoService: TodoService) {} ``` -------------------------------- ### Workflow CI/CD pour Danet Source: https://github.com/savory/docs/blob/main/src/fr/deno-deploy.md Ce snippet YAML définit un workflow GitHub Actions pour automatiser le build et le déploiement d'une application Danet sur Deno Deploy. Il inclut les étapes pour cloner le dépôt, configurer Deno, installer le CLI Danet, bundler l'application et la déployer. ```yaml jobs: test: runs-on: ubuntu-latest steps: - name: Setup le repo uses: actions/checkout@v3 - name: Setup Deno uses: denoland/setup-deno@004814556e37c54a2f6e31384c9e18e983317366 with: deno-version: v1.x - name: Installer le CLI Danet run: deno install --allow-read --allow-write --allow-run --allow-env -n danet jsr:@danet/cli - name: Bundle l'application avec le CLI Danet run: danet bundle run.js - name: Deployer sur Deno Deploy uses: denoland/deployctl@v1 with: project: NOM-DE-TON-PROJET entrypoint: run.js root: bundle ``` -------------------------------- ### Run Danet Application Source: https://github.com/savory/docs/blob/main/src/overview/controllers.md This snippet shows how to execute the bootstrap function and start the Danet application by calling the listen method. It uses environment variables for the port, defaulting to 3000. ```ts import { bootstrap } from './bootstrap.ts'; const application = await bootstrap(); await application.listen(Number(Deno.env.get('PORT') || 3000)); ``` -------------------------------- ### Apply Compression Middleware Source: https://github.com/savory/docs/blob/main/src/fr/techniques/compression.md This snippet demonstrates how to apply the `hono_compress` middleware globally within a Danet application. Ensure you have the `hono_compress` package installed. This middleware helps reduce the size of response bodies. ```typescript import { compress } from 'jsr:@hono/hono/compress' const app = new DanetApplication(); app.use(compress()); ``` -------------------------------- ### Import and Configure a Dynamic Module Source: https://github.com/savory/docs/blob/main/src/overview/modules.md Demonstrates how to import and configure a dynamic module, such as the DatabaseModule, within another module. This example shows passing entities to the forRoot method for dynamic provider generation. ```ts import { Module } from 'jsr:@danet/core'; import { DatabaseModule } from './database/database.module'; import { User } from './users/entities/user.entity'; @Module({ imports: [DatabaseModule.forRoot([User])], }) export class AppModule {} ``` -------------------------------- ### Dynamic ConfigModule Import with Options Source: https://github.com/savory/docs/blob/main/src/fundamentals/dynamic-modules.md Example of dynamically importing the ConfigModule and passing configuration options, such as the path to the .env file folder. This allows for runtime customization. ```typescript import { Module } from 'jsr:@danet/core'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { ConfigModule } from './config/config.module'; @Module({ imports: [ConfigModule.register({ folder: './config' })], controllers: [AppController], injectables: [AppService], }) ``` -------------------------------- ### Session Middleware Setup Source: https://github.com/savory/docs/blob/main/src/fr/techniques/sessions.md Configures the session middleware for the Danet application using CookieStore. It sets encryption keys, expiration times, and cookie options for secure and functional session management. ```typescript import { Session, sessionMiddleware, CookieStore } from "jsr:@jcs224/hono-sessions"; const app = new DanetApplication(); const store = new CookieStore() app.use( sessionMiddleware({ store, encryptionKey: 'password_at_least_32_characters_long', // Required for CookieStore, recommended for others expireAfterSeconds: 900, // Expire session after 15 minutes of inactivity cookieOptions: { sameSite: 'Lax', // Recommended for basic CSRF protection in modern browsers path: '/', // Required for this library to work properly httpOnly: true, // Recommended to avoid XSS attacks }, }) ); ``` -------------------------------- ### KvVoteRepository Implementation with Secondary Keys Source: https://github.com/savory/docs/blob/main/src/techniques/databases.md An example of implementing a `KvVoteRepository` that extends `KvRepository` and handles secondary key creation for `Vote` entities. It includes custom methods to retrieve votes based on secondary keys. ```ts import { Injectable } from 'jsr:@danet/core'; import { Vote } from './class.ts'; import { type VoteRepository } from './repository.ts'; import { KvRepository, KvService } from "jsr:@danet/database/kv"; @Injectable() export class KvVoteRepository extends KvRepository implements VoteRepository { constructor(protected kv: KvService) { super(kv, 'votes'); } protected getSecondaryKeys(vote: Vote) { const voteByItemIdKey = [this.collectionName, vote.itemId, vote._id]; const voteByUserIdAndItemIdKey = [ this.collectionName, vote.userId, vote.itemId, ]; return {voteByUserIdAndItemIdKey, voteByItemIdKey}; } async getByItemId(itemId: string): Promise { const votes = []; for await ( const entry of this.kv.client().list({ prefix: [this.collectionName, itemId], }) ) { votes.push(entry.value as Vote); } return votes; } async getByItemIdAndUserId( itemId: string, userId: string, ): Promise { const entry = await this.kv.client().get([ this.collectionName, userId, itemId, ]); return entry.value !== null ? entry.value : undefined; } } ``` -------------------------------- ### Hono Sessions Middleware Setup Source: https://github.com/savory/docs/blob/main/src/techniques/sessions.md Configures the hono_sessions middleware for Savory applications. It requires a store (like CookieStore), an encryption key, session expiration time, and cookie options for security and functionality. ```typescript import { Session, sessionMiddleware, CookieStore } from 'jsr:@jcs224/hono-sessions' const app = new DanetApplication(); const store = new CookieStore() app.use( sessionMiddleware({ store, encryptionKey: 'password_at_least_32_characters_long', // Required for CookieStore, recommended for others expireAfterSeconds: 900, // Expire session after 15 minutes of inactivity cookieOptions: { sameSite: 'Lax', // Recommended for basic CSRF protection in modern browsers path: '/', // Required for this library to work properly httpOnly: true, // Recommended to avoid XSS attacks }, }) ); ``` -------------------------------- ### Simple WebSocket Middleware Example Source: https://github.com/savory/docs/blob/main/src/websockets/middlewares.md Demonstrates how to create and apply a custom middleware to a WebSocket controller in Savory. The middleware sends a status message to the client before proceeding with the request. It requires the `DanetMiddleware` interface and the `@Middleware` decorator. ```ts import { Injectable } from "@danet/core"; import { DanetMiddleware, ExecutionContext, NextFunction, Middleware, WebSocketController, OnWebSocketMessage } from "@danet/websocket"; // Assume SimpleInjectable is defined elsewhere @Injectable() class SimpleInjectable {} @Injectable() class SimpleMiddleware implements DanetMiddleware { constructor(private simpleInjectable: SimpleInjectable) { } async action(ctx: ExecutionContext, next: NextFunction) { ctx.websocket!.send( JSON.stringify({ topic: 'status', data: { middleware: 'SimpleMiddleware' }, }), ); await next(); } } @Middleware(SimpleMiddleware) @WebSocketController('ws') class ControllerWithMiddleware { @OnWebSocketMessage('trigger') getWithoutMiddleware() { } } ``` -------------------------------- ### Lancement du serveur Danet Source: https://github.com/savory/docs/blob/main/src/fr/overview/first-steps.md Démarre le serveur de l'application Danet après l'installation et la configuration. ```bash $ deno task launch-server ``` -------------------------------- ### Running the Danet Application Source: https://github.com/savory/docs/blob/main/src/overview/first-steps.md Command to launch the Danet application server, making it ready to receive HTTP requests. ```bash deno task launch-server ``` -------------------------------- ### Danet New Project with Database Options Source: https://github.com/savory/docs/blob/main/src/cli.md Shows how to create a new Danet project using the CLI, specifying the database provider either interactively or via command-line flags. ```bash # Interactive selection: $ danet new my-danet-project # Non-interactive selection: $ danet new my-danet-project --mongodb $ danet new my-danet-project --postgres $ danet new my-danet-project --in-memory ``` -------------------------------- ### Bundling Application with danet Source: https://github.com/savory/docs/blob/main/src/deno-deploy.md Demonstrates how to bundle an application using the `danet bundle` command. Bundling creates a single JavaScript file containing all project source code, which is recommended for deployment. It also mentions the requirement for bundlers to handle the `emitDecoratorMetadata` option. ```bash danet bundle my-app.js ``` -------------------------------- ### Example Template (hello.hbs) Source: https://github.com/savory/docs/blob/main/src/overview/renderer.md An example Handlebars template file demonstrating how to use variables passed from the controller. It includes basic HTML structure and placeholders for 'title' and 'name'. ```handlebars {{title}} Hello {{name}}! ``` -------------------------------- ### Bad Request Payload Example Source: https://github.com/savory/docs/blob/main/src/overview/controllers.md An example JSON response indicating a 'NotValidBodyException' when a request payload fails validation against the defined DTO. It details the specific property that caused the validation error. ```json { "status": 400, "name": "NotValidBodyException", "reasons": [ { "property": "priority", "errorMessage": "Property must be a number", "constraints": [] } ], "message": "400 - Body bad formatted" } ``` -------------------------------- ### Deno Deploy CLI Deployment Source: https://github.com/savory/docs/blob/main/src/deno-deploy.md This snippet shows the basic command to deploy a project to Deno Deploy using the `danet` CLI. It outlines the available options for specifying the project name, entry point file, and bundle output file. ```bash danet deploy Usage: danet deploy Description: Deploy your project to Deno Deploy Options: -h, --help - Show this help. -p, --project - Deno deploy project name. If no value is given, Deno deploy will generate a random name -e, --entrypoint - Bundle entrypoint file (Default: "run.ts") -b, --bundle - Bundle output file name, also used as deployctl entrypoint (Default: "bundle.js") Commands: help [command] - Show this help or the help of a sub-command. ``` -------------------------------- ### Local Deployment with deployctl Source: https://github.com/savory/docs/blob/main/src/fr/deno-deploy.md This snippet shows the three main commands to bundle an application using `danet` and deploy it to Deno Deploy using `deployctl`. It includes instructions on where to find `deployctl` and how to obtain an access token. ```bash $ danet bundle my-app.js $ cd bundle $ deployctl deploy --project=YOUR_PROJECT_NAME --no-static --token=YOUTOKEN my-app.js ``` -------------------------------- ### Using Custom Decorator Source: https://github.com/savory/docs/blob/main/src/fr/fundamentals/execution-context.md Example of applying the custom '@Roles' decorator to a route handler. ```typescript @Post() @Roles('admin') async create(@Body() createTodoDto: CreateTodoDto) { this.todoService.create(createCatDto); } ``` -------------------------------- ### ExecutionContext Interface Source: https://github.com/savory/docs/blob/main/src/fr/fundamentals/execution-context.md Defines the structure of the ExecutionContext object, providing methods to get the controller class and the handler function. ```APIDOC type ExecutionContext = { /** * Returns the type of the controller class which the current handler belongs to. */ getClass(): Constructor; /** * Returns a reference to the handler (method) that will be invoked next in the * request pipeline. */ getHandler(): Function; } ``` -------------------------------- ### Get Whole Message Data Source: https://github.com/savory/docs/blob/main/src/websockets/controllers.md Receives the entire incoming message payload as a strongly-typed object in the handler method. ```typescript @OnWebSocketMessage('events') handleEvent(@Body() payload: { name: string, whateveryouwant: CoolObject }) { return { topic: 'hello', data: name }; } ``` -------------------------------- ### Configuration de la base de données avec variables d'environnement Source: https://github.com/savory/docs/blob/main/src/fr/overview/first-steps.md Configurez les informations de connexion à la base de données en utilisant des variables d'environnement. ```.env DB_NAME= DB_HOST= DB_PORT DB_USERNAME DB_PASSWORD= ``` -------------------------------- ### Static ConfigModule Import Source: https://github.com/savory/docs/blob/main/src/fundamentals/dynamic-modules.md Example of statically importing the ConfigModule without any custom options. This is the default behavior when no configuration is provided. ```typescript import { Module } from 'jsr:@danet/core'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { ConfigModule } from './config/config.module'; @Module({ imports: [ConfigModule], controllers: [AppController], injectables: [AppService], }) ``` -------------------------------- ### Bundling Application with danet Source: https://github.com/savory/docs/blob/main/src/fr/deno-deploy.md Demonstrates the command to bundle a JavaScript application into a single file using the `danet` bundler. This is a prerequisite for deployment, ensuring all source code is included and decorator metadata is handled. ```bash $ danet bundle my-app.js ``` -------------------------------- ### Async Function Example Source: https://github.com/savory/docs/blob/main/src/overview/controllers.md Demonstrates how to define an asynchronous function in Danet that returns a Promise. This is used for handling asynchronous data extraction. ```ts import { Controller, Get } from 'jsr:@danet/core'; @Controller('todo') export class TodoController { @Get() async findAll(): Promise { return []; } } ``` -------------------------------- ### Static Module Binding: UsersModule Source: https://github.com/savory/docs/blob/main/src/fundamentals/dynamic-modules.md Defines a UsersModule that provides and exports a UsersService. This is a fundamental example of static module binding in Danet. ```ts import { Module } from 'jsr:@danet/core'; import { UsersService } from './users.service'; @Module({ injectables: [UsersService], exports: [UsersService], }) export class UsersModule {} ``` -------------------------------- ### Launch Server Source: https://github.com/savory/docs/blob/main/src/openapi/introduction.md Command to launch the Danet HTTP server. ```bash $ deno task launch-server ``` -------------------------------- ### Accessing Handler and Class Names Source: https://github.com/savory/docs/blob/main/src/fr/fundamentals/execution-context.md Example demonstrating how to retrieve the name of the current handler method and its controller class using ExecutionContext. ```typescript const methodKey = ctx.getHandler().name; // "create" const className = ctx.getClass().name; // "TodoController" ``` -------------------------------- ### Route Parameters Source: https://github.com/savory/docs/blob/main/src/overview/controllers.md Illustrates how to define routes with dynamic parameters and access them using the @Param() decorator. This is useful for handling requests like GET /todo/1. ```ts import { Controller, Get, Param } from 'jsr:@danet/core'; @Controller('todo') export class TodoController { @Get(':id') findOne(@Param('id') id: string): string { return `This action returns a #${id} todo`; } } ``` -------------------------------- ### GitHub Actions Workflow for Deno Deploy Source: https://github.com/savory/docs/blob/main/src/deno-deploy.md This snippet shows a GitHub Actions workflow configuration for deploying to Deno Deploy. It uses the `denoland/deployctl@v1` action and specifies the project name and entry point for the deployment. ```yaml name: Deploy to Deno Deploy on: push: branches: [main] permissions: contents: read id-token: write # Needed for auth with Deno Deploy jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Deploy to Deno Deploy uses: denoland/deployctl@v1 with: project: YOUR PROJECT NAME HERE entrypoint: run.js root: bundle ``` -------------------------------- ### HTTP Method Decorators Source: https://github.com/savory/docs/blob/main/src/overview/controllers.md Shows how to define handlers for different HTTP methods using Danet decorators. Supports @Get(), @Post(), @Put(), @Delete(), @Patch(), and @All(). ```ts import { Controller, Get, Post } from 'jsr:@danet/core'; @Controller('todo') export class TodoController { @Post() create(): string { return 'This action adds a new todo'; } @Get() findAll(): string { return 'This action returns all todo'; } } ``` -------------------------------- ### Manual Deployment with deployctl Source: https://github.com/savory/docs/blob/main/src/deno-deploy.md Provides instructions for manually deploying a bundled application to Deno Deploy using the `deployctl` command. This method requires obtaining an access token from Deno Deploy and specifies the command to execute within the bundle directory. ```bash cd bundle && deployctl deploy --project=YOUR_PROJECT_NAME my-app.js ``` -------------------------------- ### Invalid Request Body Exception Source: https://github.com/savory/docs/blob/main/src/fr/overview/controllers.md An example of the JSON response returned when a request body fails validation against the defined DTO. It details the validation errors encountered. ```json { "status": 400, "name": "NotValidBodyException", "reasons": [ { "property": "priority", "errorMessage": "Property must be a number", "constraints": [] } ], "message": "400 - Mauvais format du corps" } ``` -------------------------------- ### Deploying Bundled Application with deployctl Source: https://github.com/savory/docs/blob/main/src/fr/deno-deploy.md Provides the command to deploy a bundled application to Deno Deploy. It requires the project name and an access token, and uses the `--no-static` flag to indicate that static file serving is not needed. ```bash $ deployctl deploy --project=NOM_DE_TON_PROJET --no-static --token=TONTOKEN my-app.js ``` -------------------------------- ### Catching All Unhandled Exceptions Source: https://github.com/savory/docs/blob/main/src/overview/exception-filters.md An example of an exception filter ('AllExceptionsFilter') designed to catch all unhandled exceptions by omitting the '@Catch()' decorator. This filter provides a generic response for any exception type. ```ts import { Catch, ExceptionFilter, HttpContext, } from 'jsr:@danet/core'; @Injectable() export class AllExceptionsFilter implements ExceptionFilter { constructor() {} catch(exception: unknown, ctx: HttpContext): boolean { const request = ctx.req; const status = exception.status; const body = { statusCode: status, timestamp: new Date().toISOString(), path: request.url, }; return ctx.newResponse(JSON.stringify(body), { status: status.code, headers: ctx.res.headers }); } } ``` -------------------------------- ### Danet New Project Database Options Source: https://github.com/savory/docs/blob/main/src/fr/cli.md Shows how to specify the database provider when creating a new Danet project using the 'danet new' command. Options include MongoDB, PostgreSQL, and in-memory. ```bash danet new --mongodb danet new --postgres danet new ---en-mémoire ``` -------------------------------- ### GitHub Actions Workflow for Deno Deploy Source: https://github.com/savory/docs/blob/main/src/fr/deno-deploy.md This YAML snippet defines a GitHub Actions workflow for deploying to Deno Deploy. It specifies the trigger (push to main branch), necessary permissions, and uses the `denoland/deployctl` action with parameters for the project name, entrypoint, and root directory. ```yaml name: Deploy to Deno Deploy on: push: branches: [main] permissions: contents: read id-token: write # Nécessaire pour l'authentification avec Deno Deploy - name: Deployer sur Deno Deploy uses: denoland/deployctl@v1 with: project: TON NOM DE PROJET ICI entrypoint: run.js root: bundle ``` -------------------------------- ### Simple Authorization Guard Source: https://github.com/savory/docs/blob/main/src/fr/overview/guards.md An example of a simple authorization guard that implements the AuthGuard interface. It includes a canActivate method which validates the request. The validateRequest function's logic can be customized as needed. ```typescript import { Injectable, AuthGuard } from 'jsr:@danet/core'; import { ExecutionContext } from "./router.ts"; @Injectable() export class SimpleAuthGuard implements AuthGuard { canActivate( context: ExecutionContext, ): boolean | Promise { const request = context.request; return validateRequest(request); } } ``` -------------------------------- ### Bootstrapping Danet Application Source: https://github.com/savory/docs/blob/main/src/fr/overview/controllers.md This code defines a bootstrap function that creates a new DanetApplication instance and initializes it with the AppModule. This pattern is recommended for testability and managing application instances. ```ts import { AppModule } from './app.module.ts'; import { DanetApplication } from 'jsr:@danet/core'; export const bootstrap = async () => { const application = new DanetApplication(); await application.init(AppModule); return application; } ``` -------------------------------- ### Functional Logger Middleware Source: https://github.com/savory/docs/blob/main/src/fr/overview/middlewares.md Provides an example of a functional middleware. This approach is simpler when the middleware does not require dependencies or internal state. It's a plain async function that takes `HttpContext` and `NextFunction`. ```ts import { HttpContext, NextFunction } from 'jsr:@danet/core'; export async function logger(ctx: HttpContext, next: NextFunction) { console.log(`Request...`); await next(); }; ``` -------------------------------- ### ConfigService Implementation (Initial) Source: https://github.com/savory/docs/blob/main/src/fundamentals/dynamic-modules.md An initial implementation of the ConfigService that hardcodes options to demonstrate loading environment variables from a specified folder. It uses Deno's environment variables and the std/dotenv library. ```typescript import { Injectable } from 'jsr:@danet/core'; import { resolve } from "@std/path"; import { loadSync } from "jsr:@std/dotenv"; import { EnvConfig } from './interfaces'; @Injectable() export class ConfigService { private readonly envConfig: EnvConfig; constructor() { const options = { folder: './config' }; const filePath = `${Deno.env.get('ENVIRONMENT') || 'development'}.env`; const envFile = resolve(import.meta.dirname, '../../', options.folder, filePath); this.envConfig = loadSync({envPath: envFile, export: true}); } get(key: string): string { return this.envConfig[key]; } } ``` -------------------------------- ### Bootstrap Swagger Module Source: https://github.com/savory/docs/blob/main/src/openapi/introduction.md Initializes the SwaggerModule and creates an OpenAPI document for the Danet application. It sets the title, description, and version of the API specification. ```ts import { DanetApplication } from 'jsr:@danet/core'; import { SwaggerModule, SpecBuilder } from 'jsr:@danet/swagger'; import { AppModule } from './app.module'; async function bootstrap() { const application = new DanetApplication(); await application.init(AppModule); const spec = new SpecBuilder() .setTitle('Todo') .setDescription('The todo API') .setVersion('1.0') .build(); const document = await SwaggerModule.createDocument(application, spec); SwaggerModule.setup('api', application, document); return application; } ``` -------------------------------- ### Bootstrap Danet Application Source: https://github.com/savory/docs/blob/main/src/overview/controllers.md This snippet demonstrates how to create a bootstrap function that initializes a DanetApplication with the AppModule. This function returns the application instance, facilitating easier testing and management. ```ts import { AppModule } from './app.module.ts'; import { DanetApplication } from 'jsr:@danet/core'; export const bootstrap = async () => { const application = new DanetApplication(); await application.init(AppModule); return application; } ``` -------------------------------- ### Applying Multiple Middleware Source: https://github.com/savory/docs/blob/main/src/overview/middlewares.md Illustrates how to apply multiple middleware functions or classes to a controller or globally. Middleware are executed in the order they are provided. ```ts import { Middleware, Controller, Get } from 'jsr:@danet/core'; import { logger } from './logger.middleware'; import { AnotherMiddleware } from './another.middleware'; @Middleware(logger, AnotherMiddleware) @Controller('todo') class TodoController { @Get('/') getWithMiddleware() { return 'OK' } }; ```