Express + MongoDB + Swagger Crud نمونه

در این وبلاگ ، ما با ایجاد یک برنامه ساده Crud (ایجاد ، خواندن ، به روزرسانی ، حذف) با استفاده از Express.js ، MongoDB و Swagger برای مستندات API قدم می زنیم. این راهنما به شما کمک می کند تا اصول تنظیم یک API آرامش بخش را با این فناوری ها درک کنید.
پیش نیازهای
قبل از شروع ، مطمئن شوید که موارد زیر را نصب کرده اید:
- Node.js و NPM (مدیر بسته گره)
- MongoDB (شما می توانید از یک نمونه محلی یا یک سرویس ابری مانند اطلس MongoDB استفاده کنید)
تنظیم پروژه
-
پروژه را اولیه کنید:
یک دایرکتوری جدید برای پروژه خود ایجاد کنید و آن را با NPM آغاز کنید.
mkdir express-sample-crud
cd express-sample-crud
npm init -y
-
وابستگی ها را نصب کنید:
بسته های لازم را برای پروژه خود نصب کنید.
npm install express mongoose body-parser cors dotenv swagger-jsdoc swagger-ui-express
ساختار پروژه
در اینجا مختصراً از ساختار پروژه آورده شده است:
express-sample-crud/
│
├── config/
│ ├── db.js
│ └── swagger.js
│
├── controllers/
│ └── userController.js
│
├── models/
│ └── userModel.js
│
├── routes/
│ └── userRoutes.js
│
├── my-express-app/
│ ├── .env
│ └── app.js
│
└── package.json
راهنمای گام به گام
1. پیکربندی پایگاه داده
ایجاد a db.js
پرونده در config
دایرکتوری برای تنظیم اتصال MongoDB.
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB connected");
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;
2. پیکربندی swagger
ایجاد a swagger.js
پرونده در config
دایرکتوری برای تنظیم Swagger برای مستندات API.
const swaggerJsdoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const options = {
definition: {
openapi: "3.0.0",
info: {
title: "My Express API",
version: "1.0.0",
description: "A simple Express API with CRUD operations",
},
servers: [
{
url: "http://localhost:5000",
},
],
},
apis: ["./routes/*.js"],
};
const specs = swaggerJsdoc(options);
module.exports = (app) => {
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(specs));
};
3. مدل کاربر
ایجاد a userModel.js
پرونده در models
دایرکتوری برای تعریف طرحواره کاربر.
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
});
module.exports = mongoose.model("User", UserSchema);
4. کنترل کننده کاربر
ایجاد a userController.js
پرونده در controllers
دایرکتوری برای رسیدگی به عملیات CRUD.
const User = require("../models/userModel");
exports.getUsers = async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
exports.createUser = async (req, res) => {
const { name, email, password } = req.body;
try {
const newUser = new User({ name, email, password });
await newUser.save();
res.status(201).json(newUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
};
exports.updateUser = async (req, res) => {
const { id } = req.params;
const { name, email, password } = req.body;
try {
const user = await User.findByIdAndUpdate(
id,
{ name, email, password },
{ new: true }
);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
res.json(user);
} catch (err) {
res.status(400).json({ message: err.message });
}
};
exports.deleteUser = async (req, res) => {
const { id } = req.params;
try {
const user = await User.findByIdAndDelete(id);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
res.json({ message: "User deleted successfully" });
} catch (err) {
res.status(500).json({ message: err.message });
}
};
5. مسیرهای کاربر
ایجاد a userRoutes.js
پرونده در routes
دایرکتوری برای تعریف نقاط پایانی API.
const express = require("express");
const {
getUsers,
createUser,
updateUser,
deleteUser,
} = require("../controllers/userController");
const router = express.Router();
/**
* @swagger
* components:
* schemas:
* User:
* type: object
* required:
* - name
* - email
* - password
* properties:
* name:
* type: string
* description: The user's name
* email:
* type: string
* description: The user's email
* password:
* type: string
* description: The user's password
* example:
* name: John Doe
* email: john.doe@example.com
* password: password123
*/
/**
* @swagger
* /api/users:
* get:
* summary: Get all users
* responses:
* 200:
* description: A list of users
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/User'
*/
router.get("/users", getUsers);
/**
* @swagger
* /api/users:
* post:
* summary: Create a new user
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* responses:
* 201:
* description: The created user
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* 400:
* description: Invalid input
*/
router.post("/users", createUser);
/**
* @swagger
* /api/users/{id}:
* put:
* summary: Update a user
* parameters:
* - in: path
* name: id
* schema:
* type: string
* required: true
* description: The user ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* responses:
* 200:
* description: The updated user
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* 404:
* description: User not found
*/
router.put("/users/:id", updateUser);
/**
* @swagger
* /api/users/{id}:
* delete:
* summary: Delete a user
* parameters:
* - in: path
* name: id
* schema:
* type: string
* required: true
* description: The user ID
* responses:
* 200:
* description: User deleted successfully
* 404:
* description: User not found
*/
router.delete("/users/:id", deleteUser);
module.exports = router;
6 متغیرهای محیط
ایجاد a .env
پرونده در my-express-app
دایرکتوری برای ذخیره متغیرهای محیط.
MONGO_URI=mongodb://localhost:27017/express_crud
PORT=5000
7. پرونده برنامه اصلی
ایجاد app.js
پرونده در my-express-app
دایرکتوری برای تنظیم برنامه Express.
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const dotenv = require("dotenv");
const connectDB = require("./config/db");
const userRoutes = require("./routes/userRoutes");
const swaggerSetup = require("./config/swagger");
dotenv.config();
const app = express();
// Connect to MongoDB
connectDB();
// Middleware
app.use(bodyParser.json());
app.use(cors());
// Routes
app.use("/api", userRoutes);
// Swagger setup
swaggerSetup(app);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
8. پیکربندی بسته
خود را به روز کنید package.json
پرونده شامل اسکریپت ها و وابستگی های لازم است.
{
"name": "express-sample-crud",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"mongoose": "^8.11.0",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.1"
}
}
اجرای برنامه
- سرور MongoDB خود را شروع کنید.
- برنامه را با استفاده از دستور زیر اجرا کنید:
node app.js
- مرورگر خود را باز کرده و به سمت آن حرکت کنید
http://localhost:5000/api-docs
برای مشاهده مستندات API Swagger.
پایان
شما با موفقیت یک برنامه CRUD را با استفاده از Express.js ، MongoDB و Swagger ایجاد کرده اید. این تنظیم پایه و اساس کاملی برای ساختن برنامه های پیچیده تر فراهم می کند.
فراموش نکنید که برای پروژه ها و به روزرسانی های بیشتر من را در GitHub دنبال کنید: نمایه GitHub من
می توانید کد منبع این پروژه را در GitHub پیدا کنید: Express + MongoDB + Swagger Crud Sample