• 【nodejs】让nodejs像后端mvc框架(asp.net mvc )一样处理请求--路由限制及选择篇(2/8)【route】


    文章目录

    前情概要

    上文中的RouteHandler中有一个重要方法GetActionDescriptor没有贴代码和说,接下来我们就说一说这个方法。

    使用controllerName、actionName、httpmethod获得唯一匹配的处理函数描述对象

    直接上代码,看代码注释即可

    //action注册缓存对象
    let _dic_override = new Map<string, Map<string, ActionDescriptor>>();
    //最终路由到action映射关系的缓存对象
    let _dic_buid_routes: Map<string, Map<string, ActionDescriptor>>;
    
    export function GetActionDescriptor(controllerName: string, actionName: string, method?: string): ActionDescriptor | undefined {
    //没有build过,则build一下。把路由到action的映射关系解析好
        if (!_dic_buid_routes) build();
    //获得controller描述对象
        var c = _dic_buid_routes.get(controllerName)
        if (!c)
            return;
            //从controller描述对象中获得对应action,先根据请求类型_action名称来获取,获取不到的情况下则直接用action名称来获取。
        var a = c.get(actionName + (method ? '_' + method.toLowerCase() : ''));
        if (!a)
            a = c.get(actionName)
        return a;
    }
    //对controller和action名称默认做小写处理。匹配的时候方便一点。url不区分大小写嘛。
    //{"controllerName":{"post_addUser":{描述对象},"getuserinfo":{描述对象}}}。类似如此结构。
    function build() {
        _dic_buid_routes = new Map<string, Map<string, ActionDescriptor>>();
        _dic_override.forEach((v, k, m) => {
            if (v.size <= 0)
                return;
            var cname = '';
            var aMap = new Map<string, ActionDescriptor>();
            v.forEach((av, ak, am) => {
                cname = av.ControllerName;
                aMap.set(av.Id.toLowerCase(), av);
            })
            _dic_buid_routes.set(cname.toLowerCase(), aMap)
        })
    }
    

    GetActionDescriptor方法中先检查是否build过,没有则build完成之后,根据对应规则查找相应的描述对象并返回,交给后续的中间件使用。

    为什么需要ActionDescriptor对象。

    请求处理函数描述对象保存了当前处理函数的一些基本信息,比如controllername的名称,所在类的名称,所在类的原型。函数的名称,请求中函数的别,函数的原型,请求方法的约束等基本信息

    export class ActionDescriptor {
       public ControllerType: any;
       public ControllerTypeName: string;
       public ControllerName: string;
       public ActionType: any;
       public ActionTypeName: string;
       public ActionName: string;
       public HttpMethod: string;
       public Id: string;
       public isAuth?: boolean;
    }
    

    为什么要使用httpmethod_actionname 的格式规定id字段。

    1. 使用id字段可以方便直接hash查找缓存的处理函数方法
    2. 使用httpmethod的主要原因是我们需要支持针对单个处理函数指定它只接收某一种httpmethod方式的请求。
      好比route.post('/path',(req,res,next)=>{});就只能处理post请求。
  • 相关阅读:
    解决通用串行总线(USB)控制器有感叹号
    开发者需要了解的WebKit
    Win7系统搭建WiFi热点详细攻略
    给Qt生成的exe执行程序添加版本信息
    IIS(IISReset.exe)命令行
    .net开发微信公众平台
    使用ExitProcess()结束本进程、TerminateProcess 结束进程
    Hosts文件路径及修改方法
    本地动态SQL
    Oracle Package
  • 原文地址:https://www.cnblogs.com/calvinK/p/nodejs-mvc-route-auto-match-selected.html
Copyright © 2020-2023  润新知