المشروع: feed الناس اللي بتتابعهم، والاقتراحات

?only=following بيخلي الـ feed منشورات الناس اللي بتتابعهم بس، بـ $in على following، والـ query بقى feedQuery بـ enum. /posts و /posts/feed بيستخدموا نفس الـ function زي Route Posts. وتحدي: GET /users/suggestions بـ $nin: الناس اللي مش بتتابعهم ومش إنتَ.

01 / ملخص الدرس

المشروع: feed الناس اللي بتتابعهم، والاقتراحات

?only=following بيخلي الـ feed منشورات الناس اللي بتتابعهم بس، بـ $in على following، والـ query بقى feedQuery بـ enum. /posts و /posts/feed بيستخدموا نفس الـ function زي Route Posts. وتحدي: GET /users/suggestions بـ $nin: الناس اللي مش بتتابعهم ومش إنتَ.

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

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

أهلًا بيك. الـ feed في تطبيق React فيه tab اسمه بتتابعهم: منشورات الناس اللي إنتَ متابعهم بس. و list على الجنب فيها اقتراحات: ناس ممكن تتابعهم. الاتنين محتاجين following اللي عملناه الدرس اللي فات. feedQuery: pageQuery ومعاه only، enum فيه following بس، و optional. listFeed: لو only بـ following، الـ filter: user بـ dollar in، و me dot following. يعني المنشورات اللي صاحبها واحد من اللي بتابعهم. والـ route: function اسمها feed، ومتركّبة على slash و slash feed الاتنين، زي Route Posts. نجرب بمحمود، وهو متابع مُنى وكريم: الـ feed كله، وبعدين بتتابعهم بس.

src/routes/posts.js
import { Router } from "express";
import commentsRouter from "./comments.js";
import { listFeed, getPost, createPost, updatePost, deletePost, toggleLike, toggleBookmark } from "../posts.js";
import { validate } from "../middleware/validate.js";
import { requireAuth } from "../middleware/auth.js";
import { postBody, feedQuery, postParams } from "../schemas/posts.js";

const router = Router();

router.use(requireAuth);
router.use("/:id/comments", commentsRouter);

async function feed(req, res) {
  const { posts, pagination } = await listFeed(req.valid.query, req.user);
  res.json({ success: true, message: "success", data: { posts }, meta: { pagination } });
}

router.get("/", validate({ query: feedQuery }), feed);
router.get("/feed", validate({ query: feedQuery }), feed);

router.get("/:id", validate({ params: postParams }), async (req, res) => {
  const post = await getPost(req.valid.params.id, req.user);
  res.json({ success: true, message: "success", data: { post } });
});

router.post("/", validate({ body: postBody }), async (req, res) => {
  const post = await createPost({ userId: req.user._id, body: req.valid.body.body });
  res.status(201).json({ success: true, message: "اتنشر", data: { post } });
});

router.put("/:id", validate({ params: postParams, body: postBody }), async (req, res) => {
  const post = await updatePost(req.valid.params.id, req.user._id, req.valid.body);
  res.json({ success: true, message: "اتعدل", data: { post } });
});

router.delete("/:id", validate({ params: postParams }), async (req, res) => {
  await deletePost(req.valid.params.id, req.user._id);
  res.json({ success: true, message: "اتمسح", data: {} });
});

router.put("/:id/like", validate({ params: postParams }), async (req, res) => {
  const result = await toggleLike(req.valid.params.id, req.user);
  res.json({ success: true, message: result.liked ? "عملت إعجاب" : "شلت الإعجاب", data: result });
});

router.put("/:id/bookmark", validate({ params: postParams }), async (req, res) => {
  const result = await toggleBookmark(req.valid.params.id, req.user);
  res.json({ success: true, message: result.bookmarked ? "اتحفظ" : "اتشال من المحفوظات", data: result });
});

export default router;

المخرجات

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

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

→ GET /posts  (Authorization: Bearer token)
GET /posts 200 - 35 ms
← 200 OK
{
  "success": true,
  …

→ GET /posts/feed?only=following  (Authorization: Bearer token)
GET /posts/feed?only=following 200 - 11 ms
← 200 OK
{
  "success": true,
  "message": "success",
  "data": {
    "posts": [
      {
        "_id": "6ac6a81182a703959eab601f",
        "body": "أول يوم في الشغل الجديد",
        "createdAt": "2026-10-05T18:00:00.000Z",
        "user": {
          "_id": "6ac6a81182a703959eab601c",
          "name": "مُنى أحمد",
          "username": "mona"
        },
        "likes": [
          "6ac6a81182a703959eab601b",
          "6ac6a81182a703959eab601d"
        ],
        "likesCount": 2,
        "commentsCount": 2,
        "bookmarked": false
      },
      {
        "_id": "6ac6a81182a703959eab6020",
        "body": "خلصت أول مشروع React ليا",
        "createdAt": "2026-10-05T15:30:00.000Z",
        "user": {
          "_id": "6ac6a81182a703959eab601d",
   
…

الـ feed كله رجع كل المنشورات. بتتابعهم: تلاتة بس، منشورين لمُنى وواحد لكريم، من غير منشوره هو ومنشور سارة. و only بقيمة غلط: four hundred من الـ enum.

دورك. الاقتراحات: ناس محمود مش متابعهم، ومش هو نفسه. والمطلوب بالزبط: في users.js: suggestions بتاخد page و limit و me. الـ filter: underscore id بـ dollar nin، يعني not in، وجُوّاها me dot underscore id، و me dot following بالـ spread. find و countDocuments بالصفحات. وكل مستخدم بـ publicUser، وبما إنها async: Promise dot all. والـ route: GET slash suggestions، قبل slash colon id، والرد data فيها suggestions. اكتب في الملفين.

تمرين

suggestions(query, me) بـ $nin و publicUser، و GET /users/suggestions قبل /:id.

الحل. و route الاقتراحات قبل slash colon id. ليه؟ لأن لو بعده، كلمة suggestions هتتفهم على إنها id، و validate هيرفضها. اقتراحات محمود، وبعدين اقتراحات سارة.

src/routes/users.js
import { Router } from "express";
import { signup, signin, toUser, changePassword, getProfile, toggleFollow, suggestions } from "../users.js";
import { requireAuth } from "../middleware/auth.js";
import { listBookmarks, listUserPosts } from "../posts.js";
import { pageQuery } from "../schemas/posts.js";
import { validate } from "../middleware/validate.js";
import { signupBody, signinBody, changePasswordBody, userParams } from "../schemas/users.js";

const router = Router();

router.post("/signup", validate({ body: signupBody }), async (req, res) => {
  const user = await signup(req.valid.body);
  res.status(201).json({ success: true, message: "اتعمل الحساب", data: { user } });
});

router.post("/signin", validate({ body: signinBody }), async (req, res) => {
  const { token, user } = await signin(req.valid.body);
  res.json({ success: true, message: "أهلًا بيك", data: { token, user } });
});

router.get("/profile-data", requireAuth, (req, res) => {
  res.json({ success: true, data: { user: toUser(req.user) } });
});

router.patch("/change-password", requireAuth, validate({ body: changePasswordBody }), async (req, res) => {
  const token = await changePassword(req.user._id, req.valid.body);
  res.json({ success: true, message: "كلمة السر اتغيرت", data: { token } });
});

router.get("/bookmarks", requireAuth, validate({ query: pageQuery }), async (req, res) => {
  const { posts, pagination } = await listBookmarks(req.valid.query, req.user);
  res.json({ success: true, message: "success", data: { bookmarks: posts }, meta: { pagination } });
});

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

router.get("/:id/profile", requireAuth, validate({ params: userParams }), async (req, res) => {
  const data = await getProfile(req.valid.params.id, req.user);
  res.json({ success: true, message: "success", data });
});

router.put("/:id/follow", requireAuth, validate({ params: userParams }), async (req, res) => {
  const data = await toggleFollow(req.valid.params.id, req.user);
  res.json({ success: true, message: data.following ? "بقيت متابع" : "لغيت المتابعة", data });
});

router.get("/:id/posts", requireAuth, validate({ params: userParams, query: pageQuery }), async (req, res) => {
  const { posts, pagination } = await listUserPosts(req.valid.params.id, req.valid.query, req.user);
  res.json({ success: true, message: "success", data: { posts }, meta: { pagination } });
});

export default router;

المخرجات

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

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

→ GET /users/suggestions  (Authorization: Bearer token)
GET /users/suggestions 200 - 16 ms
← 200 OK
{
  "success": true,
  "message": "success",
  "data": {
    "suggestions": [
      {
        "_id": "6ac6a81182a703959eab601e",
        "name": "سارة علي",
        "username": "sara",
        "gender": "female",
        "followersCount": 0,
        "followingCount": 0
      }
    ]
  },
  "meta": {
    "pagination": {
      "currentPage": 1,
      "numberOfPages": 1,
      "limit": 10,
      "total": 1
    }
  }
}

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

→ GET /users/suggestions?limit=1  (Authorization: Bearer token)
GET /users/suggestions?limit=1 200 - 11 ms
← 200 OK
{
  "success": true,
  "message": "success",
  "data": {
    "suggestions": [
      {
        "_id": "6ac6a81182a703959eab601c",
        "name": "مُنى أحمد",
        "username": "mona",
        "gender": "fe
…

محمود: سارة بس، لأنه متابع الباقيين. وسارة: الـ total تلاتة، لأنها مش متابعة حد. الدرس الجاي: الإشعارات، وهنستخدم كل الـ events اللي عملناها.

src/posts.js
import { Post } from "./models/Post.js";
import { User } from "./models/User.js";
import { Comment } from "./models/Comment.js";
import { NotFoundError, ValidationError, ForbiddenError } from "./errors.js";
import { bus } from "./events.js";

const AUTHOR = "name username";

// The shape the app shows, for any list of posts: comments counted once for all of them, and bookmarked for me.
async function present(posts, me) {
  const counts = await Comment.aggregate([
    { $match: { post: { $in: posts.map((p) => p._id) } } },
    { $group: { _id: "$post", count: { $sum: 1 } } },
  ]);
  const countOf = new Map(counts.map((c) => [String(c._id), c.count]));
  const saved = new Set((me?.bookmarks ?? []).map(String));
  return posts.map((post) => ({
    _id: post._id,
    body: post.body,
    createdAt: post.createdAt,
    user: post.user,
    likes: post.likes,
    likesCount: post.likes.length,
    commentsCount: countOf.get(String(post._id)) ?? 0,
    bookmarked: saved.has(String(post._id)),
  }));
}

async function page(filter, { page = 1, limit = 10 } = {}, me) {
  const [posts, total] = await Promise.all([
    Post.find(filter)
      .populate("user", AUTHOR)
      .sort({ createdAt: -1 })
      .skip((page - 1) * limit)
      .limit(limit)
      .lean(),
    Post.countDocuments(filter),
  ]);
  const numberOfPages = Math.max(1, Math.ceil(total / limit));
  const pagination = { currentPage: page, numberOfPages, limit, total };
  if (page < numberOfPages) pagination.nextPage = page + 1;
  return { posts: await present(posts, me), pagination };
}

export function listFeed({ only, ...query }, me) {
  const filter = only === "following" ? { user: { $in: me.following } } : {};
  return page(filter, query, me);
}

export async function getPost(id, me) {
  const post = await Post.findById(id).populate("user", AUTHOR).lean();
  if (!post) throw new NotFoundError("المنشور");
  const [shown] = await present([post], me);
  return shown;
}

export async function createPost({ userId, body }) {
  if (!(await User.exists({ _id: userId }))) throw new ValidationError("المستخدم مش موجود");
  const post = await Post.create({ user: userId, body });
  bus.emit("post:created", post);
  return getPost(post._id);
}

async function findOwnPost(id, userId) {
  const post = await Post.findById(id);
  if (!post) throw new NotFoundError("المنشور");
  if (!post.user.equals(userId)) throw new ForbiddenError("ده مش منشورك");
  return post;
}

export async function updatePost(id, userId, { body }) {
  const post = await findOwnPost(id, userId);
  post.body = body;
  await post.save();
  return getPost(post._id);
}

export async function deletePost(id, userId) {
  const post = await findOwnPost(id, userId);
  await post.deleteOne();
  bus.emit("post:deleted", id);
}

export async function toggleLike(id, me) {
  const userId = me._id;
  const post = await Post.findById(id).select("likes").lean();
  if (!post) throw new NotFoundError("المنشور");

  const liked = !post.likes.some((lik
…
src/users.js
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { User } from "./models/User.js";
import { ConflictError, UnauthorizedError, ValidationError, NotFoundError } from "./errors.js";
import { bus } from "./events.js";

export function toUser(user) {
  return {
    _id: user._id,
    name: user.name,
    username: user.username,
    email: user.email,
    gender: user.gender,
    dateOfBirth: user.dateOfBirth,
  };
}

// What anyone may see about a user (no email, no password).
export async function publicUser(user) {
  return {
    _id: user._id,
    name: user.name,
    username: user.username,
    gender: user.gender,
    dateOfBirth: user.dateOfBirth,
    followersCount: await User.countDocuments({ following: user._id }),
    followingCount: user.following.length,
  };
}

async function findUser(id) {
  const user = await User.findById(id);
  if (!user) throw new NotFoundError("المستخدم");
  return user;
}

export async function getProfile(id, me) {
  const user = await findUser(id);
  return { user: await publicUser(user), isFollowing: me.following.some((f) => f.equals(user._id)) };
}

export async function toggleFollow(id, me) {
  if (me._id.equals(id)) throw new ValidationError("ما ينفعش تتابع نفسك");
  const user = await findUser(id);
  const following = !me.following.some((f) => f.equals(user._id));
  await User.updateOne({ _id: me._id }, following ? { $addToSet: { following: user._id } } : { $pull: { following: user._id } });
  if (following) bus.emit("user:followed", { userId: user._id, followerId: me._id });
  return { following, followersCount: await User.countDocuments({ following: user._id }) };
}

export async function signup({ name, username, email, password, dateOfBirth, gender }) {
  const passwordHash = await bcrypt.hash(password, 10);
  try {
    const user = await User.create({ name, username, email, password: passwordHash, dateOfBirth, gender });
    return toUser(user);
  } catch (err) {
    if (err.code === 11000) {
      const field = Object.keys(err.keyValue)[0];
      const messages = { username: "الـ username ده مستخدم", email: "الإيميل ده مستخدم" };
      throw new ConflictError(messages[field], { [field]: [messages[field]] });
    }
    throw err;
  }
}

export function signToken(user) {
  return jwt.sign({ sub: user._id, v: user.tokenVersion }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN ?? "7d",
  });
}

export async function signin({ login, password }) {
  const user = await User.findOne({ $or: [{ email: login }, { username: login }] }).select("+password");
  const ok = user && (await bcrypt.compare(password, user.password));
  if (!ok) throw new UnauthorizedError("الإيميل أو كلمة السر غلط");

  return { token: signToken(user), user: toUser(user) };
}

export async function changePassword(userId, { password, newPassword }) {
  const user = await User.findById(userId).select("+password");
  if (!(await bcrypt.compare(password, user.password))) {
    const message = "كلمة الس
…
src/schemas/posts.js
import { z } from "zod";

const MAX = Number(process.env.MAX_POST_LENGTH ?? 500);

export const postBody = z.object({
  body: z.string({ error: "المنشور لازم يبقى نص" }).trim().min(1, "المنشور فاضي").max(MAX, `المنشور أطول من ${MAX} حرف`),
});

export const pageQuery = z.object({
  page: z.coerce.number({ error: "رقم الصفحة لازم يبقى رقم" }).int().min(1).default(1),
  limit: z.coerce.number({ error: "الـ limit لازم يبقى رقم" }).int().min(1).max(50).default(10),
});

export const feedQuery = pageQuery.extend({
  only: z.enum(["following"], { error: "only بتقبل following بس" }).optional(),
});

export const postParams = z.object({
  id: z.string().regex(/^[a-f\d]{24}$/i, "الـ id مش صحيح"),
});

export const commentBody = z.object({
  content: z.string({ error: "التعليق لازم يبقى نص" }).trim().min(1, "التعليق فاضي").max(300, "التعليق أطول من 300 حرف"),
});

export const commentParams = postParams.extend({
  commentId: 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الخلاصة، وإيه الخطوة الجاية