adonisjs-cli
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAdonisJS Ace CLI Guide
AdonisJS Ace CLI 指南
AdonisJS is a TypeScript-first Node.js framework for building server-side applications. Ace is the command-line framework embedded into AdonisJS core. This guide provides essential workflows and quick references for common AdonisJS operations.
AdonisJS是一个优先支持TypeScript的Node.js服务器端应用框架。Ace是嵌入AdonisJS核心的命令行框架。本指南提供了AdonisJS常见操作的核心工作流和快速参考。
Quick Start
快速开始
bash
undefinedbash
undefinedCreate new AdonisJS project
Create new AdonisJS project
npm init adonisjs@latest my-app
npm init adonisjs@latest my-app
Navigate to project
Navigate to project
cd my-app
cd my-app
Generate app key
Generate app key
node ace generate:key
node ace generate:key
Start development server
Start development server
node ace serve --hmr
node ace serve --hmr
List all available commands
List all available commands
node ace list
node ace list
Get help for a command
Get help for a command
node ace serve --help
undefinednode ace serve --help
undefinedCommon Workflows
常见工作流
Workflow 1: API Project Setup
工作流1:API项目搭建
bash
undefinedbash
undefinedCreate API project
Create API project
npm init adonisjs@latest my-api -- --kit=api
cd my-api
npm init adonisjs@latest my-api -- --kit=api
cd my-api
Generate app key
Generate app key
node ace generate:key
node ace generate:key
Install and configure database
Install and configure database
node ace add @adonisjs/lucid
node ace add @adonisjs/lucid
Create initial model with migration
Create initial model with migration
node ace make:model User -m
node ace make:model User -m
Run migrations
Run migrations
node ace migration:run
node ace migration:run
Start dev server with HMR
Start dev server with HMR
node ace serve --hmr
undefinednode ace serve --hmr
undefinedWorkflow 2: CRUD Resource Creation
工作流2:CRUD资源创建
bash
undefinedbash
undefinedCreate complete resource (model, migration, factory, controller)
Create complete resource (model, migration, factory, controller)
node ace make:model Post -mfc
node ace make:model Post -mfc
Create validators for the resource
Create validators for the resource
node ace make:validator post --resource
node ace make:validator post --resource
Create service for business logic
Create service for business logic
node ace make:service post
node ace make:service post
Edit migration file (database/migrations/xxxxx_posts.ts)
Edit migration file (database/migrations/xxxxx_posts.ts)
Add table columns
Add table columns
Run migration
Run migration
node ace migration:run
node ace migration:run
Create seeder for testing data
Create seeder for testing data
node ace make:seeder Post
node ace make:seeder Post
Run seeder
Run seeder
node ace db:seed
undefinednode ace db:seed
undefinedWorkflow 3: Database Management
工作流3:数据库管理
bash
undefinedbash
undefinedCreate migration
Create migration
node ace make:migration add_slug_to_posts
node ace make:migration add_slug_to_posts
Preview migration changes (dry run)
Preview migration changes (dry run)
node ace migration:run --dry-run
node ace migration:run --dry-run
Run migrations
Run migrations
node ace migration:run
node ace migration:run
Check migration status
Check migration status
node ace migration:status
node ace migration:status
Rollback last batch
Rollback last batch
node ace migration:rollback
node ace migration:rollback
Refresh database (reset + run)
Refresh database (reset + run)
node ace migration:refresh --seed
undefinednode ace migration:refresh --seed
undefinedWorkflow 4: Authentication Setup
工作流4:认证设置
bash
undefinedbash
undefinedInstall authentication package
Install authentication package
node ace add @adonisjs/auth
node ace add @adonisjs/auth
Install session support
Install session support
node ace add @adonisjs/session
node ace add @adonisjs/session
Create auth controllers
Create auth controllers
node ace make:controller auth/login
node ace make:controller auth/register
node ace make:controller auth/login
node ace make:controller auth/register
Create auth middleware
Create auth middleware
node ace make:middleware auth
node ace make:middleware auth
Run auth migrations
Run auth migrations
node ace migration:run
undefinednode ace migration:run
undefinedWorkflow 5: Production Build
工作流5:生产环境构建
bash
undefinedbash
undefinedBuild application
Build application
node ace build
node ace build
Navigate to build directory
Navigate to build directory
cd build
cd build
Install production dependencies
Install production dependencies
npm ci --production
npm ci --production
Run migrations in production
Run migrations in production
node ace migration:run --force
node ace migration:run --force
Start production server
Start production server
node server.js
undefinednode server.js
undefinedDecision Tree
决策树
When to use which command:
- To start development: Use
node ace serve --hmr - To create models: Use (includes migration, factory, controller)
node ace make:model Name -mfc - To create API controllers: Use
node ace make:controller name --resource --api - To manage database: Use migration commands (,
migration:run,migration:rollback)migration:status - To add packages: Use
node ace add @adonisjs/package-name - To validate input: Use
node ace make:validator name --resource - To view routes: Use
node ace list:routes --middleware - For detailed command syntax: See Commands Reference
- For implementation patterns: See Common Patterns
- For debugging: See Troubleshooting Guide
何时使用对应命令:
- 启动开发服务:使用
node ace serve --hmr - 创建模型:使用 (包含迁移、工厂、控制器)
node ace make:model Name -mfc - 创建API控制器:使用
node ace make:controller name --resource --api - 管理数据库:使用迁移命令(,
migration:run,migration:rollback)migration:status - 添加包:使用
node ace add @adonisjs/package-name - 验证输入:使用
node ace make:validator name --resource - 查看路由:使用
node ace list:routes --middleware - 获取详细命令语法:查看 Commands Reference
- 了解实现模式:查看 Common Patterns
- 调试问题:查看 Troubleshooting Guide
Common Patterns
常见模式
Creating Resource Controllers
创建资源控制器
bash
undefinedbash
undefinedRESTful API controller
RESTful API controller
node ace make:controller posts --resource --api
node ace make:controller posts --resource --api
Generates controller with:
Generates controller with:
- index() GET /posts
- index() GET /posts
- store() POST /posts
- store() POST /posts
- show() GET /posts/:id
- show() GET /posts/:id
- update() PUT /posts/:id
- update() PUT /posts/:id
- destroy() DELETE /posts/:id
- destroy() DELETE /posts/:id
undefinedundefinedModel Relationships
模型关联
typescript
// One-to-Many (User has many Posts)
// app/models/user.ts
@hasMany(() => Post)
declare posts: HasMany<typeof Post>
// app/models/post.ts
@belongsTo(() => User)
declare user: BelongsTo<typeof User>
// Query with relationships
const user = await User.query().preload('posts')
const post = await Post.query().preload('user').first()typescript
// One-to-Many (User has many Posts)
// app/models/user.ts
@hasMany(() => Post)
declare posts: HasMany<typeof Post>
// app/models/post.ts
@belongsTo(() => User)
declare user: BelongsTo<typeof User>
// Query with relationships
const user = await User.query().preload('posts')
const post = await Post.query().preload('user').first()Request Validation
请求验证
typescript
// Create validator: node ace make:validator post --resource
// app/validators/post.ts
import vine from '@vinejs/vine'
export const createPostValidator = vine.compile(
vine.object({
title: vine.string().minLength(3).maxLength(255),
content: vine.string().minLength(10),
isPublished: vine.boolean().optional(),
})
)
// Use in controller
const payload = await request.validateUsing(createPostValidator)typescript
// Create validator: node ace make:validator post --resource
// app/validators/post.ts
import vine from '@vinejs/vine'
export const createPostValidator = vine.compile(
vine.object({
title: vine.string().minLength(3).maxLength(255),
content: vine.string().minLength(10),
isPublished: vine.boolean().optional(),
})
)
// Use in controller
const payload = await request.validateUsing(createPostValidator)Database Migrations
数据库迁移
typescript
// Create table migration
export default class extends BaseSchema {
protected tableName = 'posts'
async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
table.string('title').notNullable()
table.text('content').notNullable()
table.integer('user_id').unsigned()
.references('users.id').onDelete('CASCADE')
table.timestamp('created_at')
table.timestamp('updated_at')
})
}
async down() {
this.schema.dropTable(this.tableName)
}
}typescript
// Create table migration
export default class extends BaseSchema {
protected tableName = 'posts'
async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
table.string('title').notNullable()
table.text('content').notNullable()
table.integer('user_id').unsigned()
.references('users.id').onDelete('CASCADE')
table.timestamp('created_at')
table.timestamp('updated_at')
})
}
async down() {
this.schema.dropTable(this.tableName)
}
}Authentication Patterns
认证模式
typescript
// Session-based login
export default class LoginController {
async store({ request, auth, response }: HttpContext) {
const { email, password } = request.only(['email', 'password'])
const user = await User.verifyCredentials(email, password)
await auth.use('web').login(user)
return response.redirect('/dashboard')
}
}
// API token generation
export default class TokensController {
async store({ request, response }: HttpContext) {
const { email, password } = request.only(['email', 'password'])
const user = await User.verifyCredentials(email, password)
const token = await User.accessTokens.create(user)
return response.created({ token: token.value!.release() })
}
}typescript
// Session-based login
export default class LoginController {
async store({ request, auth, response }: HttpContext) {
const { email, password } = request.only(['email', 'password'])
const user = await User.verifyCredentials(email, password)
await auth.use('web').login(user)
return response.redirect('/dashboard')
}
}
// API token generation
export default class TokensController {
async store({ request, response }: HttpContext) {
const { email, password } = request.only(['email', 'password'])
const user = await User.verifyCredentials(email, password)
const token = await User.accessTokens.create(user)
return response.created({ token: token.value!.release() })
}
}Troubleshooting
故障排除
Common Issues:
-
Server won't start
- Quick fix: Check if port is in use
lsof -i :3333 - Generate APP_KEY:
node ace generate:key - See: Server Issues
- Quick fix: Check if port is in use
-
Migration fails
- Quick fix: Check migration status
node ace migration:status - Verify database connection in
.env - See: Migration Fails
- Quick fix: Check migration status
-
Database connection refused
- Quick fix: Verify database is running and credentials
.env - Test connection:
psql -h localhost -U postgres - See: Cannot Connect to Database
- Quick fix: Verify database is running and
-
Validation always fails
- Quick fix: Ensure validator is compiled
vine.compile(schema) - Check field names match request data
- See: Validation Issues
- Quick fix: Ensure validator is compiled
-
Route not found (404)
- Quick fix: List routes with
node ace list:routes - Check route order (specific before wildcards)
- See: Route Not Found
- Quick fix: List routes with
For detailed troubleshooting steps, see the Troubleshooting Guide.
常见问题:
-
服务器无法启动
- 快速修复:检查端口是否被占用
lsof -i :3333 - 生成APP_KEY:
node ace generate:key - 查看:Server Issues
- 快速修复:检查端口是否被占用
-
迁移失败
- 快速修复:检查迁移状态
node ace migration:status - 验证中的数据库连接
.env - 查看:Migration Fails
- 快速修复:检查迁移状态
-
数据库连接被拒绝
- 快速修复:验证数据库是否运行以及中的凭据
.env - 测试连接:
psql -h localhost -U postgres - 查看:Cannot Connect to Database
- 快速修复:验证数据库是否运行以及
-
验证始终失败
- 快速修复:确保验证器已编译
vine.compile(schema) - 检查字段名称是否与请求数据匹配
- 查看:Validation Issues
- 快速修复:确保验证器已编译
-
路由未找到(404)
- 快速修复:使用列出路由
node ace list:routes - 检查路由顺序(特定路由优先于通配符路由)
- 查看:Route Not Found
- 快速修复:使用
如需详细故障排除步骤,请查看 Troubleshooting Guide。
Reference Files
参考文件
Load as needed for detailed information:
-
Commands Reference - Complete Ace CLI command documentation with all flags and options. Use when you need exact syntax, flag details, or comprehensive command documentation.
-
Common Patterns - Real-world patterns for CRUD resources, authentication, validation, relationships, events, testing, and production deployment. Use for implementing specific features or architectural patterns.
-
Troubleshooting Guide - Detailed error messages, diagnosis steps, and resolution strategies for server, database, authentication, routing, build, and performance issues. Use when encountering errors or unexpected behavior.
When to use each reference:
- Use Commands Reference when you need exact command syntax, flag combinations, or comprehensive CLI documentation
- Use Common Patterns for implementing CRUD operations, authentication flows, database relationships, or production deployments
- Use Troubleshooting when server won't start, migrations fail, authentication breaks, or you encounter build/performance issues
按需加载以获取详细信息:
-
Commands Reference - 完整的Ace CLI命令文档,包含所有标志和选项。当你需要确切语法、标志细节或全面的命令文档时使用。
-
Common Patterns - 用于CRUD资源、认证、验证、关联、事件、测试和生产部署的实际应用模式。用于实现特定功能或架构模式时使用。
-
Troubleshooting Guide - 针对服务器、数据库、认证、路由、构建和性能问题的详细错误信息、诊断步骤和解决策略。当遇到错误或意外行为时使用。
何时使用各参考文件:
- 当你需要确切的命令语法、标志组合或全面的CLI文档时,使用 Commands Reference
- 当实现CRUD操作、认证流程、数据库关联或生产部署时,使用 Common Patterns
- 当服务器无法启动、迁移失败、认证失效或遇到构建/性能问题时,使用 Troubleshooting
Resources
资源
- Official Docs: https://docs.adonisjs.com
- Ace CLI Docs: https://docs.adonisjs.com/guides/ace
- Lucid ORM: https://lucid.adonisjs.com
- GitHub: https://github.com/adonisjs/core
- Community: https://discord.gg/vDcEjq6
- 官方文档:https://docs.adonisjs.com
- Ace CLI文档:https://docs.adonisjs.com/guides/ace
- Lucid ORM:https://lucid.adonisjs.com
- GitHub:https://github.com/adonisjs/core
- 社区:https://discord.gg/vDcEjq6