> ## Documentation Index
> Fetch the complete documentation index at: https://docs.base44.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Internal links on these pages omit the .md extension. Append .md to a docs page URL, or send an Accept: text/markdown header, to get that page as markdown.

# Actors: תהליכים לדוגמה

> תהליכים לדוגמה עבור handlers של מחזור חיים, טיימרים, חיבורים, אחסון, entities ופונקציות בקאנד

<div className="dev-docs-banner">
  <div className="dev-docs-banner-content">
    <div className="dev-docs-banner-title">
      אתה צופה בתיעוד למפתחים
    </div>

    <div className="dev-docs-banner-text">
      תיעוד זה מיועד למפתחים העובדים עם פלטפורמת המפתחים של Base44.
    </div>
  </div>
</div>

השתמש בתהליכים לדוגמה האלה כנקודת התחלה למימוש שלך.

## חיבור לקוח ל-session

כשה-frontend צריך להצטרף ל-session חי, לקבל הודעות מה-actor ולשלוח הודעות ל-actor, חבר לקוח ל-session של actor.

**לחיבור לקוח ל-session:**

1. קרא ל-[`base44.actors.ActorName(sessionId)`](/he/developers/references/sdk/docs/type-aliases/actors) כדי לבחור את ה-session.
2. קרא ל-[`.connect()`](/he/developers/references/sdk/docs/type-aliases/actors#connect) כדי לפתוח את חיבור ה-WebSocket.
3. קרא ל-[`conn.subscribe()`](/he/developers/references/sdk/docs/type-aliases/actors#subscribe) כדי לרשום מאזין להודעות מה-actor.
4. קרא ל-[`conn.send()`](/he/developers/references/sdk/docs/type-aliases/actors#send) כדי לשלוח הודעה ל-actor.

הדוגמה הבאה מתחברת ל-session של actor בשם `chatRoom`, מאזינה להודעות ושולחת הודעה:

```typescript theme={null}
const conn = base44.actors.chatRoom("lobby-1").connect();

conn.subscribe((msg) => {
  if (msg.type === "message") console.log(msg.text);
});

conn.send({ type: "message", text: "Hello" });
```

למידע נוסף על חיבורים, ראה [חיבורים](/he/developers/backend/resources/actors/reference#connections).

## הרצת ticks

כשעבודה צריכה לחזור במרווח קבוע בזמן שלקוחות נמצאים ב-session, הרץ ticks. דוגמאות: שידור מצב המשחק או עדכון טיימר של סבב.

**להרצת ticks:**

1. הגדר את [`tickIntervalMs`](/he/developers/backend/resources/actors/reference#timer-handlers-and-settings) לאורך המרווח באלפיות שנייה.
2. ממש את [`shouldTick()`](/he/developers/backend/resources/actors/reference#timer-handlers-and-settings) כך שיחזיר `true` כדי להמשיך ו-`false` כדי לעצור.
3. ב-[`handleTick()`](/he/developers/backend/resources/actors/reference#timer-handlers-and-settings), הרץ את העבודה של כל מרווח.

הדוגמה הבאה מריצה tick בכל שנייה כל עוד יש לפחות שני לקוחות ב-session, ומשדרת ספירה לאחור בכל tick:

```typescript theme={null}
export default class Game extends Actor<Incoming, Outgoing> {
  tickIntervalMs = 1000;
  countdown = 60;

  shouldTick() {
    return this.getConnections().length >= 2;
  }

  async handleTick() {
    this.countdown--;
    this.broadcast({ type: "tick", countdown: this.countdown });
  }
}
```

למידע נוסף על ticks, ראה [handlers והגדרות של טיימרים](/he/developers/backend/resources/actors/reference#timer-handlers-and-settings).

## תזמון השכמות

כשעבודה צריכה לרוץ פעם אחת בזמן מסוים, בין אם ה-session פעיל ובין אם לא, תזמן השכמה. דוגמאות: סיום תור אחרי 30 שניות או סגירת לובי ריק.

**לתזמון השכמה:**

1. קרא ל-[`schedule()`](/he/developers/backend/resources/actors/reference#timer-handlers-and-settings) עם מפתח וזמן כדי להגדיר את ההשכמה.
2. ב-[`handleWake()`](/he/developers/backend/resources/actors/reference#timer-handlers-and-settings), בדוק את המפתח והרץ את העבודה של ההשכמה.
3. כשההשכמה כבר לא רלוונטית, קרא ל-[`cancelSchedule()`](/he/developers/backend/resources/actors/reference#timer-handlers-and-settings) עם המפתח.

הדוגמה הבאה מתזמנת פסק זמן לתור כשתור מתחיל, ומשדרת הודעה כשפסק הזמן מופעל:

```typescript theme={null}
export default class Game extends Actor<Incoming, Outgoing> {
  async handleMessage(_conn, msg) {
    if (msg.type === "start-turn") {
      await this.schedule("turn-timeout", Date.now() + 30_000);
    }
    if (msg.type === "end-turn") {
      await this.cancelSchedule("turn-timeout");
    }
  }

  async handleWake(key: string) {
    if (key === "turn-timeout") {
      this.broadcast({ type: "timeout" });
    }
  }
}
```

למידע נוסף על השכמות, ראה [handlers והגדרות של טיימרים](/he/developers/backend/resources/actors/reference#timer-handlers-and-settings).

## ניהול חיבורי לקוחות

כשצריך להחליט מי יכול להצטרף ל-session, להשיב ללקוח מסוים ולהגיע לכל הלקוחות ב-session, נהל את חיבורי הלקוחות.

**לניהול חיבורי לקוחות:**

1. ב-[`handleConnect()`](/he/developers/backend/resources/actors/reference#lifecycle-handlers), בדוק את [`conn.identity`](/he/developers/backend/resources/actors/reference#connections) וקרא ל-[`conn.reject()`](/he/developers/backend/resources/actors/reference#connections) כדי לדחות לקוח.
2. קרא ל-[`conn.send()`](/he/developers/backend/resources/actors/reference#connections) כדי להשיב רק ללקוח הזה.
3. ב-[`handleMessage()`](/he/developers/backend/resources/actors/reference#lifecycle-handlers), קרא ל-[`broadcast()`](/he/developers/backend/resources/actors/reference#connections) כדי להגיע לכל לקוח מחובר. כדי לזהות את השולח, כלול בהודעה שדות מ-`conn`.

הדוגמה הבאה דוחה לקוחות אנונימיים, שולחת היסטוריה ללקוח שמתחבר ומשדרת הודעות עם מזהה המשתמש של השולח:

```typescript theme={null}
async handleConnect(conn) {
  if (conn.identity.type === "anonymous") {
    conn.reject(401, "Login required");
    return;
  }
  conn.send({ type: "history", messages: this.messages });
}

async handleMessage(conn, msg) {
  this.broadcast({ type: "message", from: conn.identity.userId, text: msg.text });
}
```

למידע נוסף על חיבורים, ראה [חיבורים](/he/developers/backend/resources/actors/reference#connections).

## שמירת נתוני session

כשערכים צריכים לשרוד תקופת חוסר פעילות, שמור את נתוני ה-session. דוגמאות: לוח, רשימת היסטוריה או התור הנוכחי.

**לשמירת נתוני session:**

1. ב-[`handleStart()`](/he/developers/backend/resources/actors/reference#lifecycle-handlers), טען ערכים מ-[`this.storage`](/he/developers/backend/resources/actors/reference#storage) לשדות המחלקה.
2. אחרי כל שינוי, קרא ל-[`this.storage.put()`](/he/developers/backend/resources/actors/reference#storage) כדי לשמור את הערך המעודכן.
3. לאיפוס ה-session, קרא ל-[`this.storage.delete()`](/he/developers/backend/resources/actors/reference#storage) או ל-[`this.storage.deleteAll()`](/he/developers/backend/resources/actors/reference#storage).

הדוגמה הבאה טוענת לוח בהפעלה, שומרת אותו אחרי כל מהלך ומנקה את האחסון כשהלקוח האחרון מתנתק:

```typescript theme={null}
async handleStart() {
  this.board = (await this.storage.get<Board>("board")) ?? newBoard();
}

async handleMessage(_conn, msg) {
  applyMove(this.board, msg.move);
  await this.storage.put("board", this.board);
}

async handleClose(_conn) {
  if (this.getConnections().length === 0) {
    await this.storage.deleteAll();
  }
}
```

למידע נוסף על אחסון, ראה [אחסון](/he/developers/backend/resources/actors/reference#storage).

## כתיבת נתוני entity מתוך session

כשה-session צריך ליצור או לעדכן רשומות באפליקציה, כתוב נתוני entity. דוגמאות: ניקוד סופי או הזמנה שהושלמה.

**לכתיבת נתוני entity מתוך session:**

1. אמת את ההודעה הנכנסת לפני הכתיבה.
2. קרא את מזהה המשתמש מ-[`conn.identity.userId`](/he/developers/backend/resources/actors/reference#connections).
3. השתמש ב-[`this.client.asServiceRole`](/he/developers/backend/resources/actors/reference#entity-access) לגישה מורחבת. כתוב עם מפתח יציב, כמו מזהה ה-session, כדי ש-handler שרץ שוב יעדכן את אותה רשומה.

הדוגמה הבאה שומרת ניקוד סופי עבור הלקוח המאומת. שמירה מאוחרת יותר עבור אותו session מעדכנת את הרשומה הזו:

```typescript theme={null}
async handleMessage(conn, msg) {
  if (msg.type !== "save-score" || conn.identity.type !== "authenticated") return;
  if (typeof msg.score !== "number") return;

  const fields = {
    sessionId: this.instanceId,
    userId: conn.identity.userId,
    score: msg.score,
  };
  const [existing] = await this.client.asServiceRole.entities.Score.filter({
    sessionId: this.instanceId,
  });

  if (existing) {
    await this.client.asServiceRole.entities.Score.update(existing.id, fields);
  } else {
    await this.client.asServiceRole.entities.Score.create(fields);
  }
}
```

למידע נוסף על גישה ל-entities, ראה [גישה ל-entities](/he/developers/backend/resources/actors/reference#entity-access).

## קריאה לפונקציית בקאנד לעבודה עם secrets

Actors יכולים לקרוא secrets של האפליקציה עם [`secrets.get()`](/he/developers/backend/resources/actors/reference#read-secrets). כש-handler צריך לבצע עבודה שמשתמשת ב-secret, כמו קריאה ל-API חיצוני עם מפתח API, מומלץ לקרוא ל-[פונקציית בקאנד](/he/developers/backend/resources/backend-functions/overview). הפונקציה קוראת את ה-secret ומחזירה את התוצאה, ולעולם לא את ה-secret.

**לקריאה לפונקציית בקאנד מתוך actor:**

1. צור פונקציית בקאנד שקוראת את ה-secret עם `secrets.get()`, מבצעת את העבודה ומחזירה את התוצאה.
2. ב-handler, קרא ל-[`this.client.functions.invoke()`](/he/developers/references/sdk/docs/interfaces/functions#invoke) עם שם הפונקציה והנתונים לשליחה.
3. השתמש בתוצאה ב-session, למשל שדר אותה ללקוחות המחוברים.

הדוגמה הבאה מציגה פונקציית בקאנד שקוראת מפתח API ומחזירה תרגום:

```typescript theme={null}
// base44/functions/translateText/entry.ts
import { secrets } from "base44:runtime";

export default async function (req: Request): Promise<Response> {
  const { text } = await req.json();
  const apiKey = secrets.get("TRANSLATE_API_KEY");

  const res = await fetch("https://api.example.com/translate", {
    method: "POST",
    headers: { Authorization: `Bearer ${apiKey}` },
    body: JSON.stringify({ text }),
  });
  const { translation } = await res.json();

  return Response.json({ translation });
}
```

הדוגמה הבאה קוראת לפונקציה הזו מתוך actor ומשדרת את התוצאה:

```typescript theme={null}
export default class ChatRoom extends Actor<Incoming, Outgoing> {
  async handleMessage(_conn, msg) {
    const result = await this.client.functions.invoke("translateText", { text: msg.text });
    this.broadcast({ type: "message", text: result.data.translation });
  }
}
```

## ראה גם

* [סקירת Actors](/he/developers/backend/resources/actors/overview): מושגים ומונחים
* [יצירת Actor](/he/developers/backend/resources/actors/create-actor): קובצי actor ומחלקה מינימלית
* [קבצים וקוד של Actors](/he/developers/backend/resources/actors/reference): ה-API המלא של מחלקת הבקאנד
* [`actors deploy`](/he/developers/references/cli/commands/actors-deploy): פריסת actors מקומיים

<Note>דף זה תורגם באמצעות AI. למידע המדויק והעדכני ביותר, עיין ב[גרסה האנגלית](/). </Note>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.