### Create HTTP Server with File-Based Routing and Middleware (Buntal JS) Source: https://buntaljs.org/docs/guides/http-server This snippet demonstrates how to initialize an HTTP server using Buntal JS, enabling file-based routing by specifying an 'appDir'. It also shows how to apply global middleware like CORS and logging, and defines a declarative GET endpoint with type-safe parameters. ```typescript import { Http } from '@buntal/http' import { cors, logger } from '@buntal/http/middlewares' // initialize the HTTP server const app = new Http({ port: 4001, appDir: './app' // Enable file-based routing! }) // add middlewares app.use(cors()) app.use(logger()) // define a simple GET endpoint with a type-safe params app.get('/hello/:name', (req, res) => { return res.json({ hello: `Hello ${req.params.name}` }) }) // start the server! app.start((server) => { console.log(`Server running at http://localhost:${server.port}`) }) ``` -------------------------------- ### Define Ping Endpoint using File-Based Routing (Buntal JS) Source: https://buntaljs.org/docs/guides/http-server This example shows how to create a simple ping endpoint within the './app/ping.ts' file. Buntal JS automatically loads this file for file-based routing, responding with a JSON object containing 'pong: 1' when the endpoint is accessed. ```typescript import { h } from '@buntal/http' export const GET = h( (req, res) => res.json({ pong: 1 }) ) ``` -------------------------------- ### Set HTTP Status Code and Send Response in BuntalJS Source: https://buntaljs.org/docs/guides/http-server Sets the HTTP status code for the response and allows chaining other response methods like sending JSON. The example demonstrates setting a 400 Bad Request status and returning a JSON error object. ```javascript export const GET = h((req, res) => res .status(400) .json({ error: 'Bad Request' }) ) ``` -------------------------------- ### Use Context for Type-Safe Data Passing in Handlers (Buntal JS) Source: https://buntaljs.org/docs/guides/http-server This example demonstrates the use of the 'context' object within Buntal JS handlers for passing data between middleware and the final handler. It simulates an authorization check and then sets user data in the context, making it accessible in a type-safe manner in subsequent handlers. ```typescript type User = { id: string name: string } export const GET = h<{}, User>( (req, res) => { if (!req.headers.get('Authorization')) { // simulate authorization check return res.status(401).json({ error: 'Unauthorized' }) } req.context = { id: '123', name: 'John Doe' } }, (req, res) => res.json({ name: req.context?.user.name // access a type-safe context }) ) ``` -------------------------------- ### Set Custom Headers in BuntalJS Response Source: https://buntaljs.org/docs/guides/http-server Sets custom headers for the HTTP response. This method is chainable, allowing multiple headers to be set before sending the response body. The example sets 'Cache-Control' and a custom 'X-Custom-Header'. ```javascript export const GET = h((req, res) => res .headers({ 'Cache-Control': 'no-cache', 'X-Custom-Header': 'MyValue', }) .json({ message: 'Hello, World!' }) ) ``` -------------------------------- ### Initialize BuntalJS Project Source: https://buntaljs.org/docs/guides/full-stack-web Command to scaffold a new BuntalJS project using the official CLI template. ```bash bun create buntal@latest my-app ``` -------------------------------- ### Create Index Page Source: https://buntaljs.org/docs/guides/full-stack-web The index.tsx file serves as the entry point for a route. It accepts props like query and params to handle dynamic content. ```tsx export default function HomePage({ query }: Readonly<{ query: Record }>) { return (

Next.js who? —{query.name || 'Buntal'}

) } ``` -------------------------------- ### Response Methods Source: https://buntaljs.org/docs/guides/http-server Methods for sending data and configuring the HTTP response lifecycle. ```APIDOC ## json(data) ### Description Sends a JSON response with the provided data and automatically sets the Content-Type header to application/json. ### Parameters - **data** (Object/Array) - Required - The payload to be serialized as JSON. ## text(data) ### Description Sends a plain text response with the provided data and automatically sets the Content-Type header to text/plain. ### Parameters - **data** (String) - Required - The text content to send. ## status(code) ### Description Sets the HTTP status code for the response. This method is chainable. ### Parameters - **code** (Number) - Required - The HTTP status code (e.g., 200, 400, 500). ## headers(headers) ### Description Sets custom headers for the response. This method is chainable. ### Parameters - **headers** (Object) - Required - An object containing key-value pairs of headers to set. ## cookie(name, value, options) ### Description Sets a cookie in the response. If the value is null, the cookie is deleted. ### Parameters - **name** (String) - Required - The name of the cookie. - **value** (String|null) - Required - The value of the cookie. - **options** (Object) - Optional - Cookie configuration (e.g., maxAge, httpOnly, path). ``` -------------------------------- ### Define Root Layout Source: https://buntaljs.org/docs/guides/full-stack-web The layout.tsx file provides a consistent structure for the application, wrapping page content. It is required to define the HTML shell for the application. ```tsx export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) { return ( Buntal App {children} ) } ``` -------------------------------- ### Implement Server-Side Data Fetching Source: https://buntaljs.org/docs/guides/full-stack-web The $ function allows for server-side data fetching before page rendering. It receives the request object and returns data to the page component. ```tsx import type { Req } from '@buntal/http' export const $ = async (req: Req) => { const resp = await fetch(`https://api.example/data/${req.params.id}`) return await resp.json() as { name: string } } export default function HomePage({ data }: { data?: Awaited> }) { return (
Hello, {data?.name || 'there'}!
) } ``` -------------------------------- ### Send JSON Response with BuntalJS Source: https://buntaljs.org/docs/guides/http-server Sends a JSON response with the provided data. BuntalJS automatically sets the 'Content-Type' header to 'application/json'. This is useful for API endpoints returning structured data. ```javascript res.json({ data: 'some value' }); ``` -------------------------------- ### Implement Custom Middleware with Request Validation (Buntal JS) Source: https://buntaljs.org/docs/guides/http-server This code illustrates how to create a custom middleware function in Buntal JS using the 'h' higher-order function. The middleware checks for a specific query parameter ('name') and returns a 403 Forbidden error if it's not 'John', otherwise it proceeds to the next handler. ```typescript import { h } from '@buntal/http' export const GET = h( (req, res) => { console.log('Hi, this is a middleware!') if (req.query.name !== 'John') { return res.status(403).json({ error: 'Forbidden' }) } }, (req, res) => res.json({ pong: 1 }) ) ``` -------------------------------- ### Send Text Response with BuntalJS Source: https://buntaljs.org/docs/guides/http-server Sends a plain text response with the provided data. BuntalJS automatically sets the 'Content-Type' header to 'text/plain'. This is suitable for simple text-based responses. ```javascript res.text('Hello, World!'); ``` -------------------------------- ### Set or Delete Cookie in BuntalJS Response Source: https://buntaljs.org/docs/guides/http-server Sets a cookie in the response. If the value is null, the cookie is deleted. Otherwise, it sets the cookie with the specified name, value, and options like maxAge, httpOnly, and path. ```javascript res.cookie('access_token', token, { maxAge: 60 * 60 * 2, // 2 hours httpOnly: true, path: '/' }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.