Lewati ke konten

Context

Setiap handler dan middleware di GamanJS menerima object ctx (Context) yang berisi semua informasi request dan utility untuk mengakses data serta mengirim response.

Pathname dari URL (tanpa query string):

// Request: GET /users/123?active=true
ctx.path; // '/users/123'

Instance URL lengkap:

ctx.url.origin; // 'http://localhost:3431'
ctx.url.pathname; // '/users/123'
ctx.url.search; // '?active=true'

Informasi raw request:

ctx.request.id; // Request ID unik (auto-generated)
ctx.request.method; // 'GET', 'POST', dll
ctx.request.url; // URL lengkap sebagai string
ctx.request.pathname; // Pathname
ctx.request.body(); // Promise<Buffer> — raw body

Ambil satu route parameter:

// Route: /users/:id
r.get('/users/:id', (ctx) => {
const id = ctx.param('id'); // '123'
return ctx.send({ id }).ok();
});

Semua route parameters sebagai object:

// Route: /posts/:postId/comments/:commentId
ctx.params; // { postId: '1', commentId: '42' }

Akses query parameter langsung:

// Request: GET /search?q=gaman&page=2
ctx.query.q; // 'gaman'
ctx.query.page; // '2'

Jika parameter memiliki banyak nilai:

// Request: GET /filter?tag=js&tag=ts
ctx.query.tag; // ['js', 'ts']

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();
}

Baca body sebagai plain text:

async Webhook(ctx) {
const raw = await ctx.text();
return ctx.send({ message: 'OK' }).ok();
}

Parse body sebagai FormData (mendukung multipart/form-data dan application/x-www-form-urlencoded).

Ambil satu string value dari form data:

const email = await ctx.input('email'); // string | null

Ambil banyak string values dari form data:

const tags = await ctx.inputs('tags'); // string[]

Ambil satu file dari form data:

const avatar = await ctx.file('avatar'); // GFile | null

Ambil banyak file dari form data:

const images = await ctx.files('images'); // GFile[]

Ambil value request header tertentu (case-insensitive):

const token = ctx.header('Authorization'); // string | null

Instance GamanHeader untuk akses dan manipulasi header:

// Baca
ctx.headers.get('Content-Type');
// Set response header
ctx.headers.set('X-Custom-Header', 'value');

Instance CookieMap dari Bun untuk akses dan pengaturan cookies:

// Baca
const session = ctx.cookies.get('session_id');
// Set
ctx.cookies.set('session_id', 'abc-123', { httpOnly: true });

Middleware dan handler bisa berbagi data via context store:

ctx.set('user', { id: 1, name: 'Angga' });
const user = ctx.get('user');

Cara utama untuk mengirim response. Mengembalikan GamanResponseBuilder.

return ctx.send({ success: true }).ok();
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();
},
});