also looking at this
Add BunPress guide and pre-E2E quality gates
#4
246 files
+1744
-64381
| @@ -1,655 +0,0 @@ | ||
| 1 | --- | |
| 2 | title: Actions | |
| 3 | description: Learn how to create and use Actions in Stacks applications | |
| 4 | --- | |
| 5 | // Get specific keys only | |
| 6 | const credentials = request.only<{ email: string; password: string }>([ | |
| 7 | 'email', | |
| 8 | 'password', | |
| 9 | ]) | |
| 10 | ||
| 11 | // Get all except specific keys | |
| 12 | const dataWithoutPassword = request.except<{ name: string; email: string }>([ | |
| 13 | 'password', | |
| 14 | ]) | |
| 15 | ||
| 16 | // Check if key exists | |
| 17 | if (request.has('remember')) { | |
| 18 | // ... | |
| 19 | } | |
| 20 | ||
| 21 | // Check if multiple keys exist | |
| 22 | if (request.has(['email', 'password'])) { | |
| 23 | // ... | |
| 24 | } | |
| 25 | ||
| 26 | // Check if any of the keys exist | |
| 27 | if (request.hasAny(['email', 'username'])) { | |
| 28 | // ... | |
| 29 | } | |
| 30 | ||
| 31 | // Check if key exists and is not empty | |
| 32 | if (request.filled('name')) { | |
| 33 | // ... | |
| 34 | } | |
| 35 | ||
| 36 | // Check if key is missing | |
| 37 | if (request.missing('optional_field')) { | |
| 38 | // ... | |
| 39 | } | |
| 40 | } | |
| 41 | ||
| 42 | ``` | |
| 43 | ||
| 44 | ### Type-Safe Input Methods | |
| 45 | ||
| 46 | ```typescript | |
| 47 | ||
| 48 | async handle(request: Request) { | |
| 49 | // String input | |
| 50 | const title = request.string('title', '') | |
| 51 | ||
| 52 | // Integer input | |
| 53 | const page = request.integer('page', 1) | |
| 54 | ||
| 55 | // Float input | |
| 56 | const price = request.float('price', 0.0) | |
| 57 | ||
| 58 | // Boolean input | |
| 59 | const active = request.boolean('active', false) | |
| 60 | ||
| 61 | // Array input | |
| 62 | const tags = request.array<string>('tags') | |
| 63 | } | |
| 64 | ||
| 65 | ``` | |
| 66 | ||
| 67 | ### Route Parameters | |
| 68 | ||
| 69 | Access route parameters: | |
| 70 | ||
| 71 | ```typescript | |
| 72 | ||
| 73 | // Route: /users/{id}/posts/{postId} | |
| 74 | async handle(request: Request) { | |
| 75 | const userId = request.params.id | |
| 76 | const postId = request.params.postId | |
| 77 | ||
| 78 | // Or using get method | |
| 79 | const id = request.get('id') | |
| 80 | } | |
| 81 | ||
| 82 | ``` | |
| 83 | ||
| 84 | ### File Uploads | |
| 85 | ||
| 86 | Handle file uploads: | |
| 87 | ||
| 88 | ```typescript | |
| 89 | ||
| 90 | async handle(request: Request) { | |
| 91 | // Get single file | |
| 92 | const avatar = request.file('avatar') | |
| 93 | ||
| 94 | if (avatar) { | |
| 95 | // Store file | |
| 96 | const path = await avatar.store('avatars') | |
| 97 | ||
| 98 | // Store with custom name | |
| 99 | const customPath = await avatar.storeAs('avatars', 'custom-name.jpg') | |
| 100 | ||
| 101 | // Get file properties | |
| 102 | console.log(avatar.name) // Original filename | |
| 103 | console.log(avatar.size) // File size in bytes | |
| 104 | console.log(avatar.type) // MIME type | |
| 105 | } | |
| 106 | ||
| 107 | // Check if file exists | |
| 108 | if (request.hasFile('document')) { | |
| 109 | const document = request.file('document') | |
| 110 | } | |
| 111 | ||
| 112 | // Get multiple files | |
| 113 | const images = request.getFiles('images') | |
| 114 | for (const image of images) { | |
| 115 | await image.store('gallery') | |
| 116 | } | |
| 117 | ||
| 118 | // Get all files | |
| 119 | const allFiles = request.allFiles() | |
| 120 | } | |
| 121 | ||
| 122 | ``` | |
| 123 | ||
| 124 | ### Authentication | |
| 125 | ||
| 126 | Access authenticated user: | |
| 127 | ||
| 128 | ```typescript | |
| 129 | ||
| 130 | async handle(request: Request) { | |
| 131 | // Get authenticated user (set by auth middleware) | |
| 132 | const user = await request.user() | |
| 133 | ||
| 134 | if (!user) { | |
| 135 | return response.unauthorized('Please log in') | |
| 136 | } | |
| 137 | ||
| 138 | // Get current access token | |
| 139 | const token = await request.userToken() | |
| 140 | ||
| 141 | // Check token abilities | |
| 142 | if (await request.tokenCan('posts:create')) { | |
| 143 | // User can create posts | |
| 144 | } | |
| 145 | ||
| 146 | if (await request.tokenCant('admin')) { | |
| 147 | return response.forbidden('Admin access required') | |
| 148 | } | |
| 149 | } | |
| 150 | ||
| 151 | ``` | |
| 152 | ||
| 153 | ## Validation | |
| 154 | ||
| 155 | ### Defining Validation Rules | |
| 156 | ||
| 157 | ```typescript | |
| 158 | ||
| 159 | import { schema } from '@stacksjs/validation' | |
| 160 | ||
| 161 | export default new Action({ | |
| 162 | validations: { | |
| 163 | // String validation | |
| 164 | name: { | |
| 165 | rule: schema.string().min(2).max(100), | |
| 166 | message: { | |
| 167 | min: 'Name is too short', | |
| 168 | max: 'Name is too long', | |
| 169 | }, | |
| 170 | }, | |
| 171 | ||
| 172 | // Email validation | |
| 173 | email: { | |
| 174 | rule: schema.string().email(), | |
| 175 | message: 'Invalid email address', | |
| 176 | }, | |
| 177 | ||
| 178 | // Number validation | |
| 179 | age: { | |
| 180 | rule: schema.number().min(18).max(120), | |
| 181 | message: { | |
| 182 | min: 'Must be at least 18', | |
| 183 | max: 'Invalid age', | |
| 184 | }, | |
| 185 | }, | |
| 186 | ||
| 187 | // Enum validation | |
| 188 | status: { | |
| 189 | rule: schema.enum(['active', 'inactive', 'pending']), | |
| 190 | message: 'Invalid status value', | |
| 191 | }, | |
| 192 | ||
| 193 | // Boolean validation | |
| 194 | acceptTerms: { | |
| 195 | rule: schema.boolean(), | |
| 196 | message: 'You must accept the terms', | |
| 197 | }, | |
| 198 | ||
| 199 | // Optional field | |
| 200 | nickname: { | |
| 201 | rule: schema.string().optional(), | |
| 202 | }, | |
| 203 | }, | |
| 204 | ||
| 205 | async handle(request) { | |
| 206 | // Validation runs automatically before handle() | |
| 207 | // If validation fails, returns 422 with errors | |
| 208 | }, | |
| 209 | }) | |
| 210 | ||
| 211 | ``` | |
| 212 | ||
| 213 | ### Validation Response | |
| 214 | ||
| 215 | When validation fails, the action returns a 422 response: | |
| 216 | ||
| 217 | ```json | |
| 218 | ||
| 219 | { | |
| 220 | "error": "Validation failed", | |
| 221 | "errors": { | |
| 222 | "email": ["Invalid email address"], | |
| 223 | "password": ["Password must be at least 8 characters"] | |
| 224 | } | |
| 225 | } | |
| 226 | ||
| 227 | ``` | |
| 228 | ||
| 229 | ## Response Helpers | |
| 230 | ||
| 231 | ### JSON Response | |
| 232 | ||
| 233 | ```typescript | |
| 234 | ||
| 235 | import { response } from '@stacksjs/router' | |
| 236 | ||
| 237 | async handle(request) { | |
| 238 | // Success response | |
| 239 | return response.json({ | |
| 240 | success: true, | |
| 241 | data: { id: 1, name: 'John' }, | |
| 242 | }) | |
| 243 | ||
| 244 | // With status code | |
| 245 | return response.json({ created: true }, 201) | |
| 246 | } | |
| 247 | ||
| 248 | ``` | |
| 249 | ||
| 250 | ### Text Response | |
| 251 | ||
| 252 | ```typescript | |
| 253 | ||
| 254 | async handle() { | |
| 255 | return response.text('Hello, World!') | |
| 256 | } | |
| 257 | ||
| 258 | ``` | |
| 259 | ||
| 260 | ### Error Responses | |
| 261 | ||
| 262 | ```typescript | |
| 263 | ||
| 264 | import { response } from '@stacksjs/router' | |
| 265 | ||
| 266 | async handle(request) { | |
| 267 | // 401 Unauthorized | |
| 268 | return response.unauthorized('Please log in') | |
| 269 | ||
| 270 | // 403 Forbidden | |
| 271 | return response.forbidden('Access denied') | |
| 272 | ||
| 273 | // 404 Not Found | |
| 274 | return response.notFound('Resource not found') | |
| 275 | ||
| 276 | // 422 Validation Error | |
| 277 | return response.validationError({ | |
| 278 | email: ['Email is required'], | |
| 279 | }) | |
| 280 | ||
| 281 | // 500 Server Error | |
| 282 | return response.serverError('Something went wrong') | |
| 283 | } | |
| 284 | ||
| 285 | ``` | |
| 286 | ||
| 287 | ### Custom Response | |
| 288 | ||
| 289 | ```typescript | |
| 290 | ||
| 291 | async handle() { | |
| 292 | return new Response(JSON.stringify({ custom: true }), { | |
| 293 | status: 200, | |
| 294 | headers: { | |
| 295 | 'Content-Type': 'application/json', | |
| 296 | 'X-Custom-Header': 'value', | |
| 297 | }, | |
| 298 | }) | |
| 299 | } | |
| 300 | ||
| 301 | ``` | |
| 302 | ||
| 303 | ## Action Composition | |
| 304 | ||
| 305 | ### Calling Other Actions | |
| 306 | ||
| 307 | ```typescript | |
| 308 | ||
| 309 | import { runAction } from '@stacksjs/actions' | |
| 310 | ||
| 311 | export default new Action({ | |
| 312 | name: 'Create Order', | |
| 313 | ||
| 314 | async handle(request) { | |
| 315 | // Create the order | |
| 316 | const order = await Order.create(request.all()) | |
| 317 | ||
| 318 | // Run another action | |
| 319 | await runAction('SendOrderConfirmation', { orderId: order.id }) | |
| 320 | ||
| 321 | // Or import and call directly | |
| 322 | const notifyAction = await import('./NotifyCustomerAction') | |
| 323 | await notifyAction.default.handle({ customerId: order.customerId }) | |
| 324 | ||
| 325 | return response.json({ order }) | |
| 326 | }, | |
| 327 | }) | |
| 328 | ||
| 329 | ``` | |
| 330 | ||
| 331 | ### Shared Logic | |
| 332 | ||
| 333 | Extract shared logic into helper functions: | |
| 334 | ||
| 335 | ```typescript | |
| 336 | ||
| 337 | // app/Actions/helpers/validation.ts | |
| 338 | export async function validateUser(userId: number): Promise<User | null> { | |
| 339 | const user = await User.find(userId) | |
| 340 | if (!user) { | |
| 341 | throw new HttpError(404, 'User not found') | |
| 342 | } | |
| 343 | return user | |
| 344 | } | |
| 345 | ||
| 346 | // app/Actions/User/UpdateUserAction.ts | |
| 347 | import { validateUser } from '../helpers/validation' | |
| 348 | ||
| 349 | export default new Action({ | |
| 350 | async handle(request) { | |
| 351 | const user = await validateUser(request.params.id) | |
| 352 | await user.update(request.all()) | |
| 353 | return response.json({ user }) | |
| 354 | }, | |
| 355 | }) | |
| 356 | ||
| 357 | ``` | |
| 358 | ||
| 359 | ## Dependency Injection | |
| 360 | ||
| 361 | ### Using Services | |
| 362 | ||
| 363 | ```typescript | |
| 364 | ||
| 365 | import { Action } from '@stacksjs/actions' | |
| 366 | import { PaymentService } from '@/services/PaymentService' | |
| 367 | import { EmailService } from '@/services/EmailService' | |
| 368 | ||
| 369 | export default new Action({ | |
| 370 | name: 'Process Payment', | |
| 371 | ||
| 372 | async handle(request) { | |
| 373 | const paymentService = new PaymentService() | |
| 374 | const emailService = new EmailService() | |
| 375 | ||
| 376 | const payment = await paymentService.process({ | |
| 377 | amount: request.get('amount'), | |
| 378 | currency: request.get('currency'), | |
| 379 | }) | |
| 380 | ||
| 381 | await emailService.sendReceipt(payment) | |
| 382 | ||
| 383 | return response.json({ payment }) | |
| 384 | }, | |
| 385 | }) | |
| 386 | ||
| 387 | ``` | |
| 388 | ||
| 389 | ### Configuration Access | |
| 390 | ||
| 391 | ```typescript | |
| 392 | ||
| 393 | import { config } from '@stacksjs/config' | |
| 394 | ||
| 395 | export default new Action({ | |
| 396 | async handle() { | |
| 397 | const apiKey = config.services.stripe.key | |
| 398 | const appName = config.app.name | |
| 399 | ||
| 400 | // Use configuration | |
| 401 | }, | |
| 402 | }) | |
| 403 | ||
| 404 | ``` | |
| 405 | ||
| 406 | ## Async Actions | |
| 407 | ||
| 408 | ### Long-Running Operations | |
| 409 | ||
| 410 | ```typescript | |
| 411 | ||
| 412 | export default new Action({ | |
| 413 | name: 'Generate Report', | |
| 414 | ||
| 415 | async handle(request) { | |
| 416 | // Start async operation | |
| 417 | const reportId = await Report.create({ | |
| 418 | status: 'processing', | |
| 419 | userId: request.get('userId'), | |
| 420 | }) | |
| 421 | ||
| 422 | // Dispatch to queue for background processing | |
| 423 | await job('GenerateReport', { reportId }).dispatch() | |
| 424 | ||
| 425 | // Return immediately | |
| 426 | return response.json({ | |
| 427 | message: 'Report generation started', | |
| 428 | reportId, | |
| 429 | }) | |
| 430 | }, | |
| 431 | }) | |
| 432 | ||
| 433 | ``` | |
| 434 | ||
| 435 | ### Streaming Responses | |
| 436 | ||
| 437 | ```typescript | |
| 438 | ||
| 439 | export default new Action({ | |
| 440 | name: 'Stream Data', | |
| 441 | ||
| 442 | async handle(request) { | |
| 443 | const stream = new ReadableStream({ | |
| 444 | async start(controller) { | |
| 445 | for (let i = 0; i < 100; i++) { | |
| 446 | controller.enqueue(`data: ${JSON.stringify({ count: i })}\n\n`) | |
| 447 | await new Promise(resolve => setTimeout(resolve, 100)) | |
| 448 | } | |
| 449 | controller.close() | |
| 450 | }, | |
| 451 | }) | |
| 452 | ||
| 453 | return new Response(stream, { | |
| 454 | headers: { | |
| 455 | 'Content-Type': 'text/event-stream', | |
| 456 | 'Cache-Control': 'no-cache', | |
| 457 | 'Connection': 'keep-alive', | |
| 458 | }, | |
| 459 | }) | |
| 460 | }, | |
| 461 | }) | |
| 462 | ||
| 463 | ``` | |
| 464 | ||
| 465 | ## Action Middleware | |
| 466 | ||
| 467 | ### Route-Level Middleware | |
| 468 | ||
| 469 | Apply middleware when routing to an action: | |
| 470 | ||
| 471 | ```typescript | |
| 472 | ||
| 473 | // routes/api.ts | |
| 474 | route.post('/admin/settings', 'Actions/Admin/UpdateSettingsAction') | |
| 475 | .middleware('auth') | |
| 476 | .middleware('abilities:admin') | |
| 477 | ||
| 478 | ``` | |
| 479 | ||
| 480 | ### Action-Based Authorization | |
| 481 | ||
| 482 | Check permissions within the action: | |
| 483 | ||
| 484 | ```typescript | |
| 485 | ||
| 486 | export default new Action({ | |
| 487 | async handle(request) { | |
| 488 | const user = await request.user() | |
| 489 | ||
| 490 | if (!user) { | |
| 491 | return response.unauthorized() | |
| 492 | } | |
| 493 | ||
| 494 | if (!await request.tokenCan('settings:update')) { | |
| 495 | return response.forbidden('Missing required permission') | |
| 496 | } | |
| 497 | ||
| 498 | // Proceed with action | |
| 499 | }, | |
| 500 | }) | |
| 501 | ||
| 502 | ``` | |
| 503 | ||
| 504 | ## Error Handling | |
| 505 | ||
| 506 | ### Throwing HTTP Errors | |
| 507 | ||
| 508 | ```typescript | |
| 509 | ||
| 510 | import { HttpError } from '@stacksjs/error-handling' | |
| 511 | ||
| 512 | export default new Action({ | |
| 513 | async handle(request) { | |
| 514 | const user = await User.find(request.params.id) | |
| 515 | ||
| 516 | if (!user) { | |
| 517 | throw new HttpError(404, 'User not found') | |
| 518 | } | |
| 519 | ||
| 520 | if (user.isDeleted) { | |
| 521 | throw new HttpError(410, 'User has been deleted') | |
| 522 | } | |
| 523 | ||
| 524 | return response.json({ user }) | |
| 525 | }, | |
| 526 | }) | |
| 527 | ||
| 528 | ``` | |
| 529 | ||
| 530 | ### Try-Catch Pattern | |
| 531 | ||
| 532 | ```typescript | |
| 533 | ||
| 534 | import { handleError } from '@stacksjs/error-handling' | |
| 535 | ||
| 536 | export default new Action({ | |
| 537 | async handle(request) { | |
| 538 | try { | |
| 539 | const result = await riskyOperation() | |
| 540 | return response.json({ result }) | |
| 541 | } catch (error) { | |
| 542 | handleError(error) | |
| 543 | return response.serverError('Operation failed') | |
| 544 | } | |
| 545 | }, | |
| 546 | }) | |
| 547 | ||
| 548 | ``` | |
| 549 | ||
| 550 | ## Edge Cases and Gotchas | |
| 551 | ||
| 552 | ### Request Body Consumption | |
| 553 | ||
| 554 | The request body can only be read once. Stacks handles this automatically, but be aware when using raw request methods: | |
| 555 | ||
| 556 | ```typescript | |
| 557 | ||
| 558 | async handle(request) { | |
| 559 | // Use request.all() or request.get() instead of request.json() | |
| 560 | const data = request.all() | |
| 561 | ||
| 562 | // Don't do this: | |
| 563 | // const body = await request.json() // May fail if already consumed | |
| 564 | } | |
| 565 | ||
| 566 | ``` | |
| 567 | ||
| 568 | ### Async Validation | |
| 569 | ||
| 570 | Validation runs synchronously before `handle()`. For async validation (like uniqueness checks), validate within the handler: | |
| 571 | ||
| 572 | ```typescript | |
| 573 | ||
| 574 | async handle(request) { | |
| 575 | const email = request.get('email') | |
| 576 | ||
| 577 | // Async uniqueness check | |
| 578 | const existing = await User.where('email', email).first() | |
| 579 | if (existing) { | |
| 580 | return response.validationError({ | |
| 581 | email: ['Email already in use'], | |
| 582 | }) | |
| 583 | } | |
| 584 | ||
| 585 | // Proceed with creation | |
| 586 | } | |
| 587 | ||
| 588 | ``` | |
| 589 | ||
| 590 | ### File Upload Limits | |
| 591 | ||
| 592 | Configure file upload limits in your server configuration: | |
| 593 | ||
| 594 | ```typescript | |
| 595 | ||
| 596 | // config/server.ts | |
| 597 | export default { | |
| 598 | maxRequestBodySize: 50 * 1024 * 1024, // 50MB | |
| 599 | } | |
| 600 | ||
| 601 | ``` | |
| 602 | ||
| 603 | ## API Reference | |
| 604 | ||
| 605 | ### Action Class | |
| 606 | ||
| 607 | ```typescript | |
| 608 | ||
| 609 | class Action { | |
| 610 | constructor(options: ActionOptions) | |
| 611 | ||
| 612 | name?: string | |
| 613 | description?: string | |
| 614 | method?: string | |
| 615 | path?: string | |
| 616 | validations?: ActionValidations | |
| 617 | rate?: string | |
| 618 | tries?: number | |
| 619 | backoff?: number | |
| 620 | enabled?: boolean | |
| 621 | model?: string | |
| 622 | handle: (request?: Request) => Promise<any> | any | |
| 623 | } | |
| 624 | ||
| 625 | ``` | |
| 626 | ||
| 627 | ### Request Methods | |
| 628 | ||
| 629 | | Method | Description | | |
| 630 | |--------|-------------| | |
| 631 | | `get(key, default?)` | Get input value | | |
| 632 | | `all()` | Get all input | | |
| 633 | | `only(keys)` | Get specific keys | | |
| 634 | | `except(keys)` | Exclude specific keys | | |
| 635 | | `has(key)` | Check key exists | | |
| 636 | | `hasAny(keys)` | Check any key exists | | |
| 637 | | `filled(key)` | Check key is not empty | | |
| 638 | | `missing(key)` | Check key is missing | | |
| 639 | | `string(key, default?)` | Get as string | | |
| 640 | | `integer(key, default?)` | Get as integer | | |
| 641 | | `float(key, default?)` | Get as float | | |
| 642 | | `boolean(key, default?)` | Get as boolean | | |
| 643 | | `array(key)` | Get as array | | |
| 644 | | `file(key)` | Get uploaded file | | |
| 645 | | `hasFile(key)` | Check file exists | | |
| 646 | | `user()` | Get authenticated user | | |
| 647 | | `tokenCan(ability)` | Check token ability | | |
| 648 | ||
| 649 | ## Related Documentation | |
| 650 | ||
| 651 | - [Routing](/basics/routing) - Route to action mapping | |
| 652 | - [Middleware](/basics/middleware) - Request middleware | |
| 653 | - [Validation](/packages/validation) - Validation rules | |
| 654 | - [Jobs](/basics/jobs) - Background job processing | |
| 655 | - [Error Handling](/basics/error-handling) - Error handling | |