Rust frontend integration: tipi shared
Tauri 2 permette di definire una sola volta i tipi di dato Rust, generare automaticamente i binding TypeScript e garantire type-safety totale tra frontend e backend. Zero runtime errors, refactoring sicuro, autocompletion IDE senza manuale API. Guida completa ai tipi shared in Tauri 2 + Rust Desktop Apps.
Answer-First: perché i tipi shared sono essenziali in Tauri
Nei desktop app tradizionali (Electron), il frontend JavaScript e il backend Node parlavano tramite IPC con stringhe grezze. Un cambio nel backend e il frontend crashava a runtime. In Tauri 2, definisci i tipi Rust una sola volta, e TypeScript li capisce automaticamente:
- Zero runtime errors: Compiler Rust + tsc TypeScript garantiscono che tipo inviato dal frontend combaci con il tipo atteso dal backend.
- Refactoring sicuro: Se aggiungi un campo a uno struct Rust, il compilatore ti obbliga a gestirlo nel frontend TypeScript, prima che il codice vada in produzione.
- Autocompletion IDE senza manuale: VSCode suggerisce field e metodi generati automaticamente dai binding TypeScript, zero documentazione out-of-sync.
- Riduzione boilerplate: Non scrivi mai validatori duplicati JavaScript per dati che il Rust compiler valida già.
- Integrazione Tauri invocation: I comandi Rust (via `#[tauri::command]`) hanno signature type-safe: il frontend conosce esattamente quale tipo aspettarsi in return.
Risultato pragmatico: App desktop Tauri + shared types riduce bug legati a mismatch API del 95%, e permette refactoring in poche ore invece che giorni.
1. Setup di un progetto Tauri con tipi shared
Inizia creando un nuovo progetto Tauri 2 con il template che supporta shared types out-of-box:
cargo create-tauri-app --template vanilla
cd frontend-name
cargo tauri init
La struttura risultante è:
project-root/
├── src-tauri/
│ ├── src/
│ │ ├── main.rs # Entry point Rust, invocation handlers
│ │ ├── commands.rs # Comandi Tauri (type-safe invocation)
│ │ └── models.rs # Struct/enum da condividere
│ ├── Cargo.toml
│ └── tauri.conf.json
├── src/
│ ├── bindings.ts # GENERATO AUTOMATICAMENTE: TypeScript bindings
│ └── App.tsx # Frontend React/Vue/Svelte
└── package.json
La magia accade in `bindings.ts`: Tauri legge i tipi Rust in fase di build e genera TypeScript definitions matching.
2. Definire struct Rust e serializzare con Serde
I tipi Rust da condividere devono essere serializzabili con Serde (JSON, binary, ecc.). In Tauri, userai JSON:
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct User {
pub id: u32,
pub name: String,
pub email: String,
pub created_at: String, // ISO8601 date
pub is_premium: bool,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserProfile {
pub user: User,
pub bio: String,
pub avatar_url: Option,
pub followers_count: usize,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum UserRole {
Admin,
Moderator,
User,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CreateUserRequest {
pub name: String,
pub email: String,
pub password: String, // NON INVIARE PASSWORD PLAINTEXT — hash server-side
}
Attributo `#[serde(rename_all = "camelCase")]` converte `created_at` (snake_case Rust) a `createdAt` (camelCase TypeScript), standard nei frontend.
3. Comandi Tauri type-safe con #[tauri::command]
Definisci i comandi Rust che il frontend invocherà. Ogni parametro e return value è type-checked:
use tauri::State;
use crate::models::{User, UserProfile, UserRole, CreateUserRequest};
#[tauri::command]
async fn get_user(user_id: u32) -> Result {
// Simula database lookup
if user_id == 0 {
return Err("Invalid user ID".to_string());
}
Ok(User {
id: user_id,
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
created_at: "2026-01-15T10:30:00Z".to_string(),
is_premium: true,
})
}
#[tauri::command]
async fn get_user_profile(user_id: u32) -> Result {
let user = get_user(user_id).await?;
Ok(UserProfile {
user,
bio: "Software Engineer".to_string(),
avatar_url: Some("https://example.com/avatar.jpg".to_string()),
followers_count: 150,
})
}
#[tauri::command]
async fn create_user(request: CreateUserRequest) -> Result {
// Validazione e hash password server-side
if request.email.is_empty() {
return Err("Email required".to_string());
}
Ok(User {
id: 1,
name: request.name,
email: request.email,
created_at: chrono::Utc::now().to_rfc3339(),
is_premium: false,
})
}
Registra i comandi in `main.rs`:
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
get_user,
get_user_profile,
create_user,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
4. Generare automaticamente TypeScript bindings
Tauri genera `bindings.ts` automaticamente durante il build. Esegui:
npm run tauri build
# oppure per dev watch
npm run tauri dev
Questo produce `src/bindings.ts`:
// AUTO-GENERATED da Tauri. NON EDITARE MANUALMENTE.
export interface User {
id: number;
name: string;
email: string;
createdAt: string; // snake_case → camelCase
isPremium: boolean;
}
export interface UserProfile {
user: User;
bio: string;
avatarUrl: string | null; // Option<T> → T | null
followersCount: number;
}
export enum UserRole {
Admin = 'Admin',
Moderator = 'Moderator',
User = 'User',
}
export interface CreateUserRequest {
name: string;
email: string;
password: string;
}
Questi type sono in TypeScript puro, non runtime, quindi il bundle frontend non appesantisce.
5. Invocare comandi dal frontend con type-safety
Nel tuo React/Vue/Svelte component, usa i binding generati:
import { invoke } from '@tauri-apps/api/core';
import type { User, UserProfile } from './bindings';
// Type-safe invocation
async function fetchUser(userId: number): Promise<User> {
try {
const user = await invoke<User>('get_user', { userId });
// TypeScript conosce esattamente quale tipo riceve
console.log(user.createdAt); // ✅ autocomplete riconosce field
console.log(user.invalidField); // ❌ TypeScript error!
return user;
} catch (error) {
console.error('Failed to fetch user:', error);
throw error;
}
}
async function fetchProfile(userId: number): Promise<UserProfile> {
const profile = await invoke<UserProfile>('get_user_profile', { userId });
return profile;
}
// Nel component React
import { useEffect, useState } from 'react';
export default function ProfileComponent() {
const [profile, setProfile] = useState<UserProfile | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchProfile(123).then(setProfile).finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading...</p>;
if (!profile) return <p>No profile found</p>;
return (
<div>
<h2>{profile.user.name}</h2>
<p>{profile.bio}</p>
<p>Followers: {profile.followersCount}</p>
</div>
);
}
6. Error handling con tipi custom
Definisci enum Rust per errori strutturati, poi trattali in TypeScript:
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UserError {
NotFound,
Unauthorized,
ValidationError(String),
InternalError,
}
#[tauri::command]
async fn get_user(user_id: u32) -> Result<User, UserError> {
if user_id == 0 {
return Err(UserError::ValidationError(
"User ID must be positive".to_string(),
));
}
// Lookup logic...
Err(UserError::NotFound) // Typed error
}
Nel frontend TypeScript:
export enum UserError {
NotFound = 'NOT_FOUND',
Unauthorized = 'UNAUTHORIZED',
ValidationError = 'VALIDATION_ERROR',
InternalError = 'INTERNAL_ERROR',
}
async function fetchUserSafe(userId: number): Promise<User | null> {
try {
const user = await invoke<User>('get_user', { userId });
return user;
} catch (error: unknown) {
const err = error as any;
if (err === UserError.NotFound) {
console.log('User not found');
} else if (err === UserError.Unauthorized) {
console.log('Not authorized');
}
return null;
}
}
7. Pattern avanzati: generics e trait bounds
Tauri supporta anche generic types per query/response wrapping:
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ApiResponse<T> {
pub status: u16,
pub data: Option<T>,
pub error: Option<String>,
pub timestamp: String,
}
#[tauri::command]
async fn get_user_response(user_id: u32) -> ApiResponse<User> {
match get_user(user_id).await {
Ok(user) => ApiResponse {
status: 200,
data: Some(user),
error: None,
timestamp: chrono::Utc::now().to_rfc3339(),
},
Err(e) => ApiResponse {
status: 400,
data: None,
error: Some(e),
timestamp: chrono::Utc::now().to_rfc3339(),
},
}
}
TypeScript generato:
export interface ApiResponse<T> {
status: number;
data: T | null;
error: string | null;
timestamp: string;
}
// Uso
const response = await invoke<ApiResponse<User>>('get_user_response', { userId });
if (response.status === 200 && response.data) {
console.log(response.data.name); // ✅ Type narrowing funziona
}
8. Testing con tipi shared
Scrivi unit test sia in Rust che in TypeScript per mantenere sincronizzazione:
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_get_user_valid_id() {
let result = get_user(1).await;
assert!(result.is_ok());
let user = result.unwrap();
assert_eq!(user.id, 1);
assert!(!user.name.is_empty());
}
#[tokio::test]
async fn test_get_user_invalid_id() {
let result = get_user(0).await;
assert!(result.is_err());
}
#[test]
fn test_user_serialization() {
let user = User {
id: 1,
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
created_at: "2026-01-15T10:30:00Z".to_string(),
is_premium: true,
};
let json = serde_json::to_string(&user).unwrap();
let deserialized: User = serde_json::from_str(&json).unwrap();
assert_eq!(user.id, deserialized.id);
}
}
Nel frontend:
import { describe, it, expect, beforeEach } from 'vitest';
import { invoke } from '@tauri-apps/api/core';
import type { User } from './bindings';
describe('User API', () => {
it('should fetch user with valid ID', async () => {
const user: User = await invoke('get_user', { userId: 1 });
expect(user.id).toBe(1);
expect(user.email).toBeDefined();
});
it('should reject invalid user ID', async () => {
try {
await invoke('get_user', { userId: 0 });
fail('Should throw error');
} catch (err) {
expect(err).toBeTruthy();
}
});
});
9. Troubleshooting comuni
Bindings non rigenerati dopo cambio tipi Rust: Pulisci la cache build:
cargo clean
npm run tauri dev
Tipo Option<T> Rust non mappaato correttamente in TypeScript: Assicurati che il tipo generico sia serializzabile. Usa `#[serde(skip_serializing_if = "Option::is_none")]` per omettere campi None nel JSON:
#[derive(Serialize, Deserialize)]
pub struct User {
pub id: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar_url: Option<String>,
}
Mismatch tra versioni di Serde nel backend e frontend: Assicurati che `Cargo.toml` pinni una versione Serde stabile:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
TypeScript non riconosce i binding: Verifica che `src/bindings.ts` esista e sia importato correttamente nel tuo punto di ingresso TypeScript.
10. Best practices
- Versionamento API: Aggiungi un campo versione agli struct per supportare evoluzione API senza rompere client vecchi.
- Validazione doppia: Valida input nel backend Rust (fonte di verità), non solo nel frontend TypeScript (user-friendly).
- Evita mutex globali: Usa `State<T>` di Tauri per gestire dati shared tra invocation handler, è thread-safe.
- Logging strutturato: Implementa logging Rust (tracing, log crate) per debuggare comunicazione IPC.
- Rate limiting: Applica rate limit lato Rust su comandi expensive (DB query, file I/O).
- Changelog tipi: Documenta ogni cambio struct/enum in un `TYPES_CHANGELOG.md` per team alignment.
FAQ: Tipi shared in Tauri 2
D: Posso usare lifetime parameters nei tipi shared?
R: No. Tauri serializza/deserializza i tipi via Serde, e JSON non supporta reference semantics. Usa owned types (`String` invece di `&str`).
D: Come gestisco circular references tra struct?
R: Evitale. Usa IDs come foreign key. Se A referenzia B, memorizza `b_id: u32` e lookup separato nel backend.
D: I bindings TypeScript sono treeshakeable nel bundle?
R: Sì. Sono type-only (TS), non runtime, quindi bundler li rimuove nel build ottimizzato.
D: Che accade se il frontend e backend si sincronizzano male?
R: Fallisce il parsing Serde server-side o il type-cast TypeScript (strict mode). Sempre rigenerato dopo `npm run tauri dev`.
D: Posso aggiungere custom derivate ai tipi?
R: Sì. Aggiungi derivate Serde custom o utilizza proc_macro per generare boilerplate.
Conclusione
I tipi shared in Tauri 2 trasformano la comunicazione IPC desktop da fragile e error-prone a robusta e refactor-safe. Non devi mai preoccuparti che il frontend invia un tipo che il backend non aspetta: il compilatore lo impedisce. Inizia semplice (struct e enum), evolvi verso generic type e pattern avanzati quando la complessità aumenta. Il risultato è app desktop più affidabili con meno bug e manutenzione più facile.

Commenti
Caricamento commenti...
Accedi per commentare