Skip to content

FormData adapter

Use the @FormData() parameter decorator to extract multipart payloads into a typed object. It works on handler parameters inside controllers.

Import

ts
import { FormData, type FormDataPayload } from "@bunstone";

Usage

ts
class UploadController {
  @Post("/upload")
  upload(
    @FormData({
      fileField: "files", // optional: specific field to read files from
      allowedTypes: ["image/avif"], // optional: mime or extensions allowed
      jsonField: "meta", // optional: parse this field as JSON
    })
    payload: FormDataPayload
  ) {
    // payload.files: File[]
    // payload.json: parsed JSON from jsonField, if provided
  }
}

Options

  • fileField (string): Only read files from this field. Defaults to all file values in the form.
  • allowedTypes (string[]): Allowed MIME types or extensions. Rejects others with a bad request.
  • jsonField (string): Field name to parse as JSON. Rejects non-string or invalid JSON.

Payload shape

ts
type FormDataPayload = {
  files: File[];
  json?: unknown;
};

Practical Example

Explore form-data handling with multiple fields:

ts
import {
  Module,
  Controller,
  Post,
  Get,
  AppStartup,
  CacheAdapter,
  FormData,
} from "../../index";

@Controller("cache")
class CacheController {
  constructor(private readonly cache: CacheAdapter) {}

  @Get(":key")
  async getCache(key: string) {
    const value = await this.cache.get(key);
    return { key, value };
  }

  @Post(":key")
  async setCache(key: string, @Body() body: any) {
    await this.cache.set(key, body, { ttlSeconds: 60 });
    return { success: true };
  }
}

@Controller("upload")
class UploadController {
  @Post()
  async uploadFile(@FormData() formData: any) {
    // Access form fields and files
    const { fields, files } = formData;
    return {
      receivedFields: Object.keys(fields),
      receivedFiles: Object.keys(files),
    };
  }
}

@Module({
  controllers: [CacheController, UploadController],
  providers: [CacheAdapter],
})
class AppModule {}

const app = AppStartup.create(AppModule);
console.log("Adapters example configured.");

See it on GitHub

Released under the MIT License.