Context
Setiap handler dan middleware di GamanJS menerima object ctx (Context) yang berisi semua informasi request dan utility untuk mengakses data serta mengirim response.
Properti Utama
Section titled “Properti Utama”ctx.path
Section titled “ctx.path”Pathname dari URL (tanpa query string):
// Request: GET /users/123?active=truectx.path; // '/users/123'ctx.url
Section titled “ctx.url”Instance URL lengkap:
ctx.url.origin; // 'http://localhost:3431'ctx.url.pathname; // '/users/123'ctx.url.search; // '?active=true'ctx.request
Section titled “ctx.request”Informasi raw request:
ctx.request.id; // Request ID unik (auto-generated)ctx.request.method; // 'GET', 'POST', dllctx.request.url; // URL lengkap sebagai stringctx.request.pathname; // Pathnamectx.request.body(); // Promise<Buffer> — raw bodyRoute Parameters
Section titled “Route Parameters”ctx.param(name)
Section titled “ctx.param(name)”Ambil satu route parameter:
// Route: /users/:idr.get('/users/:id', (ctx) => { const id = ctx.param('id'); // '123' return ctx.send({ id }).ok();});ctx.params
Section titled “ctx.params”Semua route parameters sebagai object:
// Route: /posts/:postId/comments/:commentIdctx.params; // { postId: '1', commentId: '42' }Query Parameters
Section titled “Query Parameters”ctx.query
Section titled “ctx.query”Akses query parameter langsung:
// Request: GET /search?q=gaman&page=2ctx.query.q; // 'gaman'ctx.query.page; // '2'Jika parameter memiliki banyak nilai:
// Request: GET /filter?tag=js&tag=tsctx.query.tag; // ['js', 'ts']Request Body
Section titled “Request Body”ctx.json<T>()
Section titled “ctx.json<T>()”Parse body sebagai JSON:
async Create(ctx) { const body = await ctx.json<{ name: string; email: string }>(); // body.name, body.email return ctx.send(body).created();}ctx.text()
Section titled “ctx.text()”Baca body sebagai plain text:
async Webhook(ctx) { const raw = await ctx.text(); return ctx.send({ message: 'OK' }).ok();}Form Data & File
Section titled “Form Data & File”ctx.formData()
Section titled “ctx.formData()”Parse body sebagai FormData (mendukung multipart/form-data dan application/x-www-form-urlencoded).
ctx.input(name)
Section titled “ctx.input(name)”Ambil satu string value dari form data:
const email = await ctx.input('email'); // string | nullctx.inputs(name)
Section titled “ctx.inputs(name)”Ambil banyak string values dari form data:
const tags = await ctx.inputs('tags'); // string[]ctx.file(name)
Section titled “ctx.file(name)”Ambil satu file dari form data:
const avatar = await ctx.file('avatar'); // GFile | nullctx.files(name)
Section titled “ctx.files(name)”Ambil banyak file dari form data:
const images = await ctx.files('images'); // GFile[]Headers
Section titled “Headers”ctx.header(key)
Section titled “ctx.header(key)”Ambil value request header tertentu (case-insensitive):
const token = ctx.header('Authorization'); // string | nullctx.headers
Section titled “ctx.headers”Instance GamanHeader untuk akses dan manipulasi header:
// Bacactx.headers.get('Content-Type');
// Set response headerctx.headers.set('X-Custom-Header', 'value');Cookies
Section titled “Cookies”ctx.cookies
Section titled “ctx.cookies”Instance CookieMap dari Bun untuk akses dan pengaturan cookies:
// Bacaconst session = ctx.cookies.get('session_id');
// Setctx.cookies.set('session_id', 'abc-123', { httpOnly: true });Data Store
Section titled “Data Store”Middleware dan handler bisa berbagi data via context store:
ctx.set(key, value) / ctx.get<T>(key)
Section titled “ctx.set(key, value) / ctx.get<T>(key)”ctx.set('user', { id: 1, name: 'Angga' });const user = ctx.get('user');Response
Section titled “Response”ctx.send(data?)
Section titled “ctx.send(data?)”Cara utama untuk mengirim response. Mengembalikan GamanResponseBuilder.
return ctx.send({ success: true }).ok();Contoh Lengkap
Section titled “Contoh Lengkap”import { composeController } from 'gaman/compose';import { AppService } from '../services/AppService';
export default (appService: AppService) => ({ async CreatePost(ctx) { // Route params const userId = ctx.param('userId');
// Query const draft = ctx.query.draft === 'true';
// Body const body = await ctx.json<{ title: string }>();
// Headers const token = ctx.header('Authorization');
// Set response header ctx.headers.set('X-Processed-By', 'GamanJS');
// Data dari middleware const currentUser = ctx.get('user');
return ctx.send({ userId, draft, title: body.title, author: currentUser.name, }).created(); },});