also looking at this
Add BunPress guide and pre-E2E quality gates
#4
246 files
+1744
-64381
| @@ -1,549 +0,0 @@ | ||
| 1 | # Functions | |
| 2 | ||
| 3 | Functions in Stacks are server-side TypeScript files that handle business logic, API endpoints, and actions. They provide a simple, file-based approach to building your application's backend. | |
| 4 | ||
| 5 | ## Overview | |
| 6 | ||
| 7 | Stacks functions help you: | |
| 8 | ||
| 9 | - **Handle API requests** - Build REST endpoints | |
| 10 | - **Execute business logic** - Process data and perform operations | |
| 11 | - **Access databases** - Query and mutate data | |
| 12 | - **Integrate services** - Connect to external APIs | |
| 13 | ||
| 14 | ## Quick Start | |
| 15 | ||
| 16 | ### Creating a Function | |
| 17 | ||
| 18 | Functions live in `app/Functions/`: | |
| 19 | ||
| 20 | ```typescript | |
| 21 | // app/Functions/GetUsers.ts | |
| 22 | import { db } from '@stacksjs/database' | |
| 23 | import type { FunctionContext } from '@stacksjs/types' | |
| 24 | ||
| 25 | export default async function GetUsers(ctx: FunctionContext) { | |
| 26 | const users = await db | |
| 27 | .selectFrom('users') | |
| 28 | .select(['id', 'name', 'email']) | |
| 29 | .execute() | |
| 30 | ||
| 31 | return users | |
| 32 | } | |
| 33 | ``` | |
| 34 | ||
| 35 | ### Using Functions | |
| 36 | ||
| 37 | Functions are automatically available as API endpoints: | |
| 38 | ||
| 39 | ```typescript | |
| 40 | // GET /api/functions/GetUsers | |
| 41 | const response = await fetch('/api/functions/GetUsers') | |
| 42 | const users = await response.json() | |
| 43 | ``` | |
| 44 | ||
| 45 | Or call directly from other server code: | |
| 46 | ||
| 47 | ```typescript | |
| 48 | import GetUsers from '@/Functions/GetUsers' | |
| 49 | ||
| 50 | const users = await GetUsers(context) | |
| 51 | ``` | |
| 52 | ||
| 53 | ## Function Context | |
| 54 | ||
| 55 | Every function receives a context object: | |
| 56 | ||
| 57 | ```typescript | |
| 58 | import type { FunctionContext } from '@stacksjs/types' | |
| 59 | ||
| 60 | export default async function MyFunction(ctx: FunctionContext) { | |
| 61 | // Request data | |
| 62 | ctx.request // The incoming Request object | |
| 63 | ctx.body // Parsed request body | |
| 64 | ctx.params // URL parameters | |
| 65 | ctx.query // Query string parameters | |
| 66 | ctx.headers // Request headers | |
| 67 | ||
| 68 | // Authentication | |
| 69 | ctx.user // Authenticated user (if any) | |
| 70 | ctx.isAuthenticated // Boolean auth status | |
| 71 | ||
| 72 | // Utilities | |
| 73 | ctx.log // Logger instance | |
| 74 | ctx.cache // Cache instance | |
| 75 | } | |
| 76 | ``` | |
| 77 | ||
| 78 | ## Request Handling | |
| 79 | ||
| 80 | ### Query Parameters | |
| 81 | ||
| 82 | ```typescript | |
| 83 | // GET /api/functions/SearchUsers?q=john&page=1&limit=10 | |
| 84 | export default async function SearchUsers(ctx: FunctionContext) { | |
| 85 | const { q, page = '1', limit = '10' } = ctx.query | |
| 86 | ||
| 87 | const users = await db | |
| 88 | .selectFrom('users') | |
| 89 | .where('name', 'like', `%${q}%`) | |
| 90 | .limit(Number.parseInt(limit)) | |
| 91 | .offset((Number.parseInt(page) - 1) * Number.parseInt(limit)) | |
| 92 | .execute() | |
| 93 | ||
| 94 | return { | |
| 95 | data: users, | |
| 96 | page: Number.parseInt(page), | |
| 97 | limit: Number.parseInt(limit), | |
| 98 | } | |
| 99 | } | |
| 100 | ``` | |
| 101 | ||
| 102 | ### Request Body | |
| 103 | ||
| 104 | ```typescript | |
| 105 | // POST /api/functions/CreateUser | |
| 106 | interface CreateUserBody { | |
| 107 | name: string | |
| 108 | email: string | |
| 109 | password: string | |
| 110 | } | |
| 111 | ||
| 112 | export default async function CreateUser(ctx: FunctionContext) { | |
| 113 | const body = ctx.body as CreateUserBody | |
| 114 | ||
| 115 | // Validate | |
| 116 | if (!body.email || !body.password) { | |
| 117 | return ctx.error('Email and password are required', 400) | |
| 118 | } | |
| 119 | ||
| 120 | // Create user | |
| 121 | const user = await db | |
| 122 | .insertInto('users') | |
| 123 | .values({ | |
| 124 | name: body.name, | |
| 125 | email: body.email, | |
| 126 | password: await hash(body.password), | |
| 127 | }) | |
| 128 | .returning(['id', 'name', 'email']) | |
| 129 | .executeTakeFirst() | |
| 130 | ||
| 131 | return ctx.json(user, 201) | |
| 132 | } | |
| 133 | ``` | |
| 134 | ||
| 135 | ### URL Parameters | |
| 136 | ||
| 137 | ```typescript | |
| 138 | // GET /api/functions/GetUser/123 | |
| 139 | export default async function GetUser(ctx: FunctionContext) { | |
| 140 | const { id } = ctx.params | |
| 141 | ||
| 142 | const user = await db | |
| 143 | .selectFrom('users') | |
| 144 | .where('id', '=', Number(id)) | |
| 145 | .selectAll() | |
| 146 | .executeTakeFirst() | |
| 147 | ||
| 148 | if (!user) { | |
| 149 | return ctx.error('User not found', 404) | |
| 150 | } | |
| 151 | ||
| 152 | return user | |
| 153 | } | |
| 154 | ``` | |
| 155 | ||
| 156 | ## Response Helpers | |
| 157 | ||
| 158 | ### JSON Responses | |
| 159 | ||
| 160 | ```typescript | |
| 161 | export default async function MyFunction(ctx: FunctionContext) { | |
| 162 | // Simple return (auto-serialized to JSON) | |
| 163 | return { message: 'Hello' } | |
| 164 | ||
| 165 | // With status code | |
| 166 | return ctx.json({ message: 'Created' }, 201) | |
| 167 | ||
| 168 | // With headers | |
| 169 | return ctx.json(data, 200, { | |
| 170 | 'X-Custom-Header': 'value', | |
| 171 | }) | |
| 172 | } | |
| 173 | ``` | |
| 174 | ||
| 175 | ### Error Responses | |
| 176 | ||
| 177 | ```typescript | |
| 178 | export default async function MyFunction(ctx: FunctionContext) { | |
| 179 | // Simple error | |
| 180 | return ctx.error('Something went wrong', 500) | |
| 181 | ||
| 182 | // Validation errors | |
| 183 | return ctx.error({ | |
| 184 | message: 'Validation failed', | |
| 185 | errors: { | |
| 186 | email: ['Invalid email format'], | |
| 187 | password: ['Must be at least 8 characters'], | |
| 188 | }, | |
| 189 | }, 422) | |
| 190 | ||
| 191 | // Or throw exceptions | |
| 192 | if (!authorized) { | |
| 193 | throw new HttpException(403, 'Forbidden') | |
| 194 | } | |
| 195 | } | |
| 196 | ``` | |
| 197 | ||
| 198 | ### Redirect | |
| 199 | ||
| 200 | ```typescript | |
| 201 | export default async function MyFunction(ctx: FunctionContext) { | |
| 202 | // Temporary redirect (302) | |
| 203 | return ctx.redirect('/new-location') | |
| 204 | ||
| 205 | // Permanent redirect (301) | |
| 206 | return ctx.redirect('/new-location', 301) | |
| 207 | } | |
| 208 | ``` | |
| 209 | ||
| 210 | ## Authentication | |
| 211 | ||
| 212 | ### Protected Functions | |
| 213 | ||
| 214 | ```typescript | |
| 215 | // app/Functions/GetProfile.ts | |
| 216 | export default async function GetProfile(ctx: FunctionContext) { | |
| 217 | // Check authentication | |
| 218 | if (!ctx.isAuthenticated) { | |
| 219 | return ctx.error('Unauthorized', 401) | |
| 220 | } | |
| 221 | ||
| 222 | // Access the authenticated user | |
| 223 | const user = ctx.user | |
| 224 | ||
| 225 | return { | |
| 226 | id: user.id, | |
| 227 | name: user.name, | |
| 228 | email: user.email, | |
| 229 | } | |
| 230 | } | |
| 231 | ||
| 232 | // Export config to require auth | |
| 233 | export const config = { | |
| 234 | auth: true, // Requires authentication | |
| 235 | } | |
| 236 | ``` | |
| 237 | ||
| 238 | ### Authorization | |
| 239 | ||
| 240 | ```typescript | |
| 241 | export default async function AdminOnly(ctx: FunctionContext) { | |
| 242 | if (!ctx.isAuthenticated) { | |
| 243 | return ctx.error('Unauthorized', 401) | |
| 244 | } | |
| 245 | ||
| 246 | if (ctx.user.role !== 'admin') { | |
| 247 | return ctx.error('Forbidden', 403) | |
| 248 | } | |
| 249 | ||
| 250 | // Admin-only logic here | |
| 251 | return { secret: 'data' } | |
| 252 | } | |
| 253 | ``` | |
| 254 | ||
| 255 | ## Validation | |
| 256 | ||
| 257 | ### Manual Validation | |
| 258 | ||
| 259 | ```typescript | |
| 260 | import { validate } from '@stacksjs/validation' | |
| 261 | ||
| 262 | export default async function CreatePost(ctx: FunctionContext) { | |
| 263 | const errors = validate(ctx.body, { | |
| 264 | title: 'required|string|min:3|max:200', | |
| 265 | content: 'required|string|min:10', | |
| 266 | category: 'required|in:tech,news,lifestyle', | |
| 267 | }) | |
| 268 | ||
| 269 | if (errors) { | |
| 270 | return ctx.error({ message: 'Validation failed', errors }, 422) | |
| 271 | } | |
| 272 | ||
| 273 | // Proceed with valid data | |
| 274 | const post = await db.insertInto('posts').values(ctx.body).execute() | |
| 275 | ||
| 276 | return ctx.json(post, 201) | |
| 277 | } | |
| 278 | ``` | |
| 279 | ||
| 280 | ### Using Validators | |
| 281 | ||
| 282 | ```typescript | |
| 283 | import { CreatePostValidator } from '@/Validators/CreatePostValidator' | |
| 284 | ||
| 285 | export default async function CreatePost(ctx: FunctionContext) { | |
| 286 | const validated = await CreatePostValidator.validate(ctx.body) | |
| 287 | ||
| 288 | if (validated.failed) { | |
| 289 | return ctx.error(validated.errors, 422) | |
| 290 | } | |
| 291 | ||
| 292 | const post = await db.insertInto('posts').values(validated.data).execute() | |
| 293 | ||
| 294 | return ctx.json(post, 201) | |
| 295 | } | |
| 296 | ``` | |
| 297 | ||
| 298 | ## Database Operations | |
| 299 | ||
| 300 | ### Queries | |
| 301 | ||
| 302 | ```typescript | |
| 303 | import { db } from '@stacksjs/database' | |
| 304 | ||
| 305 | export default async function GetPosts(ctx: FunctionContext) { | |
| 306 | const { page = '1', category } = ctx.query | |
| 307 | ||
| 308 | let query = db | |
| 309 | .selectFrom('posts') | |
| 310 | .innerJoin('users', 'users.id', 'posts.author*id') | |
| 311 | .select([ | |
| 312 | 'posts.id', | |
| 313 | 'posts.title', | |
| 314 | 'posts.created*at', | |
| 315 | 'users.name as author', | |
| 316 | ]) | |
| 317 | .orderBy('posts.created*at', 'desc') | |
| 318 | ||
| 319 | if (category) { | |
| 320 | query = query.where('posts.category', '=', category) | |
| 321 | } | |
| 322 | ||
| 323 | const posts = await query | |
| 324 | .limit(10) | |
| 325 | .offset((Number.parseInt(page) - 1) * 10) | |
| 326 | .execute() | |
| 327 | ||
| 328 | return { data: posts, page: Number.parseInt(page) } | |
| 329 | } | |
| 330 | ``` | |
| 331 | ||
| 332 | ### Mutations | |
| 333 | ||
| 334 | ```typescript | |
| 335 | export default async function UpdateUser(ctx: FunctionContext) { | |
| 336 | const { id } = ctx.params | |
| 337 | const { name, email } = ctx.body | |
| 338 | ||
| 339 | const user = await db | |
| 340 | .updateTable('users') | |
| 341 | .set({ name, email, updated*at: new Date() }) | |
| 342 | .where('id', '=', Number(id)) | |
| 343 | .returning(['id', 'name', 'email']) | |
| 344 | .executeTakeFirst() | |
| 345 | ||
| 346 | if (!user) { | |
| 347 | return ctx.error('User not found', 404) | |
| 348 | } | |
| 349 | ||
| 350 | return user | |
| 351 | } | |
| 352 | ``` | |
| 353 | ||
| 354 | ### Transactions | |
| 355 | ||
| 356 | ```typescript | |
| 357 | export default async function TransferFunds(ctx: FunctionContext) { | |
| 358 | const { fromAccount, toAccount, amount } = ctx.body | |
| 359 | ||
| 360 | await db.transaction().execute(async (trx) => { | |
| 361 | // Debit from source | |
| 362 | await trx | |
| 363 | .updateTable('accounts') | |
| 364 | .set((eb) => ({ | |
| 365 | balance: eb('balance', '-', amount), | |
| 366 | })) | |
| 367 | .where('id', '=', fromAccount) | |
| 368 | .execute() | |
| 369 | ||
| 370 | // Credit to destination | |
| 371 | await trx | |
| 372 | .updateTable('accounts') | |
| 373 | .set((eb) => ({ | |
| 374 | balance: eb('balance', '+', amount), | |
| 375 | })) | |
| 376 | .where('id', '=', toAccount) | |
| 377 | .execute() | |
| 378 | ||
| 379 | // Record transaction | |
| 380 | await trx | |
| 381 | .insertInto('transactions') | |
| 382 | .values({ | |
| 383 | from*account: fromAccount, | |
| 384 | to*account: toAccount, | |
| 385 | amount, | |
| 386 | created_at: new Date(), | |
| 387 | }) | |
| 388 | .execute() | |
| 389 | }) | |
| 390 | ||
| 391 | return { success: true } | |
| 392 | } | |
| 393 | ``` | |
| 394 | ||
| 395 | ## Caching | |
| 396 | ||
| 397 | ```typescript | |
| 398 | export default async function GetDashboard(ctx: FunctionContext) { | |
| 399 | // Try cache first | |
| 400 | const cached = await ctx.cache.get('dashboard:stats') | |
| 401 | if (cached) { | |
| 402 | return cached | |
| 403 | } | |
| 404 | ||
| 405 | // Expensive computation | |
| 406 | const stats = await computeDashboardStats() | |
| 407 | ||
| 408 | // Cache for 5 minutes | |
| 409 | await ctx.cache.set('dashboard:stats', stats, 300) | |
| 410 | ||
| 411 | return stats | |
| 412 | } | |
| 413 | ``` | |
| 414 | ||
| 415 | ## Background Jobs | |
| 416 | ||
| 417 | ```typescript | |
| 418 | import { dispatch } from '@stacksjs/queue' | |
| 419 | ||
| 420 | export default async function CreateOrder(ctx: FunctionContext) { | |
| 421 | const order = await db | |
| 422 | .insertInto('orders') | |
| 423 | .values(ctx.body) | |
| 424 | .returning('*') | |
| 425 | .executeTakeFirst() | |
| 426 | ||
| 427 | // Dispatch background jobs | |
| 428 | await dispatch('SendOrderConfirmation', { orderId: order.id }) | |
| 429 | await dispatch('NotifyWarehouse', { orderId: order.id }) | |
| 430 | await dispatch('UpdateInventory', { items: ctx.body.items }) | |
| 431 | ||
| 432 | return ctx.json(order, 201) | |
| 433 | } | |
| 434 | ``` | |
| 435 | ||
| 436 | ## Function Configuration | |
| 437 | ||
| 438 | Export a config object to customize function behavior: | |
| 439 | ||
| 440 | ```typescript | |
| 441 | export default async function MyFunction(ctx: FunctionContext) { | |
| 442 | // Function logic | |
| 443 | } | |
| 444 | ||
| 445 | export const config = { | |
| 446 | // Require authentication | |
| 447 | auth: true, | |
| 448 | ||
| 449 | // Allowed HTTP methods | |
| 450 | methods: ['GET', 'POST'], | |
| 451 | ||
| 452 | // Rate limiting | |
| 453 | rateLimit: { | |
| 454 | max: 100, | |
| 455 | window: 60, // seconds | |
| 456 | }, | |
| 457 | ||
| 458 | // Middleware | |
| 459 | middleware: ['logging', 'cors'], | |
| 460 | ||
| 461 | // Timeout (seconds) | |
| 462 | timeout: 30, | |
| 463 | } | |
| 464 | ``` | |
| 465 | ||
| 466 | ## Error Handling | |
| 467 | ||
| 468 | ```typescript | |
| 469 | import { handleError } from '@stacksjs/error-handling' | |
| 470 | ||
| 471 | export default async function RiskyOperation(ctx: FunctionContext) { | |
| 472 | try { | |
| 473 | const result = await performRiskyOperation() | |
| 474 | return result | |
| 475 | } | |
| 476 | catch (error) { | |
| 477 | // Log and handle | |
| 478 | handleError(error, { | |
| 479 | message: 'Risky operation failed', | |
| 480 | shouldExit: false, | |
| 481 | }) | |
| 482 | ||
| 483 | // Return appropriate error response | |
| 484 | if (error instanceof ValidationError) { | |
| 485 | return ctx.error(error.message, 422) | |
| 486 | } | |
| 487 | ||
| 488 | if (error instanceof NotFoundError) { | |
| 489 | return ctx.error(error.message, 404) | |
| 490 | } | |
| 491 | ||
| 492 | return ctx.error('Internal server error', 500) | |
| 493 | } | |
| 494 | } | |
| 495 | ``` | |
| 496 | ||
| 497 | ## Testing Functions | |
| 498 | ||
| 499 | ```typescript | |
| 500 | // tests/Unit/GetUsersTest.ts | |
| 501 | import { describe, expect, it } from 'bun:test' | |
| 502 | import GetUsers from '@/Functions/GetUsers' | |
| 503 | import { createMockContext } from '@stacksjs/testing' | |
| 504 | ||
| 505 | describe('GetUsers', () => { | |
| 506 | it('returns users list', async () => { | |
| 507 | const ctx = createMockContext() | |
| 508 | ||
| 509 | const result = await GetUsers(ctx) | |
| 510 | ||
| 511 | expect(Array.isArray(result)).toBe(true) | |
| 512 | }) | |
| 513 | ||
| 514 | it('filters by query parameter', async () => { | |
| 515 | const ctx = createMockContext({ | |
| 516 | query: { role: 'admin' }, | |
| 517 | }) | |
| 518 | ||
| 519 | const result = await GetUsers(ctx) | |
| 520 | ||
| 521 | expect(result.every((u: any) => u.role === 'admin')).toBe(true) | |
| 522 | }) | |
| 523 | }) | |
| 524 | ``` | |
| 525 | ||
| 526 | ## Best Practices | |
| 527 | ||
| 528 | ### DO | |
| 529 | ||
| 530 | - **Keep functions focused** - One operation per function | |
| 531 | - **Validate input** - Never trust user input | |
| 532 | - **Handle errors** - Provide meaningful error responses | |
| 533 | - **Use types** - Type your context and responses | |
| 534 | - **Cache expensive operations** - Reduce database load | |
| 535 | ||
| 536 | ### DON'T | |
| 537 | ||
| 538 | - **Don't expose sensitive data** - Filter response fields | |
| 539 | - **Don't trust client data** - Always validate server-side | |
| 540 | - **Don't block the event loop** - Use async for I/O | |
| 541 | - **Don't catch and ignore errors** - Log or handle them | |
| 542 | ||
| 543 | ## Related Documentation | |
| 544 | ||
| 545 | - **[API Routes](/guide/routing)** - HTTP routing | |
| 546 | - **[Validation](/guide/validation)** - Input validation | |
| 547 | - **[Database](/guide/database)** - Database queries | |
| 548 | - **[Authentication](/guide/authentication)** - Auth system | |
| 549 | - **[Jobs](/basics/jobs)** - Background processing | |