agent-workflow-kit-cli 1.3.2 → 1.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/commands/add.js +3 -1
- package/dist/cli/commands/doctor.js +145 -47
- package/dist/cli/commands/init.js +6 -0
- package/dist/core/analyzer.js +70 -0
- package/dist/core/detector.js +22 -0
- package/package.json +1 -1
- package/templates/common/AGENTS.md.hbs +4 -0
- package/templates/common/GLOBAL_RULES.md +101 -0
- package/templates/devops/AGENTS.md.hbs +32 -0
- package/templates/devops/skills/devops/SKILL.md +477 -0
- package/templates/diagram/AGENTS.md.hbs +30 -0
- package/templates/diagram/skills/drawio-diagram/SKILL.md +427 -0
- package/templates/dotnet/AGENTS.md.hbs +38 -34
- package/templates/dotnet/rules/api-structure.md +15 -15
- package/templates/dotnet/rules/csharp-style.md +17 -17
- package/templates/dotnet/rules/dependency-injection.md +12 -12
- package/templates/dotnet/rules/error-handling-validation.md +15 -15
- package/templates/dotnet/skills/dotnet-controller/SKILL.md +16 -16
- package/templates/express/AGENTS.md.hbs +37 -33
- package/templates/express/rules/error-handling.md +18 -18
- package/templates/express/rules/express-style.md +19 -19
- package/templates/express/rules/router-controller.md +16 -16
- package/templates/express/skills/express-endpoint/SKILL.md +14 -14
- package/templates/fastapi/AGENTS.md.hbs +25 -3
- package/templates/fastapi/rules/api-testing.md +24 -0
- package/templates/fastapi/rules/database-async.md +26 -0
- package/templates/golang/AGENTS.md.hbs +42 -0
- package/templates/golang/rules/concurrency.md +71 -0
- package/templates/golang/rules/error-handling.md +42 -0
- package/templates/golang/rules/golang-style.md +24 -0
- package/templates/golang/rules/project-layout.md +39 -0
- package/templates/golang/skills/golang-db/SKILL.md +27 -0
- package/templates/golang/skills/golang-feature/SKILL.md +42 -0
- package/templates/nestjs/AGENTS.md.hbs +33 -29
- package/templates/nestjs/rules/module-architecture.md +14 -14
- package/templates/nestjs/rules/nestjs-style.md +12 -12
- package/templates/nestjs/rules/validation-errors.md +15 -15
- package/templates/nestjs/skills/nestjs-module/SKILL.md +15 -15
- package/templates/next-js/AGENTS.md.hbs +39 -35
- package/templates/next-js/rules/data-fetching-mutations.md +17 -17
- package/templates/next-js/rules/next-style.md +17 -17
- package/templates/next-js/rules/seo-metadata.md +18 -18
- package/templates/next-js/rules/server-client-components.md +17 -17
- package/templates/next-js/skills/next-feature/SKILL.md +16 -16
- package/templates/rust/AGENTS.md.hbs +41 -0
- package/templates/rust/rules/error-handling.md +36 -0
- package/templates/rust/rules/memory-concurrency.md +47 -0
- package/templates/rust/rules/project-layout.md +49 -0
- package/templates/rust/rules/rust-style.md +26 -0
- package/templates/rust/skills/rust-db/SKILL.md +27 -0
- package/templates/rust/skills/rust-feature/SKILL.md +34 -0
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# C# Coding Style & Conventions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
This document specifies standard coding styles, naming patterns, and source file organization conventions in .NET projects.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
## 🏷️
|
|
7
|
+
## 🏷️ Naming Conventions
|
|
8
8
|
|
|
9
|
-
###
|
|
10
|
-
- **PascalCase:**
|
|
11
|
-
- *
|
|
12
|
-
- **Interface Prefix:**
|
|
13
|
-
- *
|
|
14
|
-
- **camelCase:**
|
|
15
|
-
- *
|
|
16
|
-
- **Private Fields Prefix:**
|
|
17
|
-
- *
|
|
9
|
+
### Class & Component Naming Rules
|
|
10
|
+
- **PascalCase:** Use for Classes, Structs, Records, Enums, Interfaces, Methods, and Public Properties.
|
|
11
|
+
- *Examples:* `UserService`, `GetActiveUsers()`, `CreatedDate`.
|
|
12
|
+
- **Interface Prefix:** Interface names must start with the uppercase letter `I`.
|
|
13
|
+
- *Examples:* `IUserService`, `IUserRepository`.
|
|
14
|
+
- **camelCase:** Use for method arguments and local variables.
|
|
15
|
+
- *Examples:* `userId`, `requestPayload`.
|
|
16
|
+
- **Private Fields Prefix:** Private fields inside classes must use `camelCase` and start with an underscore `_`.
|
|
17
|
+
- *Example:* `private readonly IUserRepository _userRepository;`.
|
|
18
18
|
|
|
19
19
|
---
|
|
20
20
|
|
|
21
|
-
## 📦
|
|
22
|
-
- **Namespaces:**
|
|
23
|
-
- *
|
|
24
|
-
- **File
|
|
21
|
+
## 📦 File Structure & Formatting
|
|
22
|
+
- **Namespaces:** Match namespaces with the physical directory structure to ensure easy discovery.
|
|
23
|
+
- *Example:* `ProjectName.Application.Services`.
|
|
24
|
+
- **File-Scoped Namespaces:** Use C# 10+ file-scoped namespaces to reduce unnecessary indentation levels:
|
|
25
25
|
```csharp
|
|
26
26
|
namespace ProjectName.Application.Services;
|
|
27
27
|
|
|
@@ -30,4 +30,4 @@ Tài liệu này đặc tả quy chuẩn coding style, đặt tên biến, tên
|
|
|
30
30
|
// ...
|
|
31
31
|
}
|
|
32
32
|
```
|
|
33
|
-
- **
|
|
33
|
+
- **Sorting Usings:** Organize `using` directives by placing system namespaces (`System.*`) first, followed by third-party packages, and internal project dependencies last.
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Dependency Injection (DI) Configurations
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
This document details guidelines for configuring and consuming dependency injection in .NET Core applications.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
## 💉 Constructor Injection
|
|
8
|
-
- **
|
|
9
|
-
-
|
|
7
|
+
## 💉 Constructor Injection
|
|
8
|
+
- **Mandatory Rule:** Always resolve class dependencies using constructor parameters. Assign them to private readonly fields prefixed with an underscore `_`.
|
|
9
|
+
- Never use the Service Locator pattern (do not call `app.Services.GetService<T>()` or inject `IServiceProvider` to dynamically resolve services at runtime).
|
|
10
10
|
|
|
11
|
-
* **
|
|
11
|
+
* **Invalid (❌ Prohibited):**
|
|
12
12
|
```csharp
|
|
13
13
|
public class OrderService
|
|
14
14
|
{
|
|
@@ -26,7 +26,7 @@ Tài liệu này hướng dẫn cách cấu hình và tiêm phụ thuộc trong
|
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
28
|
```
|
|
29
|
-
* **
|
|
29
|
+
* **Valid (✔️ Recommended):**
|
|
30
30
|
```csharp
|
|
31
31
|
public class OrderService : IOrderService
|
|
32
32
|
{
|
|
@@ -47,8 +47,8 @@ Tài liệu này hướng dẫn cách cấu hình và tiêm phụ thuộc trong
|
|
|
47
47
|
|
|
48
48
|
---
|
|
49
49
|
|
|
50
|
-
## ⚙️
|
|
51
|
-
|
|
52
|
-
1. **Transient (`AddTransient<I, T>()`):**
|
|
53
|
-
2. **Scoped (`AddScoped<I, T>()`):**
|
|
54
|
-
3. **Singleton (`AddSingleton<I, T>()`):**
|
|
50
|
+
## ⚙️ Service Lifetimes Registration
|
|
51
|
+
Register dependencies with the appropriate lifetime scopes inside `Program.cs`:
|
|
52
|
+
1. **Transient (`AddTransient<I, T>()`):** Instantiated every time they are requested. Use for lightweight, stateless services.
|
|
53
|
+
2. **Scoped (`AddScoped<I, T>()`):** Instantiated once per HTTP request context. Recommended for repositories, database contexts (`DbContext`), and business services.
|
|
54
|
+
3. **Singleton (`AddSingleton<I, T>()`):** Instantiated once and shared across the entire application lifetime. Use for in-memory caching, system configurations, and thread-safe helper services.
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Unified Exception Handling & Automated Validation (FluentValidation)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
This document defines configurations for centralized exception handling using Middleware and incoming request validation using the FluentValidation library in .NET applications.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
## 🛡️
|
|
8
|
-
- **
|
|
9
|
-
-
|
|
7
|
+
## 🛡️ Automated Validation with FluentValidation
|
|
8
|
+
- **Rule:** Every API request representing complex input data payloads must have a corresponding validator class inheriting from `AbstractValidator<T>` to declare validation rules.
|
|
9
|
+
- Configure FluentValidation to automatically intercept invalid requests and return an HTTP `400 Bad Request` payload to the client, preventing repetitive manual validation checks inside Controllers.
|
|
10
10
|
|
|
11
11
|
```csharp
|
|
12
|
-
//
|
|
12
|
+
// Example of a Validator class
|
|
13
13
|
using FluentValidation;
|
|
14
14
|
|
|
15
15
|
public class CreateCourseRequestValidator : AbstractValidator<CreateCourseRequestDto>
|
|
@@ -17,32 +17,32 @@ Tài liệu này quy định cấu hình xử lý ngoại lệ tập trung qua M
|
|
|
17
17
|
public CreateCourseRequestValidator()
|
|
18
18
|
{
|
|
19
19
|
RuleFor(x => x.Title)
|
|
20
|
-
.NotEmpty().WithMessage("
|
|
21
|
-
.MaximumLength(150).WithMessage("
|
|
20
|
+
.NotEmpty().WithMessage("Course title cannot be empty.")
|
|
21
|
+
.MaximumLength(150).WithMessage("Title must not exceed 150 characters.");
|
|
22
22
|
|
|
23
23
|
RuleFor(x => x.Price)
|
|
24
|
-
.GreaterThanOrEqualTo(0).WithMessage("
|
|
24
|
+
.GreaterThanOrEqualTo(0).WithMessage("Course price cannot be less than 0.");
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
```
|
|
28
28
|
|
|
29
29
|
---
|
|
30
30
|
|
|
31
|
-
## 🚨
|
|
32
|
-
- **
|
|
33
|
-
-
|
|
31
|
+
## 🚨 Centralized Exception Handling (Global Exception Middleware)
|
|
32
|
+
- **Rule:** Never expose raw system exceptions (such as database faults, file system errors, or stack traces) directly to clients as HTTP 500 errors.
|
|
33
|
+
- Build a global middleware (`ExceptionHandlingMiddleware`) or implement `IExceptionHandler` in .NET 8+ to intercept all unhandled exceptions and format them into a standard JSON payload:
|
|
34
34
|
|
|
35
35
|
```json
|
|
36
36
|
{
|
|
37
37
|
"success": false,
|
|
38
38
|
"statusCode": 500,
|
|
39
39
|
"timestamp": "2026-06-13T07:42:00.000Z",
|
|
40
|
-
"message": "
|
|
40
|
+
"message": "An internal server error occurred. Please contact the administrator."
|
|
41
41
|
}
|
|
42
42
|
```
|
|
43
43
|
|
|
44
44
|
```csharp
|
|
45
|
-
//
|
|
45
|
+
// Standard Global Exception Handling Middleware
|
|
46
46
|
public class ExceptionHandlingMiddleware
|
|
47
47
|
{
|
|
48
48
|
private readonly RequestDelegate _next;
|
|
@@ -77,7 +77,7 @@ Tài liệu này quy định cấu hình xử lý ngoại lệ tập trung qua M
|
|
|
77
77
|
success = false,
|
|
78
78
|
statusCode = context.Response.StatusCode,
|
|
79
79
|
timestamp = DateTime.UtcNow,
|
|
80
|
-
message = "
|
|
80
|
+
message = "An internal server error occurred. Please contact the administrator."
|
|
81
81
|
};
|
|
82
82
|
|
|
83
83
|
return context.Response.WriteAsJsonAsync(response);
|
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: dotnet-controller
|
|
3
|
-
description:
|
|
3
|
+
description: Scaffold or extend an ASP.NET Core API Controller with corresponding DTOs, FluentValidation, and Service interfaces
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
Follow this process to generate a new API Endpoint or Controller in .NET (C#).
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
- controllerName:
|
|
10
|
-
- routePath:
|
|
11
|
-
- requestDtoName:
|
|
12
|
-
- functionality:
|
|
8
|
+
Inputs:
|
|
9
|
+
- controllerName: Name of the Controller (e.g., `CoursesController`)
|
|
10
|
+
- routePath: HTTP route mapping (e.g., `api/v1/courses`)
|
|
11
|
+
- requestDtoName: Class name of the request DTO (e.g., `CreateCourseRequestDto`)
|
|
12
|
+
- functionality: Summary of the business requirements and methods to process
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
1.
|
|
16
|
-
2.
|
|
17
|
-
3.
|
|
18
|
-
4.
|
|
19
|
-
5.
|
|
20
|
-
6.
|
|
21
|
-
7.
|
|
22
|
-
8.
|
|
14
|
+
Steps:
|
|
15
|
+
1. Declare the corresponding Request/Response DTO classes inside the Application layer (or the project's `DTOs` directory).
|
|
16
|
+
2. Create a Validator class inheriting from FluentValidation's `AbstractValidator<T>` in the Application layer to define data constraints.
|
|
17
|
+
3. Define the Service Interface (e.g., `ICourseService`) and its concrete implementation class (`CourseService`) in the Application layer to handle business logic.
|
|
18
|
+
4. Register the new Service in the Dependency Injection container (using Scoped lifetime) inside the `Program.cs` configuration file.
|
|
19
|
+
5. Create the Controller class inheriting from `ControllerBase`, decorated with `[ApiController]` and `[Route]` attributes.
|
|
20
|
+
6. Use Constructor Injection to inject the Service Interface into the Controller, delegate request processing, and map responses to appropriate `IActionResult` objects (e.g., `Ok()`, `Created()`, `BadRequest()`).
|
|
21
|
+
7. Write unit tests for the Service and Controller using xUnit and Moq.
|
|
22
|
+
8. Execute compilation and testing:
|
|
23
23
|
- `dotnet build`
|
|
24
24
|
- `dotnet test`
|
|
@@ -1,41 +1,45 @@
|
|
|
1
|
-
## 🗺️
|
|
2
|
-
|
|
3
|
-
### 🔄
|
|
4
|
-
|
|
5
|
-
1. **
|
|
6
|
-
2. **
|
|
7
|
-
3. **
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
- Chạy Kiểm thử: `{{runCommand}} test` (hoặc `{{runCommand}} test -- --run` cho môi trường CI/CD)
|
|
11
|
-
- Chạy Build thử nghiệm: `{{runCommand}} build`
|
|
12
|
-
4. **Quản lý Thư viện:** Cài đặt các thư viện mới bằng lệnh: `{{packageManager}} add [tên_thư_viện]`. Tuyệt đối cấm sửa thủ công file lock `{{lockFile}}`.
|
|
1
|
+
## 🗺️ Express.js Development Guide (Node.js Backend)
|
|
2
|
+
|
|
3
|
+
### 🔄 Agent Development Lifecycle
|
|
4
|
+
The AI Agent must execute all Express.js tasks following this structured 5-stage lifecycle:
|
|
5
|
+
1. **Design & Code:** Organize code according to a clean 3-tier architecture as detailed in `@router-controller.md`. Spaghetti code is strictly prohibited.
|
|
6
|
+
2. **Comprehensive Testing:** Write unit tests for Services using Jest, and test API integrations using Supertest.
|
|
7
|
+
3. **Troubleshooting & Debugging:** When debugging async router handlers or validation payloads, verify error forwarding is properly configured.
|
|
8
|
+
4. **Code Quality & Review:** Perform self-review using `@error-handling.md` to ensure errors are captured globally and validation uses Zod schemas. Check style rules in `@express-style.md`.
|
|
9
|
+
5. **Production Readiness:** Verify compilation and static analysis checks pass without errors.
|
|
13
10
|
|
|
14
11
|
---
|
|
15
12
|
|
|
16
|
-
### 🏗️
|
|
17
|
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
13
|
+
### 🏗️ Template Blueprint
|
|
14
|
+
Refer to the detailed rules below:
|
|
15
|
+
- Clean coding style and type safety using TypeScript in Express: `@express-style.md`
|
|
16
|
+
- Separation of concerns: Router mappings $\rightarrow$ Controller delegation $\rightarrow$ Service execution: `@router-controller.md`
|
|
17
|
+
- Async error catching strategies and centralized global error handling middleware: `@error-handling.md`
|
|
18
|
+
- Process to scaffold new API endpoints cleanly from Routers to Validators: `@express-endpoint`
|
|
22
19
|
|
|
23
20
|
---
|
|
24
21
|
|
|
25
|
-
### 🏛️
|
|
22
|
+
### 🏛️ Strict Development Rules
|
|
26
23
|
|
|
27
|
-
#### 1.
|
|
28
|
-
|
|
24
|
+
#### 1. Strict Layer Separation
|
|
25
|
+
Strictly comply with the data flow chain:
|
|
29
26
|
$$\text{Client} \longrightarrow \text{Router} \longrightarrow \text{Middleware} \longrightarrow \text{Controller} \longrightarrow \text{Service} \longrightarrow \text{Model/Database}$$
|
|
30
|
-
- **Router:**
|
|
31
|
-
- **Controller:**
|
|
32
|
-
- **Service:**
|
|
33
|
-
|
|
34
|
-
#### 2.
|
|
35
|
-
- **
|
|
36
|
-
- **
|
|
37
|
-
- **
|
|
38
|
-
|
|
39
|
-
#### 3.
|
|
40
|
-
- **
|
|
41
|
-
- **
|
|
27
|
+
- **Router:** Must not contain processing logic. Only maps HTTP methods + paths and registers auth/validation middlewares.
|
|
28
|
+
- **Controller:** Only extracts inputs from the request object (`req.body`, `req.query`, `req.params`), invokes the target Service, and returns the response using `res.status().json()`. Never execute database queries directly here.
|
|
29
|
+
- **Service:** Houses business logic, calculations, and database model interactions. Must not reference or depend on Express `req` or `res` objects to ensure testability.
|
|
30
|
+
|
|
31
|
+
#### 2. Async Error Handling
|
|
32
|
+
- **No Manual Try/Catch in Controllers:** Avoid wrapping every controller method in manual try/catch blocks.
|
|
33
|
+
- **Use Async Handlers:** Wrap all async controller functions with an automatic error-catching wrapper (such as `express-async-handler`) to forward exceptions to the `next()` function automatically.
|
|
34
|
+
- **Centralized Global Error Middleware:** Declare a 4-parameter error-handling middleware at the end of the server bootstrap chain (after all route registrations) to format error payloads.
|
|
35
|
+
|
|
36
|
+
#### 3. Request Validation with Zod Middleware
|
|
37
|
+
- **No Manual Conditional Validation:** Do not write scattered `if` blocks to check input parameters.
|
|
38
|
+
- **Zod Schema Middleware:** Implement a shared validation middleware that accepts a Zod schema to validate request segments (`body`, `query`, `params`) before they reach the Controller.
|
|
39
|
+
|
|
40
|
+
### 🧪 Verification & Testing
|
|
41
|
+
Before completing a task, run the following verification pipeline:
|
|
42
|
+
- **Linting:** `{{runCommand}} lint`
|
|
43
|
+
- **Type Checking:** `{{runCommand}} typecheck`
|
|
44
|
+
- **Testing:** `{{runCommand}} test`
|
|
45
|
+
- **Build Validation:** `{{runCommand}} build`
|
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Async Error Handling & Automated Validation (Zod Middleware)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
This document defines standard practices for asynchronous error catching, centralized global error handling middleware, and automated schema validations using Zod.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
## 🚨
|
|
8
|
-
- **
|
|
9
|
-
- **
|
|
7
|
+
## 🚨 Async Error Handling Architecture
|
|
8
|
+
- **No Manual Try/Catch in Controllers:** Wrapping every controller method in manual try/catch blocks is prohibited.
|
|
9
|
+
- **Use Async Handlers:** Wrap all async controller functions with an automatic error-catching wrapper (such as `asyncHandler`) to automatically forward exceptions to Express's `next()` function.
|
|
10
10
|
|
|
11
11
|
```typescript
|
|
12
12
|
import { Request, Response, NextFunction } from 'express';
|
|
13
13
|
|
|
14
|
-
//
|
|
15
|
-
|
|
14
|
+
// Automated async error catcher wrapper
|
|
15
|
+
const asyncHandler = (fn: Function) => (req: Request, res: Response, next: NextFunction) => {
|
|
16
16
|
Promise.resolve(fn(req, res, next)).catch(next);
|
|
17
17
|
};
|
|
18
18
|
|
|
19
|
-
//
|
|
19
|
+
// Controller usage example
|
|
20
20
|
export const getUserProfile = asyncHandler(async (req: Request, res: Response) => {
|
|
21
21
|
const userId = req.user.id;
|
|
22
|
-
const profile = await userService.getProfile(userId); //
|
|
22
|
+
const profile = await userService.getProfile(userId); // Errors thrown inside the service are automatically caught
|
|
23
23
|
return res.status(200).json({ success: true, data: profile });
|
|
24
24
|
});
|
|
25
25
|
```
|
|
26
26
|
|
|
27
27
|
---
|
|
28
28
|
|
|
29
|
-
## 🔌
|
|
30
|
-
- **
|
|
29
|
+
## 🔌 Centralized Global Error Handler Middleware
|
|
30
|
+
- **Register Error Middleware:** You must register a 4-parameter error-handling middleware at the end of the server bootstrap chain (after all route registrations) to parse and return clean error responses.
|
|
31
31
|
|
|
32
32
|
```typescript
|
|
33
|
-
//
|
|
33
|
+
// Inside app.ts or server.ts
|
|
34
34
|
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
|
|
35
35
|
const statusCode = err.statusCode || 500;
|
|
36
36
|
const message = err.message || 'Internal Server Error';
|
|
@@ -46,9 +46,9 @@ Tài liệu này quy định chiến lược xử lý lỗi bất đồng bộ (
|
|
|
46
46
|
|
|
47
47
|
---
|
|
48
48
|
|
|
49
|
-
## 🛡️
|
|
50
|
-
- **
|
|
51
|
-
- **
|
|
49
|
+
## 🛡️ Automated Validation with Zod Middleware
|
|
50
|
+
- **No Manual Conditional Checks:** Do not write scattered `if (!req.body.email)` conditionals inside controllers.
|
|
51
|
+
- **Zod Schema Middleware:** Implement a shared validation middleware that accepts a Zod schema to validate request segments (`body`, `query`, `params`) before they reach the Controller.
|
|
52
52
|
|
|
53
53
|
```typescript
|
|
54
54
|
import { AnyZodObject, ZodError } from 'zod';
|
|
@@ -57,14 +57,14 @@ Tài liệu này quy định chiến lược xử lý lỗi bất đồng bộ (
|
|
|
57
57
|
export const validateSchema = (schema: AnyZodObject) => {
|
|
58
58
|
return async (req: Request, res: Response, next: NextFunction): Promise<any> => {
|
|
59
59
|
try {
|
|
60
|
-
//
|
|
60
|
+
// Validate incoming request segments concurrently
|
|
61
61
|
const parsed = await schema.parseAsync({
|
|
62
62
|
body: req.body,
|
|
63
63
|
query: req.query,
|
|
64
64
|
params: req.params,
|
|
65
65
|
});
|
|
66
66
|
|
|
67
|
-
//
|
|
67
|
+
// Re-assign parsed and sanitized payloads
|
|
68
68
|
req.body = parsed.body;
|
|
69
69
|
req.query = parsed.query;
|
|
70
70
|
req.params = parsed.params;
|
|
@@ -74,7 +74,7 @@ Tài liệu này quy định chiến lược xử lý lỗi bất đồng bộ (
|
|
|
74
74
|
if (error instanceof ZodError) {
|
|
75
75
|
return res.status(400).json({
|
|
76
76
|
success: false,
|
|
77
|
-
message: '
|
|
77
|
+
message: 'Invalid input payload parameters',
|
|
78
78
|
errors: error.errors.map((err) => ({
|
|
79
79
|
field: err.path.join('.'),
|
|
80
80
|
message: err.message,
|
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Express.js Naming Conventions & Coding Style
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
This document defines coding conventions, directory layout, and TypeScript configurations for Express.js applications.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
## 🏷️
|
|
7
|
+
## 🏷️ Naming Conventions
|
|
8
8
|
|
|
9
|
-
###
|
|
10
|
-
|
|
9
|
+
### Directory Layout (3-Tier Architecture)
|
|
10
|
+
The codebase must be structured cleanly according to a 3-tier architecture layout:
|
|
11
11
|
```bash
|
|
12
12
|
src/
|
|
13
|
-
├── config/ #
|
|
14
|
-
├── middlewares/ #
|
|
15
|
-
├── models/ #
|
|
16
|
-
├── routes/ #
|
|
17
|
-
├── controllers/ #
|
|
18
|
-
├── services/ #
|
|
19
|
-
├── utils/ #
|
|
20
|
-
└── app.ts #
|
|
13
|
+
├── config/ # Environment configurations, DB initializations
|
|
14
|
+
├── middlewares/ # Express middleware functions (Auth, Log, Validation)
|
|
15
|
+
├── models/ # Database Schemas (Mongoose, Sequelize, or Prisma client)
|
|
16
|
+
├── routes/ # HTTP Route definitions and input middleware binding
|
|
17
|
+
├── controllers/ # Request parameter extraction, response formatting
|
|
18
|
+
├── services/ # Houses 100% of business logic and computations
|
|
19
|
+
├── utils/ # Standalone utility helper functions
|
|
20
|
+
└── app.ts # Express App setup and server bootstrapping
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
###
|
|
24
|
-
- **
|
|
25
|
-
- **
|
|
23
|
+
### Filename Notation
|
|
24
|
+
- **Consistency:** Use `kebab-case.ts` across all filenames in the repository.
|
|
25
|
+
- **Suffix Declarations:** Filenames must end with a suffix representing their architectural role:
|
|
26
26
|
- Controller: `user-controller.ts`
|
|
27
27
|
- Service: `user-service.ts`
|
|
28
28
|
- Route: `user-route.ts`
|
|
@@ -31,9 +31,9 @@ src/
|
|
|
31
31
|
|
|
32
32
|
---
|
|
33
33
|
|
|
34
|
-
## 📦
|
|
35
|
-
- **
|
|
34
|
+
## 📦 TypeScript & Type Declarations
|
|
35
|
+
- **Explicit Type Declarations:** Avoid implicit type inference. Always define types for `req`, `res`, and `next` parameters imported from `express`:
|
|
36
36
|
```typescript
|
|
37
37
|
import { Request, Response, NextFunction } from 'express';
|
|
38
38
|
```
|
|
39
|
-
- **
|
|
39
|
+
- **Strictly Ban the `any` Keyword:** Declare interfaces or types for all request bodies and API response structures.
|
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Architectural Boundaries (Router vs Controller vs Service)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
This document establishes boundaries and responsibilities for routers, controllers, and services in Express.js projects.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
## 🏛️
|
|
8
|
-
|
|
7
|
+
## 🏛️ Data Flow Chain
|
|
8
|
+
All features in the repository must comply with the standard 3-tier architecture data flow:
|
|
9
9
|
$$\text{Client} \longrightarrow \text{Router} \longrightarrow \text{Middleware} \longrightarrow \text{Controller} \longrightarrow \text{Service} \longrightarrow \text{Model/Database}$$
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
-
## 🚦
|
|
13
|
+
## 🚦 Layer Responsibilities
|
|
14
14
|
|
|
15
|
-
### 1.
|
|
16
|
-
- **
|
|
17
|
-
- **
|
|
15
|
+
### 1. Router Layer (`routes/`)
|
|
16
|
+
- **Role:** Exclusively responsible for mapping HTTP methods + paths and binding authentication or payload validation middlewares (e.g., Zod schemas).
|
|
17
|
+
- **Rule:** Under no circumstances should the Router layer house business calculations or database operations. It must only forward requests to the target Controller.
|
|
18
18
|
|
|
19
|
-
### 2.
|
|
20
|
-
- **
|
|
21
|
-
- **
|
|
22
|
-
-
|
|
23
|
-
-
|
|
19
|
+
### 2. Controller Layer (`controllers/`)
|
|
20
|
+
- **Role:** Responsible for extracting input payloads from the Express `req` object (`req.body`, `req.query`, `req.params`, `req.user`), forwarding these arguments to the Service layer, receiving outcomes, and responding to the client via `res.status().json()`.
|
|
21
|
+
- **Rules:**
|
|
22
|
+
- Never query database models or call ORM clients inside the Controller.
|
|
23
|
+
- Never write manual try/catch blocks (delegate errors to the global error handler using async wrappers).
|
|
24
24
|
|
|
25
|
-
### 3.
|
|
26
|
-
- **
|
|
27
|
-
- **
|
|
25
|
+
### 3. Service Layer (`services/`)
|
|
26
|
+
- **Role:** Houses 100% of the core business logic, coordinates data mutations, executes algorithms, and interacts with Database models.
|
|
27
|
+
- **Rule:** Never import, reference, or access Express-specific objects (`req`, `res`, or `next`) inside Services. The Service layer must remain completely decoupled from the web framework to maintain isolated testability.
|
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: express-endpoint
|
|
3
|
-
description:
|
|
3
|
+
description: Scaffold or extend a secure Express.js + TypeScript API endpoint including Router, Controller, and Validator
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
Follow this process to generate a new Express.js API Endpoint or extend an existing route.
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
- endpointName:
|
|
10
|
-
- routePath:
|
|
11
|
-
- httpMethod:
|
|
12
|
-
- targetPath:
|
|
8
|
+
Inputs:
|
|
9
|
+
- endpointName: Name of the API Endpoint to create (e.g., `user-profile`)
|
|
10
|
+
- routePath: HTTP route path of the API (e.g., `/api/v1/users/profile`)
|
|
11
|
+
- httpMethod: HTTP method (GET, POST, PUT, DELETE)
|
|
12
|
+
- targetPath: The destination path to place the code files
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
1.
|
|
16
|
-
2.
|
|
17
|
-
3.
|
|
18
|
-
4.
|
|
19
|
-
5.
|
|
20
|
-
6.
|
|
14
|
+
Steps:
|
|
15
|
+
1. Define a Zod Validation Schema under the `middlewares/` directory or alongside the controller to validate input payloads.
|
|
16
|
+
2. Implement the corresponding Service function under the `services/` directory to handle 100% of the business logic and ORM queries.
|
|
17
|
+
3. Implement the Controller dispatcher in the `controllers/` directory using the `asyncHandler` wrapper to forward errors automatically, extract inputs, and send JSON responses.
|
|
18
|
+
4. Register the Controller and mount the `validateSchema(zodSchema)` middleware on the target Route file under the `routes/` directory.
|
|
19
|
+
5. Create unit test suites for the Service and integration test suites (E2E) using Supertest.
|
|
20
|
+
6. Execute local validation:
|
|
21
21
|
- `{{runCommand}} lint`
|
|
22
22
|
- `{{runCommand}} typecheck`
|
|
23
23
|
- `{{runCommand}} test`
|