为了账号安全,请及时绑定邮箱和手机立即绑定

使用设计模式构建一个可扩展的用户管理系统,与TypeScript结合

标签:
设计模式

在这篇博客文章中,我们将带您一步步地使用TypeScript和Mongoose构建可扩展用户管理系统的方法。我们将实现并解释几个关键的设计模式:模型-视图-控制器(MVC)、仓储、服务、工厂、依赖注入(DI)和SRP原则。

设计模式简介
  1. 模型-视图-控制器(MVC)模式:将应用程序分为三个相互关联的部分。
  2. 仓库模式:抽象数据访问逻辑。
  3. 服务模式:封装业务处理逻辑。
  4. 工厂模式:负责创建对象的模式。
  5. 依赖注入(DI)模式:通过注入依赖来促进松耦合性。
  6. 单一职责原则(SRP):确保每个类只负责一项任务。
分步实施

我们将创建一个用户管理系统,其结构如下:

  1. UserModel :表示用户的数据结构。
  2. UserRepository :负责数据访问。
  3. UserService :处理业务逻辑。
  4. UserFactory :负责创建服务实例。
  5. UserController :处理HTTP请求。
第一步:定义用户画像

首先,我们来为 User 实体定义一个 Mongoose 模型。

    import mongoose, { Schema, Document, Model } from "mongoose";  

    // 定义一个扩展了Mongoose Document的User接口  
    interface IUser extends Document {  
      username: string;  
      email: string;  
      password: string;  
    }  
    // 定义User模式如下  
    const UserSchema: Schema<IUser> = new Schema({  
      username: { type: String, required: true },  
      email: { type: String, required: true },  
      password: { type: String, required: true }  
    });  
    // 创建名为User的模型  
    const UserModel: Model<IUser> = mongoose.model<IUser>("User", UserSchema);  
    export { IUser, UserModel };
第二步:创建用户仓库

接下来,我们创建一个存储库类来处理数据访问任务。

    import { Model } from "mongoose";
    import { IUser, UserModel } from "./UserModel";

    class UserRepository {
      private userModel: Model<IUser>;
      constructor() {
        this.userModel = UserModel;
      }
      async findOneByUsername(username: string): Promise<IUser | null> {
        return this.userModel.findOne({ username }).exec();
      }
      async findAll(): Promise<IUser[]> {
        return this.userModel.find().exec();
      }
      async create(user: Partial<IUser>): Promise<IUser> {
        return this.userModel.create(user);
      }
      async updateById(id: string, update: Partial<IUser>): Promise<void> {
        await this.userModel.findByIdAndUpdate(id, update).exec();
      }
      async deleteById(id: string): Promise<void> {
        await this.userModel.findByIdAndDelete(id).exec();
      }
    }
    export default UserRepository;
步骤 3:创建 UserService

服务层包含业务逻辑,并与数据仓库打交道。

    import 用户存储库 from "./UserRepository";  
    import { 用户接口 } from "./UserModel";  

    class 用户服务 {  
      private 用户存储: 用户存储库;  
      constructor(用户存储: 用户存储库) {  
        this.用户存储 = 用户存储;  
      }  
      async 注册用户(username: string, email: string, password: string): Promise<用户接口> {  
        const 用户 = { username, email, password };  
        return this.用户存储.create(用户);  
      }  
      async 通过用户名获取用户(username: string): Promise<用户接口 | null> {  
        return this.用户存储.findOneByUsername(username);  
      }  
      async 更新用户(id: string, update: Partial<用户接口>): Promise<void> {  
        await this.用户存储.updateById(id, update);  
      }  
      async 删除用户(id: string): Promise<void> {  
        await this.用户存储.deleteById(id);  
      }  
    }  
    export default 用户服务;
第4步:创建用户工厂(UserFactory)

工厂模式用来创建服务的实例。

    import UserRepository from "./UserRepository";  // 用户仓库类
    import UserService from "./UserService";  // 用户服务类

    /**

* 用户工厂类,用于创建用户服务
     */
    class UserFactory {  
      /**

* 创建用户服务

* @returns {UserService}
       */
      static createUserService(): UserService {  
        const userRepository = new UserRepository();  // 创建用户仓库实例
        return new UserService(userRepository);  // 使用用户仓库实例创建用户服务实例
      }  
    }  
    // 导出默认的用户工厂
    export default UserFactory;
步骤 5:建立 UserController

控制器处理HTTP请求,并利用服务执行相关操作。

    import { Request, Response } from "express";  
    import UserFactory from "./UserFactory";  

    class UserController {  
      private userService = UserFactory.createUserService();  
      async userRegister(req: Request, res: Response): Promise<void> {  
        const { username, email, password } = req.body;  
        try {  
          const user = await this.userService.registerUser(username, email, password);  
          res.status(201).json(user);  
        } catch (error) {  
          res.status(400).json({ message: error.message });  
        }  
      }  
      async getUserInfo(req: Request, res: Response): Promise<void> {  
        const { username } = req.params;  
        try {  
          const user = await this.userService.getUserByUsername(username);  
          if (user) {  
            res.status(200).json(user);  
          } else {  
            res.status(404).json({ message: "找不到该用户" });  
          }  
        } catch (error) {  
          res.status(400).json({ message: error.message });  
        }  
      }  
      async updateUserInformation(req: Request, res: Response): Promise<void> {  
        const { id } = req.params;  
        const update = req.body;  
        try {  
          await this.userService.updateUser(id, update);  
          res.status(200).json({ message: "用户信息已更新" });  
        } catch (error) {  
          res.status(400).json({ message: error.message });  
        }  
      }  
      async deleteUserInformation(req: Request, res: Response): Promise<void> {  
        const { id } = req.params;  
        try {  
          await this.userService.deleteUser(id);  
          res.status(200).json({ message: "用户信息已删除" });  
        } catch (error) {  
          res.status(400).json({ message: error.message });  
        }  
      }  
    }  
    export default UserController;

步骤 6:配置 Express 路由程序

最后,设置Express路由来处理HTTP请求。

    import express from "express";  
    import mongoose from "mongoose";  
    import UserController from "./UserController";  

    const app = express();  
    const userController = new UserController();  
    // 中间件  
    app.use(express.json());  
    // 路由定义  
    app.post("/users", userController.registerUser.bind(userController));  
    app.get("/users/:username", userController.getUser.bind(userController));  
    app.put("/users/:id", userController.updateUser.bind(userController));  
    app.delete("/users/:id", userController.deleteUser.bind(userController));  
    // 连接数据库并启动服务器  
    mongoose.connect("mongodb://localhost:27017/mydatabase", {  
      useNewUrlParser: true,  
      useUnifiedTopology: true  
    }).then(() => {  
      app.listen(3000, () => {  
        console.log("服务器在端口 3000 上运行");  
      });  
    }).catch(console.error);
设计模式概要:
  1. 模型-视图-控制器(MVC)模式
  • UserModel 对应 MVC 架构中的模型部分。
  • UserController 负责 MVC 架构中的控制器部分。
  • 视图部分在这个例子中没有直接展示,但通常会涉及前端组件。

二. 仓库模式:

  • UserRepository 提供了一个类似集合的接口来访问用户资料。

3. 服务模式如下

  • UserService 的包含了与用户相关的操作的处理逻辑。

4. 工厂模式

  • UserFactory 包含了 UserService 的创建逻辑。

5. 依赖注入(DI)模式

  • UserFactoryUserRepository 注入到 UserService

6. 单一职责原则(SRP),即一个模块或类应该只负责一项职责

每个类只有一个职责,这样有助于维护和理解。

通过实现这些设计模式,你可以为你的应用程序创建一个坚固且可维护且可扩展的架构。这样做分离了关注点,促进代码重用,并使代码更便于测试和维护。

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消