المشروع: منشورات بصور، بنفس الـ FormData اللي React بيبعتها
middleware اسمه upload فيه multer بالـ storage والحد والصور بس. Post بقى فيه image، والكلام ممكن يبقى فاضي لو فيه صورة. POST و PUT بيقروا الـ FormData، والرد فيه رابط الصورة كامل من PUBLIC_URL، و /uploads بيرجّعها. hasImage=true بيفلتر المنشورات اللي فيها صور، والتعليقات بتقبل FormData كمان. وتحدي: الصورة تتمسح من الـ disk مع المنشور.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. نطبق multer على Social. تطبيق React بيبعت المنشور FormData فيها body و image، والصورة اختيارية. ولو فيه صورة من غير كلام، بيبعت مسافة بس، علشان Route Posts كان بيرفض الكلام الفاضي. فلازم الـ API بتاعنا يقبل الشكل ده بالزبط. upload.js في الـ middleware: UPLOADS_DIR: folder اسمه uploads في أول المشروع. multer بالـ storage، وحد اتنين ميجا، والصور بس، والخطأ ValidationError علشان errorHandler يرد بيه. و imageUrl: بتحوّل اسم الملف لرابط كامل، من PUBLIC_URL اللي في dot env، علشان React يحطه في img على طول. و uploads في dot gitignore، و multer في package.json. Post: body بقى مش required، والافتراضي نص فاضي، و image: اسم الملف. postBody: الكلام ممكن يبقى فاضي، والمسافة اللي React بيبعتها بتبقى فاضية بعد trim. و feedQuery بقى فيه hasImage، زي tab صور بس في React.
posts.js: present بقت بترجّع image كرابط. listFeed: لو hasImage بـ true، الـ filter: image موجودة، بـ dollar exists. createPost و updatePost: لو مفيش كلام ومفيش صورة، four hundred: اكتب حاجة أو ارفع صورة. والتوصيل: POST و PUT: upload dot single image قبل validate، فـ multer يقرا الـ form الأول، و req dot body يبقى جاهز. التعليقات كمان، لأن React بيبعتها FormData. app.js: express dot static على slash uploads. و errorHandler بيرد على أخطاء multer بالعربي. نجرب بسارة: منشور بصورة ومسافة بس، زي React بالزبط. و form من غير كلام ولا صورة. وتعليق بـ FormData. والـ feed بالصور بس.
import multer from "multer";
import { AppError } from "../errors.js";
const BODY_ERRORS = {
"entity.parse.failed": "الـ body مش JSON صحيح",
"entity.too.large": "الـ body أكبر من المسموح",
};
export function notFound(req, res) {
res.status(404).json({ success: false, message: "الـ route ده مش موجود" });
}
export function errorHandler(err, req, res, next) {
if (err instanceof AppError) {
return res.status(err.status).json({ success: false, message: err.message, errors: err.details });
}
if (err instanceof multer.MulterError) {
const message = err.code === "LIMIT_FILE_SIZE" ? "الصورة أكبر من 2 MB" : "مشكلة في رفع الملف";
return res.status(400).json({ success: false, message });
}
if (BODY_ERRORS[err.type]) {
return res.status(err.status).json({ success: false, message: BODY_ERRORS[err.type] });
}
console.error(err);
res.status(500).json({ success: false, message: "حصلت مشكلة في الـ server" });
}المخرجات
$ node --env-file=.env server.js
اتصلنا بـ MongoDB
Social API شغال على http://localhost:3000
→ POST /users/signin
{"login":"sara","password":"Social@123"}
POST /users/signin 200 - 92 ms
← 200 OK
{
"success": true,
…
→ POST /posts (Authorization: Bearer token)
(form: body, image=alex.jpg)
POST /posts 201 - 31 ms
← 201 Created
{
"success": true,
"message": "اتنشر",
"data": {
"post": {
"_id": "6ac6a88e2dc31d6887bef9a9",
"body": "",
"image": "http://localhost:3000/uploads/c0f7d6d4-6eda-4469-af58-7f597e0e4ff8.jpg",
…
→ POST /posts (Authorization: Bearer token)
(form: body)
POST /posts 400 - 3 ms
← 400 Bad Request
{
"success": false,
"message": "اكتب حاجة أو ارفع صورة"
}
→ POST /posts/6ac6a88e2dc31d6887bef9a9/comments (Authorization: Bearer token)
(form: content)
POST /posts/6ac6a88e2dc31d6887bef9a9/comments 201 - 12 ms
← 201 Created
{
"success": true,
"message": "اتضاف التعليق",
"data": {
"comment": {
"_id": "6ac6a88f2dc31d6887bef9aa",
…
→ GET /posts?hasImage=true (Authorization: Bearer token)
GET /posts?hasImage=true 200 - 10 ms
← 200 OK
{
"success": true,
"message": "success",
"data": {
"posts": [
…المنشور اتعمل، والـ body فاضي، و image رابط كامل لـ uploads. من غير كلام ولا صورة: four hundred. التعليق اتقرا من الـ FormData. و hasImage رجّع منشور سارة بس. كده React يقدر ينشر صور على الـ API بتاعنا.
دورك. لما منشور فيه صورة يتمسح، الصورة بتفضل على الـ disk للأبد، وبتاخد مساحة. والمطلوب بالزبط: في deletePost، بعد deleteOne. لو المنشور كان فيه image: امسح الملف بـ fs dot rm، والـ path من UPLOADS_DIR واسم الصورة. و force بـ true، علشان لو الملف مش موجود لأي سبب، ما يحصلش خطأ. اكتب في posts.js.
في deletePost: لو post.image، امسح الملف بـ fs.rm(path.join(UPLOADS_DIR, post.image), { force: true }).
الحل. import لـ fs و path و UPLOADS_DIR، وسطر بعد المسح. سارة تنشر صورة، وتفتح المنشور، وتمسحه.
import fs from "node:fs/promises";
import path from "node:path";
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";
import { imageUrl, UPLOADS_DIR } from "./middleware/upload.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,
image: imageUrl(post.image),
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, hasImage, ...query }, me) {
const filter = only === "following" ? { user: { $in: me.following } } : {};
if (hasImage === "true") filter.image = { $exists: true };
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, image }) {
if (!body && !image) throw new ValidationError("اكتب حاجة أو ارفع صورة");
if (!(await User.exists({ _id: userId }))) throw new ValidationError("المستخدم مش موجود");
const post = await Post.create({ user: userId, body, image });
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, image }) {
const post = await findOwnPost(id, userId);
if (!body && !image && !post.image) throw new ValidationError("اكتب حاجة أو ارفع صورة");
post.body = body;
i
…المخرجات
$ node --env-file=.env server.js
اتصلنا بـ MongoDB
Social API شغال على http://localhost:3000
→ POST /users/signin
{"login":"sara","password":"Social@123"}
POST /users/signin 200 - 92 ms
← 200 OK
{
"success": true,
…
→ POST /posts (Authorization: Bearer token)
(form: body, image=alex.jpg)
POST /posts 201 - 38 ms
← 201 Created
{
"success": true,
"message": "اتنشر",
"data": {
"post": {
"_id": "6ac6a891a8c2ff6a8a6b2b31",
…
→ GET /posts/6ac6a891a8c2ff6a8a6b2b31 (Authorization: Bearer token)
GET /posts/6ac6a891a8c2ff6a8a6b2b31 200 - 8 ms
← 200 OK
{
"success": true,
"message": "success",
"data": {
"post": {
"_id": "6ac6a891a8c2ff6a8a6b2b31",
…
→ DELETE /posts/6ac6a891a8c2ff6a8a6b2b31 (Authorization: Bearer token)
DELETE /posts/6ac6a891a8c2ff6a8a6b2b31 200 - 5 ms
← 200 OK
{
"success": true,
"message": "اتمسح",
"data": {}
}المنشور اتمسح، والصورة اتمسحت معاه من folder الـ uploads. كده Social API فيه كل حاجة تطبيق React محتاجها. القسم الأخير: نجهزه للإنتاج: الأمان، والاختبارات، والنشر، ونربطه بـ React.
import multer from "multer";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { ValidationError } from "../errors.js";
export const UPLOADS_DIR = path.join(import.meta.dirname, "..", "..", "uploads");
const IMAGE_TYPES = ["image/png", "image/jpeg", "image/webp"];
export const upload = multer({
storage: multer.diskStorage({
destination: UPLOADS_DIR,
filename: (req, file, cb) => cb(null, randomUUID() + path.extname(file.originalname).toLowerCase()),
}),
limits: { fileSize: 2 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
if (IMAGE_TYPES.includes(file.mimetype)) cb(null, true);
else cb(new ValidationError("الملف لازم يبقى صورة: png أو jpg أو webp"));
},
});
export function imageUrl(name) {
return name ? `${process.env.PUBLIC_URL}/uploads/${name}` : undefined;
}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 { upload } from "../middleware/upload.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("/", upload.single("image"), validate({ body: postBody }), async (req, res) => {
const post = await createPost({ userId: req.user._id, body: req.valid.body.body, image: req.file?.filename });
res.status(201).json({ success: true, message: "اتنشر", data: { post } });
});
router.put("/:id", upload.single("image"), validate({ params: postParams, body: postBody }), async (req, res) => {
const post = await updatePost(req.valid.params.id, req.user._id, { ...req.valid.body, image: req.file?.filename });
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;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 { UPLOADS_DIR } from "./middleware/upload.js";
import { notFound, errorHandler } from "./middleware/errors.js";
export const app = express();
app.use(express.json({ limit: "10kb" }));
app.use(logger);
app.use("/uploads", express.static(UPLOADS_DIR));
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);{
"name": "social-api",
"version": "1.0.0",
"description": "الـ backend بتاع تطبيق Social",
"type": "module",
"dependencies": {
"bcryptjs": "^3.0.3",
"express": "^5.2.1",
"jsonwebtoken": "^9.0.3",
"mongoose": "^9.11.0",
"multer": "^2.4.0",
"zod": "^4.6.5"
},
"scripts": {
"start": "node --env-file=.env server.js",
"seed": "node --env-file=.env seed.js"
}
}node_modules
.env
logs
uploadsMAX_POST_LENGTH=40
MONGO_URI=mongodb://127.0.0.1:27017/social
JWT_SECRET=dev-only-secret-change-me
JWT_EXPIRES_IN=7d
PUBLIC_URL=http://localhost:3000MAX_POST_LENGTH=500
MONGO_URI=mongodb://127.0.0.1:27017/social
JWT_SECRET=
JWT_EXPIRES_IN=7d
PUBLIC_URL=http://localhost:3000import { z } from "zod";
const MAX = Number(process.env.MAX_POST_LENGTH ?? 500);
// The text can be empty when there is a picture (the app then sends " "); the service checks that one of them exists.
export const postBody = z.object({
body: z.string({ error: "المنشور لازم يبقى نص" }).trim().max(MAX, `المنشور أطول من ${MAX} حرف`).default(""),
});
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(),
hasImage: z.enum(["true", "false"]).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 بتاع التعليق مش صحيح"),
});import mongoose from "mongoose";
const postSchema = new mongoose.Schema(
{
user: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
body: { type: String, trim: true, maxlength: 500, default: "" },
image: String,
likes: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
},
{ timestamps: true },
);
postSchema.index({ createdAt: -1 });
export const Post = mongoose.model("Post", postSchema);import { Router } from "express";
import { listComments, addComment, deleteComment } from "../comments.js";
import { validate } from "../middleware/validate.js";
import { upload } from "../middleware/upload.js";
import { commentBody, commentParams, pageQuery, postParams } from "../schemas/posts.js";
// mergeParams: the :id of the post comes from the parent router (/posts/:id/comments).
const router = Router({ mergeParams: true });
router.get("/", validate({ params: postParams, query: pageQuery }), async (req, res) => {
const { comments, pagination } = await listComments(req.valid.params.id, req.valid.query);
res.json({ success: true, message: "success", data: { comments }, meta: { pagination } });
});
router.post("/", upload.single("image"), validate({ params: postParams, body: commentBody }), async (req, res) => {
const comment = await addComment(req.valid.params.id, req.user._id, req.valid.body.content);
res.status(201).json({ success: true, message: "اتضاف التعليق", data: { comment } });
});
router.delete("/:commentId", validate({ params: commentParams }), async (req, res) => {
await deleteComment(req.valid.params.id, req.valid.params.commentId, req.user._id);
res.json({ success: true, message: "اتمسح التعليق", data: {} });
});
export default router;03 / دروس الكورس (70)
- 01أهلًا بيك: هنبني إيه في الكورس ده
- 02يعني إيه Node.js؟ وأول برنامج برة المتصفح
- 03process.argv: برنامج بياخد معلومات من الأمر نفسه
- 04Environment variables: إعدادات برة الـ code
- 05تقسيم الـ code على ملفات: require و module.exports
- 06ES modules: import و export، والنظام اللي هنبني بيه المشروع
- 07الـ modules اللي جاية مع Node: path و os و crypto
- 08المشروع: بداية Social API، والبيانات اللي هنشتغل عليها
- 09قراية وكتابة الملفات: fs بالطريقة المتزامنة
- 10ليه Node بيحب الـ async: fs.readFile و callbacks
- 11fs/promises و async/await: نفس الـ async من غير callback hell
- 12ملفات JSON: نخزن objects و arrays ونرجعهم
- 13الـ folders: mkdir و readdir و stat و rm
- 14المشروع: أول database لـ Social على ملفات JSON
- 15blocking: لما الـ thread الواحد يقف، كل حاجة تقف
- 16الـ event loop: مين بيشتغل إمتى
- 17الـ promises من جُوّه: new Promise و resolve و reject
- 18Promise.all وأخواتها: كذا حاجة في نفس الوقت
- 19الأخطاء في الـ async: await المنسية، والخطأ اللي بيوقّع البرنامج
- 20المشروع: Promise.all، و race condition بيضيّع منشور، وطابور للكتابة
- 21الـ events: EventEmitter و on و emit
- 22الـ streams: ملف كبير حتة حتة
- 23pipeline: نوصّل الـ streams ببعض، ونضغط ونفلتر
- 24الـ terminal نفسه stream: process.stdout و readline
- 25المشروع: أداة command line، و events بتسجل النشاط في stream
- 26npm و package.json: بطاقة المشروع والـ scripts
- 27npm install: نستخدم package حد تاني كتبها
- 28المشروع: package.json و scripts و .gitignore و .env
- 29HTTP، وأول server بـ node:http
- 30الـ routing بإيدينا: method و path و query و params
- 31نستقبل body: الـ request نفسه stream
- 32المشروع: Social API على node:http من غير مكتبات
- 33Express: نفس الـ server في نص الـ code
- 34POST و PATCH و DELETE في Express، و express.json
- 35الـ middleware: function في نص الطريق
- 36Router: كل مجموعة routes في ملف
- 37الأخطاء في Express: throw في أي route، ورد واحد من مكان واحد
- 38المشروع: Social API على Express، بترتيب المشاريع الحقيقية
- 39ملفات ثابتة بـ express.static، و CORS علشان React يكلمنا
- 40Zod على الـ server: ما تصدقش أي حاجة جاية من برة
- 41middleware واحد للـ validation في كل الـ routes
- 42المشروع: Zod في Social API، و pagination زي Route Posts
- 43MongoDB: قاعدة بيانات بتخزن documents
- 44Mongoose: Schema و Model بيحددوا شكل البيانات
- 45القراية من MongoDB: find والشروط والترتيب والصفحات
- 46التعديل والمسح: $set و $inc و $addToSet و $pull
- 47العلاقات: ref و populate
- 48المشروع: Social API على MongoDB
- 49كلمات السر: ليه ما بنحفزهاش، و bcrypt
- 50JWT: الـ server يفتكرك إزاي
- 51المشروع: حساب جديد، بـ Zod و bcrypt و MongoDB
- 52المشروع: تسجيل الدخول، ونرجّع token
- 53المشروع: middleware بيحمي الـ routes بالـ token
- 54المشروع: الصلاحيات، منشورك بس اللي تعدّله
- 55المشروع: تغيير كلمة السر، والـ tokens القديمة تبطل
- 56المشروع: نفس شكل Route Posts، والإعجاب
- 57المشروع: التعليقات، و router جُوّه router، وعدد التعليقات
- 58المشروع: حفظ المنشورات، و bookmarked لكل مستخدم
- 59المشروع: المتابعة، وصفحة الـ profile
- 60المشروع: feed الناس اللي بتتابعهم، والاقتراحات
- 61المشروع: الإشعارات من الـ events
- 62رفع الملفات بـ multer
- 63المشروع: منشورات بصور، بنفس الـ FormData اللي React بيبعتهاانت هنا
- 64الأمان: helmet و CORS و rate limiting
- 65الإعدادات: environment variables متفحوصة من أول ثانية
- 66الاختبارات بـ node:test
- 67اختبار الـ API كله: supertest وقاعدة بيانات للاختبار
- 68المشروع: نربط تطبيق React بالـ API بتاعنا
- 69النشر: MongoDB Atlas و Render
- 70الخلاصة، وإيه الخطوة الجاية