【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字段。
- 使用id字段可以方便直接hash查找缓存的处理函数方法
- 使用httpmethod的主要原因是我们需要支持针对单个处理函数指定它只接收某一种httpmethod方式的请求。
好比route.post('/path',(req,res,next)=>{});就只能处理post请求。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义