Skip to main content
Questa pagina fa parte di una skill per agenti di codifica IA ed è scritta per gli agenti, non per gli esseri umani. Per la documentazione Base44 leggibile dagli umani, consulta la documentazione per sviluppatori.

Modulo Entities

Operazioni CRUD sui modelli di dati. Accedi tramite base44.entities.EntityName.method().

Contenuti

Metodi

Nota: il limite massimo per list() e filter() è 5.000 elementi per richiesta.
MetodoFirmaDescrizione
create(data)Promise<T>Crea un record
bulkCreate(dataArray)Promise<T[]>Crea più record
list(sort?, limit?, skip?, fields?)Promise<Pick<T, K>[]>Ottieni tutti i record (paginati)
filter(query, sort?, limit?, skip?, fields?)Promise<Pick<T, K>[]>Ottieni i record che soddisfano le condizioni
get(id)Promise<T>Ottieni un singolo record per ID
update(id, data)Promise<T>Aggiorna il record (aggiornamento parziale)
updateMany(query, data)Promise<UpdateManyResult>Aggiorna tutti i record corrispondenti usando operatori di aggiornamento MongoDB
bulkUpdate(dataArray)Promise<T[]>Aggiorna più record per ID, ciascuno con i propri dati
delete(id)Promise<DeleteResult>Elimina un record per ID
deleteMany(query)Promise<DeleteManyResult>Elimina tutti i record corrispondenti
importEntities(file)Promise<ImportResult<T>>Importa da CSV (solo frontend)
subscribe(callback)() => voidSottoscrivi aggiornamenti in tempo reale (restituisce funzione di disiscrizione)

Esempi

Creazione

const task = await base44.entities.Task.create({
  title: "Complete documentation",
  status: "pending",
  dueDate: "2024-12-31"
});

Creazione multipla

const tasks = await base44.entities.Task.bulkCreate([
  { title: "Task 1", status: "pending" },
  { title: "Task 2", status: "pending" }
]);

Elenco con paginazione

// Get first 10 records, sorted by created_date descending (max 5,000 per request)
const tasks = await base44.entities.Task.list(
  "-created_date",  // sort (SortField: prefix with - for descending)
  10,               // limit
  0                 // skip
);

// Get next page
const page2 = await base44.entities.Task.list("-created_date", 10, 10);

Filtro

// Simple filter
const pending = await base44.entities.Task.filter({ status: "pending" });

// Multiple conditions
const myPending = await base44.entities.Task.filter({
  status: "pending",
  assignedTo: userId
});

// With sort, limit, skip (max 5,000 per request)
const recent = await base44.entities.Task.filter(
  { status: "pending" },
  "-created_date",  // sort (SortField: prefix with - for descending)
  5,
  0
);

// Select specific fields
const titles = await base44.entities.Task.filter(
  { status: "pending" },
  null,
  null,
  null,
  ["id", "title"]
);

Ottieni per ID

const task = await base44.entities.Task.get("task-id-123");

Aggiornamento

// Partial update - only specified fields change
await base44.entities.Task.update("task-id-123", {
  status: "completed",
  completedAt: new Date().toISOString()
});

Eliminazione

// Single record
const result = await base44.entities.Task.delete("task-id-123");
console.log("Deleted:", result.success);

// Multiple records matching query
const manyResult = await base44.entities.Task.deleteMany({ status: "archived" });
console.log("Deleted:", manyResult.deleted);

Aggiornamento multiplo (stile MongoDB)

// Update all pending tasks to status "in-progress"
const result = await base44.entities.Task.updateMany(
  { status: "pending" },                     // query: which records to update
  { $set: { status: "in-progress" } }        // MongoDB update operator
);
console.log("Updated:", result.updated);

// Increment a counter field
await base44.entities.Task.updateMany(
  { category: "bugs" },
  { $inc: { priority: 1 } }
);

Aggiornamento in blocco (per ID)

// Update multiple records, each with different data
const updated = await base44.entities.Task.bulkUpdate([
  { id: "task-1", status: "done", completedAt: new Date().toISOString() },
  { id: "task-2", status: "in-progress", assignedTo: userId },
  { id: "task-3", priority: 5 }
]);

Importazione da file

// Frontend only: import from CSV/file
const result = await base44.entities.Task.importEntities(file);
if (result.status === "success" && result.output) {
  console.log(`Imported ${result.output.length} records`);
} else {
  console.error(result.details);
}

Sottoscrivere aggiornamenti in tempo reale

// Subscribe to all changes on Task entity
const unsubscribe = base44.entities.Task.subscribe((event) => {
  console.log(`Task ${event.id} was ${event.type}:`, event.data);
  // event.type is "create", "update", or "delete"
});

// Later: unsubscribe to stop receiving updates
unsubscribe();
Struttura dell’evento:
{
  type: "create" | "update" | "delete",
  data: { ... },       // the entity data
  id: "entity-id",     // the affected entity's ID
  timestamp: "2024-01-15T10:30:00Z"
}

Entità User

Ogni app ha un’entità User integrata con regole speciali:
  • Gli utenti regolari possono leggere/aggiornare solo il proprio record
  • Non è possibile creare utenti tramite entities.create() - usa invece auth.register()
  • Il ruolo di servizio ha accesso completo a tutti i record utente
// Get current user's record
const me = await base44.entities.User.get(currentUserId);

// Service role: get any user
const anyUser = await base44.asServiceRole.entities.User.get(userId);

Accesso con ruolo di servizio

Per operazioni di livello admin (bypassa i permessi utente):
// Backend only
const allTasks = await base44.asServiceRole.entities.Task.list();
const allUsers = await base44.asServiceRole.entities.User.list();

Permessi (RLS e FLS)

L’accesso ai dati è controllato dalle regole di Row Level Security (RLS) e Field Level Security (FLS) definite negli schemi delle entità.
  1. Livello di autenticazione: anonimo, autenticato o ruolo di servizio
  2. Regole RLS: controllano quali record (righe) gli utenti possono creare/leggere/aggiornare/eliminare
  3. Regole FLS: controllano quali campi gli utenti possono leggere/scrivere all’interno dei record accessibili
Le operazioni riescono o falliscono in base a queste regole - nessun risultato parziale. RLS e FLS sono configurati nei file di schema delle entità (base44/entities/*.jsonc). Consulta entities-create.md per i dettagli di configurazione. Nota: asServiceRole imposta il ruolo dell’utente su "admin" ma NON bypassa RLS. Le tue regole RLS devono includere l’accesso admin (es. { "user_condition": { "role": "admin" } }) affinché le operazioni con ruolo di servizio abbiano successo.

Definizioni di tipo

RealtimeEvent

/** Event types for realtime entity updates. */
type RealtimeEventType = "create" | "update" | "delete";

/** Payload received when a realtime event occurs. */
interface RealtimeEvent<T = any> {
  /** The type of change that occurred. */
  type: RealtimeEventType;
  /** The entity data. */
  data: T;
  /** The unique identifier of the affected entity. */
  id: string;
  /** ISO 8601 timestamp of when the event occurred. */
  timestamp: string;
}

/** Callback function invoked when a realtime event occurs. */
type RealtimeCallback<T = any> = (event: RealtimeEvent<T>) => void;

Tipi di risultato

/** Result returned when updating multiple entities. */
interface UpdateManyResult {
  /** Whether the update was successful. */
  success: boolean;
  /** Number of entities that were updated. */
  updated: number;
}

/** Result returned when deleting a single entity. */
interface DeleteResult {
  /** Whether the deletion was successful. */
  success: boolean;
}

/** Result returned when deleting multiple entities. */
interface DeleteManyResult {
  /** Whether the deletion was successful. */
  success: boolean;
  /** Number of entities that were deleted. */
  deleted: number;
}

/** Result returned when importing entities from a file. */
interface ImportResult<T = any> {
  /** Status of the import operation. */
  status: "success" | "error";
  /** Details message, e.g., "Successfully imported 3 entities with RLS enforcement". */
  details: string | null;
  /** Array of created entity objects when successful, or null on error. */
  output: T[] | null;
}

SortField e campi del server

/**
 * Sort field type for entity queries.
 * Supports ascending (no prefix or '+') and descending ('-') sorting.
 * Example: 'created_date', '+created_date', '-created_date'
 */
type SortField<T> = (keyof T & string) | `+${keyof T & string}` | `-${keyof T & string}`;

/** Fields added by the server to every entity record. */
interface ServerEntityFields {
  id: string;
  created_date: string;
  updated_date: string;
  created_by?: string | null;
  created_by_id?: string | null;
  is_sample?: boolean;
}

Registro dei tipi (per entità tipizzate)

Come ottenere entità tipizzate: la CLI di Base44 può generare interfacce di entità e un’estensione di EntityTypeRegistry dal tuo progetto. Per come eseguirla, usa la skill base44-cli.
/**
 * Registry mapping entity names to their TypeScript types.
 * Augment this interface with your entity schema (user-defined fields only).
 * Typically populated by the Base44 CLI type generator.
 */
interface EntityTypeRegistry {}

/**
 * Full record type for each entity: schema fields + server-injected fields.
 */
type EntityRecord = {
  [K in keyof EntityTypeRegistry]: EntityTypeRegistry[K] & ServerEntityFields;
};

EntityHandler

/** Entity handler providing CRUD operations for a specific entity type. */
interface EntityHandler<T = any> {
  /** Lists records with optional pagination and sorting. Max 5,000 per request. */
  list<K extends keyof T = keyof T>(
    sort?: SortField<T>,
    limit?: number,
    skip?: number,
    fields?: K[]
  ): Promise<Pick<T, K>[]>;

  /** Filters records based on a query. Max 5,000 per request. */
  filter<K extends keyof T = keyof T>(
    query: Partial<T>,
    sort?: SortField<T>,
    limit?: number,
    skip?: number,
    fields?: K[]
  ): Promise<Pick<T, K>[]>;

  /** Gets a single record by ID. */
  get(id: string): Promise<T>;

  /** Creates a new record. */
  create(data: Partial<T>): Promise<T>;

  /** Updates an existing record. */
  update(id: string, data: Partial<T>): Promise<T>;

  /** Deletes a single record by ID. */
  delete(id: string): Promise<DeleteResult>;

  /** Deletes multiple records matching a query. */
  deleteMany(query: Partial<T>): Promise<DeleteManyResult>;

  /** Creates multiple records in a single request. */
  bulkCreate(data: Partial<T>[]): Promise<T[]>;

  /**
   * Updates multiple records matching a query using MongoDB update operators.
   * @param query - Filter to select which records to update.
   * @param data - MongoDB update operator object (e.g., `{ $set: { field: value } }`).
   */
  updateMany(query: Partial<T>, data: Record<string, Record<string, any>>): Promise<UpdateManyResult>;

  /** Updates multiple records by ID, each with its own update data. */
  bulkUpdate(data: (Partial<T> & { id: string })[]): Promise<T[]>;

  /** Imports records from a file (frontend only). */
  importEntities(file: File): Promise<ImportResult<T>>;

  /** Subscribes to realtime updates. Returns unsubscribe function. */
  subscribe(callback: RealtimeCallback<T>): () => void;
}

EntitiesModule

/** Entities module: typed registry keys get typed handlers; dynamic access remains untyped. */
type EntitiesModule = TypedEntitiesModule & DynamicEntitiesModule;

type TypedEntitiesModule = {
  [K in keyof EntityTypeRegistry]: EntityHandler<EntityRecord[K]>;
};

type DynamicEntitiesModule = {
  [entityName: string]: EntityHandler<any>;
};
Questa pagina è stata tradotta utilizzando l’IA. Per informazioni più accurate e aggiornate, consulta la versione inglese.