在Java的Spring框架中,我们经常会看到类似于@Controller这样的注解,这类代码能够极大的提高我们代码的可读性和复用性。而在Javascript的ES7提案中,有一种新的语法叫做decorator,它能够在Javascript中实现与注解相同的功能。

@tuzilow/express-decorator

@tuzilow/express-decorator是由本人开发的一个简单的express装饰器包,具有@Controller@RootUrl@Get等API,能够方便快捷的构建express后台接口。

正式开始

创建package.json

执行npm init,并使用npmyarn添加以下依赖

{
"name": "decorator-demo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@tuzilow/express-decorator": "^0.0.3",
"express": "^4.17.1"
},
"devDependencies": {
"@babel/cli": "^7.11.6",
"@babel/core": "^7.0.0",
"@babel/node": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.10.4",
"@babel/plugin-proposal-decorators": "^7.10.5",
"@babel/preset-env": "^7.0.0",
"babel-eslint": "^9.0.0"
},
"scripts": {
"start": "babel-node index"
}
}

创建.babelrc

{
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }]
],
"presets": ["@babel/preset-env"]
}

创建index.js并编写代码

首先,编写一个普通的express应用

import express from 'express';

const Server = express();

Server.get('/', (req, res) => {
res.json({
title: 'hello world',
});
}); Server.listen(3000, () => {
console.info('running in http://localhost:3000');
});

执行无误后使用@tuzilow/express-decorator对其进行改造

import express from 'express';
import { Controller, Get } from '@tuzilow/express-decorator'; const Server = express(); @Controller
class User {
@Get('/')
home(req, res) {
res.json({
title: 'hello world',
});
}
} Server.use(new User()); Server.listen(3000, () => {
console.info('running in http://localhost:3000');
});

运行结果与前面普通的express应用的运行结果相同,如果想要设定统一的父级路由,可以使用@RootUrl

import express from 'express';
import { Controller, Get, RootUrl } from '@tuzilow/express-decorator'; const Server = express(); @Controller
class User {
@RootUrl('/user') url() {} @Get('/')
home(req, res) {
res.json({
title: 'hello world',
});
} @Get('/list')
list(req, res) {
res.json({
title: 'this is a list',
});
}
} Server.use(new User()); Server.listen(3000, () => {
console.info('running in http://localhost:3000');

这样请求路径就会变为http://localhost:3000/userhttp://localhost:3000/user/list,因为该装饰器包只提供了简易的API,因此传递参数、设置header等操作需要使用express的方法

import express from 'express';
import { Controller, Get, RootUrl, Post } from '@tuzilow/express-decorator'; const Server = express(); @Controller
class User {
@RootUrl('/user') url() {} @Get('/')
home(req, res) {
res.json({
title: 'hello world',
});
} // query传参
@Get('/getOne')
getOne(req, res) {
const { id } = req.query;
res.json({
title: 'hello world',
id,
});
} // params传参
@Get('/list/:id')
getItem(req, res) {
const { id } = req.params;
res.json({
title: 'hello world',
id,
});
} // body传参
@Post('/create')
create(req, res) {
const { id } = req.body;
res.json({
code: 0,
id,
});
}
} Server.use(new User()); Server.listen(3000, () => {
console.info('running in http://localhost:3000');
});

项目源码

在express中使用ES7装饰器构建路由的更多相关文章

  1. Python中利用函数装饰器实现备忘功能

    Python中利用函数装饰器实现备忘功能 这篇文章主要介绍了Python中利用函数装饰器实现备忘功能,同时还降到了利用装饰器来检查函数的递归.确保参数传递的正确,需要的朋友可以参考下   " ...

  2. Angular 个人深究(一)【Angular中的Typescript 装饰器】

    Angular 个人深究[Angular中的Typescript 装饰器] 最近进入一个新的前端项目,为了能够更好地了解Angular框架,想到要研究底层代码. 注:本人前端小白一枚,文章旨在记录自己 ...

  3. python 中多个装饰器的执行顺序

    python 中多个装饰器的执行顺序: def wrapper1(f1): print('in wrapper1') def inner1(*args,**kwargs): print('in inn ...

  4. 第7.17节 Python类中的静态方法装饰器staticmethod 定义的静态方法深入剖析

    第7.17节  Python类中的静态方法装饰器staticmethod 定义的静态方法深入剖析 静态方法也是通过类定义的一种方法,一般将不需要访问类属性但是类需要具有的一些能力可以静态方法提供. 一 ...

  5. 第7.26节 Python中的@property装饰器定义属性访问方法getter、setter、deleter 详解

    第7.26节 Python中的@property装饰器定义属性访问方法getter.setter.deleter 详解 一.    引言 Python中的装饰器在前面接触过,老猿还没有深入展开介绍装饰 ...

  6. ts装饰器的用法,基于express创建Controller等装饰器

    TS TypeScript 是一种由微软开发的自由和开源的编程语言.它是 JavaScript 的一个超集,而且本质上向这个语言添加了可选的静态类 型和基于类的面向对象编程. TypeScript 扩 ...

  7. EntityFramework中使用Repository装饰器

    铺垫 通常在使用 EntityFramework 时,我们会封装出 IRepository 和 IUnitOfWork 接口,前者负责 CRUD 操作,后者负责数据提交 Commit. public ...

  8. nodejs+express中设置登录拦截器

    在nodejs+express中,采用nodejs后端路由控制用户登录后,为了加强前端的安全性控制,阻止用户通过在浏览器地址栏中输入地址访问后台接口,在app.js中需要加入拦截器进行拦截: /*** ...

  9. Python中的各种装饰器详解

    Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义. 一.函数式装饰器:装饰器本身是一个函数. 1.装饰函数:被装饰对象是一个函数 [1]装饰器无参数: a.被装饰对象无参数: ...

随机推荐

  1. C#LeetCode刷题之#720-词典中最长的单词(Longest Word in Dictionary)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4120 访问. 给出一个字符串数组words组成的一本英语词典.从 ...

  2. 从零开始,Windows操作系统下的超详细的阿里云发布项目过程

    ==================== 步骤0: 购买阿里云服务器 ==================== 0.1 从来没有搞过外网部署的我,当然是先买服务器了,感谢很多小伙伴的帮忙 0.2 登录 ...

  3. MyBatis-Pro,新一代的MyBatis增强框架

    框架功能 内置提供基础CRUD方法 提供根据方法名自进行单表查询(包括查询.统计.删除等) 接入方法 Spring Boot <dependency> <groupId>com ...

  4. Android学习进程 Java引用 Rxjava MVP

    第一份Android开发工作,以便于记录学习进程 Java引用 Java没有显式的使用指针,但对象的访问仍是通过指针实现的,所以直接对象之间的赋值会导致存储空间是数据的改变,如设置两个对象,其中对象一 ...

  5. vue keep-alive 不生效和多级(三级以上)缓存失败

    vue keep-alive https://cn.vuejs.org/v2/api/#keep-alive keep-alive 不生效的可能原因 如果安装官方的写法,已经正常完成keep-aliv ...

  6. DB2根据报错代码查看表与字段信息

    select * from syscat.tables where tbspaceid='?' and tableid='?' select * from syscat.columns where t ...

  7. 阿里P8架构师大话设计模式,体会乐与怒的程序人生中值得回味一幕

    本书特色 本书有两个特色,第一特色是重视过程.看了太多的计算机编程类的图书,大多数书籍都是集中在讲授优秀的解决方案或者一个完美的程序样例,但对这些解决方案和程序的演变过程却重视不够,好书之所以好,就是 ...

  8. 【期外】(三)Linux下集成开发环境Geany

    今天小编发现了一个很好的软件,它的名字就叫做Geany. 这是Linux系统中的开发工具,相当的好用. Linux与windows最大的不同正是不是集成开发环境,所以写起代码来总是用文档写好后,然后再 ...

  9. JDK1.8源码学习-LinkedList

    JDK1.8源码学习-LinkedList 目录 一.LinkedList简介 LinkedList是一个继承于AbstractSequentialList的双向链表,是可以在任意位置进行插入和移除操 ...

  10. CCF-202006-1线性分类器

    1 def judga(lis1,z): #判断列表lis1中点是否都在线z的一侧 s=0 for i in lis1: if z[0]+i[0]*z[1]+i[1]*z[2]>0: s+=1 ...