VelaVela
Cloudflare

R2

Use Cloudflare R2 object storage in your Vela application.

The R2Module provides a managed R2Service for interacting with Cloudflare R2 buckets.

Setup

Import the module and configure the binding name:

import { Module } from '@velajs/vela';
import { R2Module } from '@velajs/cloudflare';

@Module({
  imports: [R2Module.forRoot({ binding: 'MY_BUCKET' })],
})
class AppModule {}

Add the R2 bucket to wrangler.toml:

[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "my-bucket"

Using R2Service

Inject R2Service into any provider or controller:

import { Controller, Get, Post, Param, Body } from '@velajs/vela';
import { R2Service } from '@velajs/cloudflare';

@Controller('files')
class FilesController {
  constructor(private readonly r2: R2Service) {}

  @Get(':key')
  async download(@Param('key') key: string) {
    const object = await this.r2.get(key);
    if (!object) return { error: 'Not found' };
    return object.body;
  }

  @Post(':key')
  async upload(@Param('key') key: string, @Body() body: ReadableStream) {
    await this.r2.put(key, body);
    return { success: true };
  }
}

Methods

MethodDescription
get(key)Retrieve an object. Returns the object with its body and metadata, or null.
head(key)Retrieve object metadata without downloading the body.
put(key, value, options?)Upload an object. Options support httpMetadata, customMetadata, and md5.
delete(key)Delete an object.
list(options?)List objects. Options support prefix, limit, cursor, and delimiter.
Edit on GitHub

Last updated on

On this page