Cloudflare
D1
Use Cloudflare D1 databases in your Vela application.
The D1Module provides a managed D1Service for interacting with Cloudflare D1 SQL databases.
Setup
Import the module and configure the binding name:
import { Module } from '@velajs/vela';
import { D1Module } from '@velajs/cloudflare';
@Module({
imports: [D1Module.forRoot({ binding: 'MY_DB' })],
})
class AppModule {}Add the D1 database to wrangler.toml:
[[d1_databases]]
binding = "MY_DB"
database_name = "my-db"
database_id = "xxx"Using D1Service
Inject D1Service into any provider or controller:
import { Controller, Get, Post, Body, Param } from '@velajs/vela';
import { D1Service } from '@velajs/cloudflare';
@Controller('users')
class UsersController {
constructor(private readonly db: D1Service) {}
@Get()
async findAll() {
const stmt = this.db.prepare('SELECT * FROM users');
const { results } = await stmt.all();
return results;
}
@Get(':id')
async findOne(@Param('id') id: string) {
const stmt = this.db.prepare('SELECT * FROM users WHERE id = ?').bind(id);
return stmt.first();
}
@Post()
async create(@Body() body: { name: string; email: string }) {
const stmt = this.db
.prepare('INSERT INTO users (name, email) VALUES (?, ?)')
.bind(body.name, body.email);
return stmt.run();
}
}Methods
| Method | Description |
|---|---|
prepare(sql) | Create a prepared statement. Chain .bind() to add parameters, then .all(), .first(), .raw(), or .run() to execute. |
batch(statements) | Execute multiple prepared statements in a single transaction. |
exec(sql) | Execute raw SQL (useful for multi-statement scripts like migrations). |
dump() | Export the entire database as a raw SQL file. |
KV
Use Cloudflare KV namespaces in your Vela application.
R2
Use Cloudflare R2 object storage in your Vela application.
Edit on GitHub
Last updated on