0Pricing
Serverless AWS Lambda Development · درس

التكامل مع DynamoDB

اربط دوال Lambda بـ Amazon DynamoDB، وهي قاعدة بيانات NoSQL مُدارة بالكامل، لتخزين البيانات واستردادها بأداء عالٍ وقابلية توسع في التطبيقات عديمة الخوادم

التكامل مع DynamoDB درس مجاني في Serverless AWS Lambda Development على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Serverless AWS Lambda Development، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Serverless AWS Lambda Development 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Lambda Meets DynamoDB

Welcome! In this lesson, we'll connect the power of serverless AWS Lambda with Amazon DynamoDB, a super-fast and flexible NoSQL database.

This combination is perfect for building scalable, high-performance applications without managing servers or database infrastructure.

DynamoDB: NoSQL in a Nutshell

Amazon DynamoDB is a fully managed, serverless NoSQL database. Unlike traditional SQL databases, it uses a key-value and document data model.

  • Tables: Similar to SQL tables, but hold items.
  • Items: Like rows in SQL, but can have different attributes.
  • Attributes: Like columns, but flexible (no fixed schema).
  • Primary Key: Uniquely identifies each item. Can be a simple Partition Key or a composite Partition Key + Sort Key.

Setting Up Your DynamoDB Table

Before Lambda can interact with DynamoDB, you need a table. You can create one easily in the AWS Management Console.

When creating, you'll define a Primary Key. For example, an id attribute as a Partition Key is common for simple lookups.

Giving Lambda DynamoDB Access

For your Lambda function to talk to DynamoDB, it needs permission. This is managed via an IAM Role attached to your Lambda function.

You'll need to grant policies like dynamodb:PutItem, dynamodb:GetItem, etc., to specific tables for secure, granular access. For simplicity in learning, AmazonDynamoDBFullAccess might be used initially, but always prefer least privilege in production.

Writing Data: The PutItem Op

The PutItem operation is used to add a new item to a table or replace an existing item if an item with the same primary key already exists.

Try running this example to see how to add an item. We're using a mock AWS SDK for local execution.

// MOCK AWS SDK for local runnable example
const mockDynamoDB = {
  DocumentClient: function() {
    return {
      put: (params) => ({
        promise: () => {
          console.log("MOCK: Put item to table '" + params.TableName + "':", params.Item);
          return Promise.resolve({ success: true, item: params.Item });
        }
      })
    };
  }
};

// Simulate the Lambda handler function
async function handler(event) {
  const ddb = new mockDynamoDB.DocumentClient();

  const params = {
    TableName: "MyUsersTable", // Replace with your table name
    Item: {
      id: event.userId,
      name: event.userName,
      email: event.userEmail
    }
  };

  try {
    const data = await ddb.put(params).promise();
    console.log("Operation successful (mock):", data);
    return { statusCode: 200, body: JSON.stringify(data) };
  } catch (err) {
    console.error("Operation failed (mock):", err);
    return { statusCode: 500, body: JSON.stringify(err) };
  }
}

// Entry point for CoddyKit's runnable environment
async function main() {
  console.log("Running simulated PutItem operation...");
  const testEvent = {
    userId: "user123",
    userName: "Alice",
    userEmail: "alice@example.com"
  };
  await handler(testEvent);
}

main();

Understanding the PutItem Code

In the example, we're using DynamoDB.DocumentClient() to simplify interactions with DynamoDB, as it handles data types automatically.

  • TableName: The name of your DynamoDB table.
  • Item: A JavaScript object representing the data you want to store. Each key-value pair is an attribute.
  • promise(): Used to handle the asynchronous nature of AWS SDK calls.

Reading Data: The GetItem Op

To retrieve a single item from your table, you use the GetItem operation. You must provide the full Primary Key of the item you want to fetch.

Run this code to see how to get an item back.

// MOCK AWS SDK for local runnable example
const mockDynamoDB = {
  DocumentClient: function() {
    return {
      get: (params) => ({
        promise: () => {
          console.log("MOCK: Get item from table '" + params.TableName + "' with Key:", params.Key);
          // Simulate finding an item with id 'user123'
          if (params.Key.id === "user123") {
            return Promise.resolve({ Item: { id: "user123", name: "Alice", email: "alice@example.com" } });
          }
          return Promise.resolve({ Item: null }); // Item not found
        }
      })
    };
  }
};

// Simulate the Lambda handler function
async function handler(event) {
  const ddb = new mockDynamoDB.DocumentClient();

  const params = {
    TableName: "MyUsersTable", // Replace with your table name
    Key: {
      id: event.userId // The primary key to retrieve
    }
  };

  try {
    const data = await ddb.get(params).promise();
    console.log("Retrieved item (mock):", data.Item);
    return { statusCode: 200, body: JSON.stringify(data.Item) };
  } catch (err) {
    console.error("Operation failed (mock):", err);
    return { statusCode: 500, body: JSON.stringify(err) };
  }
}

// Entry point for CoddyKit's runnable environment
async function main() {
  console.log("Running simulated GetItem operation...");
  const testEvent = {
    userId: "user123" // ID of the item to retrieve
  };
  await handler(testEvent);
}

main();

Updating Data: The UpdateItem Op

The UpdateItem operation modifies existing attributes of an item or adds new attributes if they don't exist. It's more efficient than reading, modifying, and then putting the whole item back.

This example updates the email for an existing user.

// MOCK AWS SDK for local runnable example
const mockDynamoDB = {
  DocumentClient: function() {
    return {
      update: (params) => ({
        promise: () => {
          console.log("MOCK: Update item in table '" + params.TableName + "' with Key:", params.Key);
          console.log("MOCK: Update Expression:", params.UpdateExpression, "Values:", params.ExpressionAttributeValues);
          return Promise.resolve({ Attributes: { id: params.Key.id, email: "updated@example.com" } });
        }
      })
    };
  }
};

// Simulate the Lambda handler function
async function handler(event) {
  const ddb = new mockDynamoDB.DocumentClient();

  const params = {
    TableName: "MyUsersTable", // Replace with your table name
    Key: {
      id: event.userId // Primary key of the item to update
    },
    UpdateExpression: "set email = :e",
    ExpressionAttributeValues: {
      ":e": event.newEmail
    },
    ReturnValues: "UPDATED_NEW" // Return the new values of updated attributes
  };

  try {
    const data = await ddb.update(params).promise();
    console.log("Updated item (mock):", data.Attributes);
    return { statusCode: 200, body: JSON.stringify(data.Attributes) };
  } catch (err) {
    console.error("Operation failed (mock):", err);
    return { statusCode: 500, body: JSON.stringify(err) };
  }
}

// Entry point for CoddyKit's runnable environment
async function main() {
  console.log("Running simulated UpdateItem operation...");
  const testEvent = {
    userId: "user123",
    newEmail: "alice.new@example.com"
  };
  await handler(testEvent);
}

main();

Deleting Data: The DeleteItem Op

When you no longer need an item, you can remove it using the DeleteItem operation. Just like GetItem, you must specify the full primary key of the item to delete.

Be careful with deletions, as they are permanent!

// MOCK AWS SDK for local runnable example
const mockDynamoDB = {
  DocumentClient: function() {
    return {
      delete: (params) => ({
        promise: () => {
          console.log("MOCK: Delete item from table '" + params.TableName + "' with Key:", params.Key);
          return Promise.resolve({ success: true });
        }
      })
    };
  }
};

// Simulate the Lambda handler function
async function handler(event) {
  const ddb = new mockDynamoDB.DocumentClient();

  const params = {
    TableName: "MyUsersTable", // Replace with your table name
    Key: {
      id: event.userId // Primary key of the item to delete
    }
  };

  try {
    const data = await ddb.delete(params).promise();
    console.log("Item deleted successfully (mock).");
    return { statusCode: 200, body: JSON.stringify(data) };
  } catch (err) {
    console.error("Operation failed (mock):", err);
    return { statusCode: 500, body: JSON.stringify(err) };
  }
}

// Entry point for CoddyKit's runnable environment
async function main() {
  console.log("Running simulated DeleteItem operation...");
  const testEvent = {
    userId: "user123" // ID of the item to delete
  };
  await handler(testEvent);
}

main();

Quick Check: DynamoDB Actions

You've learned about basic DynamoDB operations. Let's test your understanding!

Recap: Lambda + DynamoDB

Great job! You've learned how to integrate AWS Lambda with Amazon DynamoDB for powerful serverless applications.

  • DynamoDB provides a scalable NoSQL database.
  • Lambda functions need IAM permissions to interact with DynamoDB tables.
  • You can perform common operations like PutItem (create/replace), GetItem (read), UpdateItem (modify), and DeleteItem (remove).

This integration is fundamental for building dynamic, event-driven serverless backends!

الأسئلة الشائعة

هل درس «التكامل مع DynamoDB» مجاني؟

نعم — نص درس «التكامل مع DynamoDB» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Serverless AWS Lambda Development، انتقل إلى CoddyKit PRO. تتضمن دورة Serverless AWS Lambda Development 4 دروس في المجموع.

ماذا ستتعلم في «التكامل مع DynamoDB»؟

اربط دوال Lambda بـ Amazon DynamoDB، وهي قاعدة بيانات NoSQL مُدارة بالكامل، لتخزين البيانات واستردادها بأداء عالٍ وقابلية توسع في التطبيقات عديمة الخوادم تتمرن على Serverless AWS Lambda Development مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Serverless AWS Lambda Development؟

لا تُشترط خبرة سابقة. Serverless AWS Lambda Development على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «التكامل مع DynamoDB»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Serverless AWS Lambda Development هذا؟

نعم. كل درس في Serverless AWS Lambda Development يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. التكامل مع DynamoDB
  2. S3 لتخزين الملفات والأحداث
  3. اختيار مخزن البيانات المناسب
  4. التخزين المؤقت باستخدام Amazon ElastiCache وDAX
← العودة إلى Serverless AWS Lambda Development