المشروع: الإشعارات من الـ events

Notification model فيه recipient و actor و type و isRead. startNotifications بتسمع على post:liked و comment:created و user:followed وتعمل إشعار، وما بتعملش إشعار لنفسك، وأي خطأ في الـ listener بيتسجل بس. GET /notifications و /unread-count زي Route Posts. وتحدي: PATCH /:id/read و /read-all.

01 / ملخص الدرس

المشروع: الإشعارات من الـ events

Notification model فيه recipient و actor و type و isRead. startNotifications بتسمع على post:liked و comment:created و user:followed وتعمل إشعار، وما بتعملش إشعار لنفسك، وأي خطأ في الـ listener بيتسجل بس. GET /notifications و /unread-count زي Route Posts. وتحدي: PATCH /:id/read و /read-all.

02 / شرح الدرس مكتوبًا

نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.

أهلًا بيك. الإشعارات: حد عمل إعجاب لمنشورك، أو علّق، أو تابعك. فاكر الـ events اللي كنا بنعملها emit من دروس فاتت؟ post colon liked، و comment colon created، و user colon followed. النهارده بنسمع عليهم. و posts.js و comments.js مش هيتغيروا ولا حرف. Notification model: recipient: اللي هيوصله الإشعار، و index علشان كل استعلام بيبدأ بيه. actor: اللي عمل الحاجة. type: واحد من تلاتة، بنفس أسماء Route Posts. entity: المنشور أو المستخدم اللي حصل عليه. و isRead. notifications.js: notify: لو الـ recipient هو الـ actor، ما نعملش حاجة، محدش بيوصله إشعار إنه عمل إعجاب لمنشور نفسه. safely: الـ listeners async، ولو حصل فيها خطأ، مفيش حد هيمسكه. فبنلفها بـ catch تسجل الخطأ بس، لأن الـ request الأصلي نجح خلاص. startNotifications: تلات listeners، واحد لكل event. listNotifications: إشعاراتي بس، بالـ actor، والأحدس الأول. و unread بـ false معناها اللي ما اتقراش، زي Route Posts بالزبط. و unreadCount للعداد اللي على الجرس.

والـ routes والـ schemas، وفي app.js: الـ router، و startNotifications مرة واحدة. نجرب: سارة تعمل إعجاب لمنشور مُنى، وتعلّق، وتتابعها. وبعدين مُنى تفتح الإشعارات والعداد.

src/app.js
import express from "express";
import postsRouter from "./routes/posts.js";
import usersRouter from "./routes/users.js";
import notificationsRouter from "./routes/notifications.js";
import { startNotifications } from "./notifications.js";
import { logger } from "./middleware/logger.js";
import { notFound, errorHandler } from "./middleware/errors.js";

export const app = express();

app.use(express.json({ limit: "10kb" }));
app.use(logger);

app.get("/", (req, res) => {
  res.json({ success: true, message: "Social API شغال" });
});
app.use("/posts", postsRouter);
app.use("/users", usersRouter);
app.use("/notifications", notificationsRouter);

startNotifications();

app.use(notFound);
app.use(errorHandler);

المخرجات

$ node --env-file=.env server.js
اتصلنا بـ MongoDB
Social API شغال على http://localhost:3000

→ POST /users/signin
  {"login":"mona","password":"Social@123"}
POST /users/signin 200 - 91 ms
← 200 OK
{
  "success": true,
  …

→ GET /posts?limit=1  (Authorization: Bearer token)
GET /posts?limit=1 200 - 16 ms
← 200 OK
{
  "success": true,
  …

→ POST /users/signin
  {"login":"sara","password":"Social@123"}
POST /users/signin 200 - 78 ms
← 200 OK
{
  "success": true,
  …

→ PUT /posts/6ac7395f5bb9f9ed835e4814/like  (Authorization: Bearer token)
PUT /posts/6ac7395f5bb9f9ed835e4814/like 200 - 18 ms
← 200 OK
{
  "success": true,
  "message": "عملت إعجاب",
  …

→ POST /posts/6ac7395f5bb9f9ed835e4814/comments  (Authorization: Bearer token)
  {"content":"مبروك يا مُنى"}
POST /posts/6ac7395f5bb9f9ed835e4814/comments 201 - 6 ms
← 201 Created
{
  "success": true,
  "message": "اتضاف التعليق",
  …

→ PUT /users/6ac7395f5bb9f9ed835e4811/follow  (Authorization: Bearer token)
PUT /users/6ac7395f5bb9f9ed835e4811/follow 200 - 7 ms
← 200 OK
{
  "success": true,
  "message": "بقيت متابع",
  …

→ POST /users/signin
  {"login":"mona","password":"Social@123"}
POST /users/signin 200 - 69 ms
← 200 OK
{
  "su
…

العداد تلاتة. والإشعارات من الأحدس: سارة تابعتك، وقبلها علّقت، وكل واحد فيه الـ actor بالاسم. تلات events، وتلات إشعارات، ومن غير ما نلمس الـ code بتاع الإعجاب ولا التعليقات. دي فايدة الـ events اللي اتعلمناها من بدري.

دورك. الجرس في React بيعلّم إن الإشعار اتقرا لما تدوس عليه، وفيه زرار يعلّم الكل إنه اتقرا. والمطلوب بالزبط: markRead: updateOne بشرطين: الـ id، و recipient هو أنا، علشان محدش يعلّم إشعارات غيره. ولو matchedCount صفر: four oh four. markAllRead: updateMany لكل إشعاراتي اللي ما اتقراتش. والـ routes: PATCH slash read-all، و PATCH slash colon id slash read. و read-all قبل colon id. اكتب في الملفين.

تمرين

markRead بـ updateOne بشرط recipient، و markAllRead بـ updateMany، و PATCH /read-all و /:id/read.

الحل. الشرط على recipient بيحمي من غير ما نقرا الإشعار الأول. نفس الإشعارات، ومُنى تعلّم واحد، وبعدين الكل.

src/routes/notifications.js
import { Router } from "express";
import { requireAuth } from "../middleware/auth.js";
import { validate } from "../middleware/validate.js";
import { listNotifications, unreadCount, markRead, markAllRead } from "../notifications.js";
import { notificationsQuery, notificationParams } from "../schemas/notifications.js";

const router = Router();
router.use(requireAuth);

router.get("/", validate({ query: notificationsQuery }), async (req, res) => {
  const { notifications, pagination } = await listNotifications(req.valid.query, req.user);
  res.json({ success: true, message: "success", data: { notifications }, meta: { pagination } });
});

router.get("/unread-count", async (req, res) => {
  res.json({ success: true, message: "success", data: { unreadCount: await unreadCount(req.user) } });
});

router.patch("/read-all", async (req, res) => {
  await markAllRead(req.user);
  res.json({ success: true, message: "كله بقى مقروء", data: {} });
});

router.patch("/:id/read", validate({ params: notificationParams }), async (req, res) => {
  await markRead(req.valid.params.id, req.user);
  res.json({ success: true, message: "اتقرا", data: {} });
});

export default router;

المخرجات

$ node --env-file=.env server.js
اتصلنا بـ MongoDB
Social API شغال على http://localhost:3000

→ POST /users/signin
  {"login":"mona","password":"Social@123"}
POST /users/signin 200 - 96 ms
← 200 OK
{
  "success": true,
  …

→ GET /posts?limit=1  (Authorization: Bearer token)
GET /posts?limit=1 200 - 23 ms
← 200 OK
{
  "success": true,
  …

→ POST /users/signin
  {"login":"sara","password":"Social@123"}
POST /users/signin 200 - 70 ms
← 200 OK
{
  "success": true,
  …

→ PUT /posts/6ac7395f5bb9f9ed835e4814/like  (Authorization: Bearer token)
PUT /posts/6ac7395f5bb9f9ed835e4814/like 200 - 12 ms
← 200 OK
{
  "success": true,
  "message": "شلت الإعجاب",
  …

→ POST /posts/6ac7395f5bb9f9ed835e4814/comments  (Authorization: Bearer token)
  {"content":"مبروك يا مُنى"}
POST /posts/6ac7395f5bb9f9ed835e4814/comments 201 - 15 ms
← 201 Created
{
  "success": true,
  "message": "اتضاف التعليق",
  …

→ PUT /users/6ac7395f5bb9f9ed835e4811/follow  (Authorization: Bearer token)
PUT /users/6ac7395f5bb9f9ed835e4811/follow 200 - 5 ms
← 200 OK
{
  "success": true,
  "message": "لغيت المتابعة",
  …

→ POST /users/signin
  {"login":"mona","password":"Social@123"}
POST /users/signin 200 - 71 ms
← 200 OK
{

…

الإشعارات بقت أربعة: التعليق الجديد بس عمل إشعار، لأن الإعجاب التاني شال الإعجاب، والمتابعة التانية لغت المتابعة. بعد تعليم واحد: العداد بقى تلاتة. وبعد الكل: صفر. كده features تطبيق Social كلها جاهزة. القسم الجاي: رفع الصور.

src/models/Notification.js
import mongoose from "mongoose";

const notificationSchema = new mongoose.Schema(
  {
    recipient: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true, index: true },
    actor: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
    type: { type: String, enum: ["like_post", "comment_post", "follow_user"], required: true },
    entity: { type: mongoose.Schema.Types.ObjectId },
    isRead: { type: Boolean, default: false },
  },
  { timestamps: true },
);

export const Notification = mongoose.model("Notification", notificationSchema);
src/notifications.js
import { Notification } from "./models/Notification.js";
import { Post } from "./models/Post.js";
import { NotFoundError } from "./errors.js";
import { bus } from "./events.js";

async function notify(recipient, actor, type, entity) {
  if (recipient.equals(actor)) return; // nobody is notified about themselves
  await Notification.create({ recipient, actor, type, entity });
}

// A listener's error must not crash the server: it is logged, and the request that caused it already succeeded.
const safely = (fn) => (data) => fn(data).catch((err) => console.error("الإشعار ما اتعملش:", err.message));

export function startNotifications() {
  bus.on("post:liked", safely(async ({ postId, userId }) => {
    const post = await Post.findById(postId).select("user");
    if (post) await notify(post.user, userId, "like_post", post._id);
  }));
  bus.on("comment:created", safely(({ postId, postOwner, userId }) => notify(postOwner, userId, "comment_post", postId)));
  bus.on("user:followed", safely(({ userId, followerId }) => notify(userId, followerId, "follow_user", followerId)));
}

export async function listNotifications({ page, limit, unread }, me) {
  const filter = { recipient: me._id };
  if (unread === "false") filter.isRead = false;
  const [notifications, total] = await Promise.all([
    Notification.find(filter)
      .populate("actor", "name username")
      .sort({ createdAt: -1 })
      .skip((page - 1) * limit)
      .limit(limit)
      .lean(),
    Notification.countDocuments(filter),
  ]);
  const numberOfPages = Math.max(1, Math.ceil(total / limit));
  return { notifications, pagination: { currentPage: page, numberOfPages, limit, total } };
}

export function unreadCount(me) {
  return Notification.countDocuments({ recipient: me._id, isRead: false });
}

export async function markRead(id, me) {
  const result = await Notification.updateOne({ _id: id, recipient: me._id }, { isRead: true });
  if (result.matchedCount === 0) throw new NotFoundError("الإشعار");
}

export async function markAllRead(me) {
  await Notification.updateMany({ recipient: me._id, isRead: false }, { isRead: true });
}
src/schemas/notifications.js
import { z } from "zod";
import { pageQuery } from "./posts.js";

export const notificationsQuery = pageQuery.extend({
  unread: z.enum(["true", "false"]).optional(),
});

export const notificationParams = z.object({
  id: z.string().regex(/^[a-f\d]{24}$/i, "الـ id بتاع الإشعار مش صحيح"),
});
03 / دروس الكورس (70)
  1. 01أهلًا بيك: هنبني إيه في الكورس ده
  2. 02يعني إيه Node.js؟ وأول برنامج برة المتصفح
  3. 03process.argv: برنامج بياخد معلومات من الأمر نفسه
  4. 04Environment variables: إعدادات برة الـ code
  5. 05تقسيم الـ code على ملفات: require و module.exports
  6. 06ES modules: import و export، والنظام اللي هنبني بيه المشروع
  7. 07الـ modules اللي جاية مع Node: path و os و crypto
  8. 08المشروع: بداية Social API، والبيانات اللي هنشتغل عليها
  9. 09قراية وكتابة الملفات: fs بالطريقة المتزامنة
  10. 10ليه Node بيحب الـ async: fs.readFile و callbacks
  11. 11fs/promises و async/await: نفس الـ async من غير callback hell
  12. 12ملفات JSON: نخزن objects و arrays ونرجعهم
  13. 13الـ folders: mkdir و readdir و stat و rm
  14. 14المشروع: أول database لـ Social على ملفات JSON
  15. 15blocking: لما الـ thread الواحد يقف، كل حاجة تقف
  16. 16الـ event loop: مين بيشتغل إمتى
  17. 17الـ promises من جُوّه: new Promise و resolve و reject
  18. 18Promise.all وأخواتها: كذا حاجة في نفس الوقت
  19. 19الأخطاء في الـ async: await المنسية، والخطأ اللي بيوقّع البرنامج
  20. 20المشروع: Promise.all، و race condition بيضيّع منشور، وطابور للكتابة
  21. 21الـ events: EventEmitter و on و emit
  22. 22الـ streams: ملف كبير حتة حتة
  23. 23pipeline: نوصّل الـ streams ببعض، ونضغط ونفلتر
  24. 24الـ terminal نفسه stream: process.stdout و readline
  25. 25المشروع: أداة command line، و events بتسجل النشاط في stream
  26. 26npm و package.json: بطاقة المشروع والـ scripts
  27. 27npm install: نستخدم package حد تاني كتبها
  28. 28المشروع: package.json و scripts و .gitignore و .env
  29. 29HTTP، وأول server بـ node:http
  30. 30الـ routing بإيدينا: method و path و query و params
  31. 31نستقبل body: الـ request نفسه stream
  32. 32المشروع: Social API على node:http من غير مكتبات
  33. 33Express: نفس الـ server في نص الـ code
  34. 34POST و PATCH و DELETE في Express، و express.json
  35. 35الـ middleware: function في نص الطريق
  36. 36Router: كل مجموعة routes في ملف
  37. 37الأخطاء في Express: throw في أي route، ورد واحد من مكان واحد
  38. 38المشروع: Social API على Express، بترتيب المشاريع الحقيقية
  39. 39ملفات ثابتة بـ express.static، و CORS علشان React يكلمنا
  40. 40Zod على الـ server: ما تصدقش أي حاجة جاية من برة
  41. 41middleware واحد للـ validation في كل الـ routes
  42. 42المشروع: Zod في Social API، و pagination زي Route Posts
  43. 43MongoDB: قاعدة بيانات بتخزن documents
  44. 44Mongoose: Schema و Model بيحددوا شكل البيانات
  45. 45القراية من MongoDB: find والشروط والترتيب والصفحات
  46. 46التعديل والمسح: $set و $inc و $addToSet و $pull
  47. 47العلاقات: ref و populate
  48. 48المشروع: Social API على MongoDB
  49. 49كلمات السر: ليه ما بنحفزهاش، و bcrypt
  50. 50JWT: الـ server يفتكرك إزاي
  51. 51المشروع: حساب جديد، بـ Zod و bcrypt و MongoDB
  52. 52المشروع: تسجيل الدخول، ونرجّع token
  53. 53المشروع: middleware بيحمي الـ routes بالـ token
  54. 54المشروع: الصلاحيات، منشورك بس اللي تعدّله
  55. 55المشروع: تغيير كلمة السر، والـ tokens القديمة تبطل
  56. 56المشروع: نفس شكل Route Posts، والإعجاب
  57. 57المشروع: التعليقات، و router جُوّه router، وعدد التعليقات
  58. 58المشروع: حفظ المنشورات، و bookmarked لكل مستخدم
  59. 59المشروع: المتابعة، وصفحة الـ profile
  60. 60المشروع: feed الناس اللي بتتابعهم، والاقتراحات
  61. 61المشروع: الإشعارات من الـ eventsانت هنا
  62. 62رفع الملفات بـ multer
  63. 63المشروع: منشورات بصور، بنفس الـ FormData اللي React بيبعتها
  64. 64الأمان: helmet و CORS و rate limiting
  65. 65الإعدادات: environment variables متفحوصة من أول ثانية
  66. 66الاختبارات بـ node:test
  67. 67اختبار الـ API كله: supertest وقاعدة بيانات للاختبار
  68. 68المشروع: نربط تطبيق React بالـ API بتاعنا
  69. 69النشر: MongoDB Atlas و Render
  70. 70الخلاصة، وإيه الخطوة الجاية