在express中使用ES7装饰器构建路由
在Java的Spring框架中,我们经常会看到类似于@Controller这样的注解,这类代码能够极大的提高我们代码的可读性和复用性。而在Javascript的ES7提案中,有一种新的语法叫做decorator,它能够在Javascript中实现与注解相同的功能。
@tuzilow/express-decorator
@tuzilow/express-decorator是由本人开发的一个简单的express装饰器包,具有@Controller、@RootUrl、@Get等API,能够方便快捷的构建express后台接口。
正式开始
创建package.json
执行npm init,并使用npm或yarn添加以下依赖
{
"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/user和http://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');
});
项目源码
- GitHub仓库地址:Tuzilow/express-decorator
- npm地址:@tuzilow/express-decorator
在express中使用ES7装饰器构建路由的更多相关文章
- Python中利用函数装饰器实现备忘功能
Python中利用函数装饰器实现备忘功能 这篇文章主要介绍了Python中利用函数装饰器实现备忘功能,同时还降到了利用装饰器来检查函数的递归.确保参数传递的正确,需要的朋友可以参考下 " ...
- Angular 个人深究(一)【Angular中的Typescript 装饰器】
Angular 个人深究[Angular中的Typescript 装饰器] 最近进入一个新的前端项目,为了能够更好地了解Angular框架,想到要研究底层代码. 注:本人前端小白一枚,文章旨在记录自己 ...
- python 中多个装饰器的执行顺序
python 中多个装饰器的执行顺序: def wrapper1(f1): print('in wrapper1') def inner1(*args,**kwargs): print('in inn ...
- 第7.17节 Python类中的静态方法装饰器staticmethod 定义的静态方法深入剖析
第7.17节 Python类中的静态方法装饰器staticmethod 定义的静态方法深入剖析 静态方法也是通过类定义的一种方法,一般将不需要访问类属性但是类需要具有的一些能力可以静态方法提供. 一 ...
- 第7.26节 Python中的@property装饰器定义属性访问方法getter、setter、deleter 详解
第7.26节 Python中的@property装饰器定义属性访问方法getter.setter.deleter 详解 一. 引言 Python中的装饰器在前面接触过,老猿还没有深入展开介绍装饰 ...
- ts装饰器的用法,基于express创建Controller等装饰器
TS TypeScript 是一种由微软开发的自由和开源的编程语言.它是 JavaScript 的一个超集,而且本质上向这个语言添加了可选的静态类 型和基于类的面向对象编程. TypeScript 扩 ...
- EntityFramework中使用Repository装饰器
铺垫 通常在使用 EntityFramework 时,我们会封装出 IRepository 和 IUnitOfWork 接口,前者负责 CRUD 操作,后者负责数据提交 Commit. public ...
- nodejs+express中设置登录拦截器
在nodejs+express中,采用nodejs后端路由控制用户登录后,为了加强前端的安全性控制,阻止用户通过在浏览器地址栏中输入地址访问后台接口,在app.js中需要加入拦截器进行拦截: /*** ...
- Python中的各种装饰器详解
Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义. 一.函数式装饰器:装饰器本身是一个函数. 1.装饰函数:被装饰对象是一个函数 [1]装饰器无参数: a.被装饰对象无参数: ...
随机推荐
- Python多进程实现并行化随机森林
文章目录 1. 前言 2. 随机森林原理 3.实现原理 3.1并行化训练 3.1.1训练函数 3.1.2 单进程训练函数 生成数据集模块--生成部分数据集 单进程训练函数代码 3.2 并行化预测 3. ...
- Jira 和 Confluence 企业最佳部署方式
在Atlassian,我们为客户提供不同的方式来部署 Atlassian 产品:可以部署在由 Altassian 管理的云端(Cloud)上,也可以部署在客户自己选择的服务器(Server)或数据中心 ...
- (转)@Autowired(required=false)注入注意的问题
1.前言 在使用spring开发过程中,我们基本上都是使用@Autowired这个注解,用来注入已有的bean.但是有些时候,会注入失败.当我们加上参数(required=false)就能解决.今天整 ...
- linux驱动之内核多线程(二)
本文摘自http://www.cnblogs.com/zhuyp1015/archive/2012/06/11/2545702.html 内核多线程是在项目中使用到,自己也不熟悉,遇到一个很囧的问题, ...
- Antd cracoTs Js 配置流程
JS:文档:0.1.4 配置 js 环境.note链接:http://note.youdao.com/noteshare?id=e32fa75c1baa014b5819fa5e22887dbc& ...
- Jmeter 常用函数(18)- 详解 __isDefined
如果你想查看更多 Jmeter 常用函数可以在这篇文章找找哦 https://www.cnblogs.com/poloyy/p/13291704.htm 作用 判断 Jmeter 变量是否存在,1 就 ...
- cni-ipam-etcd demo
链接:https://github.com/jeremyxu2010/cni-ipam-etcd 测试demo: package main import ( "fmt" " ...
- cinderclient命令行源码解析
一.简介 openstack的各个模块中,都有相应的客户端模块实现,其作用是为用户访问具体模块提供了接口,并且也作为模块之间相互访问的途径.Cinder也一样,有着自己的cinder-client. ...
- 基于 abp vNext 微服务开发的敏捷应用构建平台 - 设计构想
许多中小企业的管理模式都是在自身的发展过程中不断摸索,逐步建立起来的,每一家都有其独有的管理模式,而且随着企业的不断发展,管理模式也在不断变化中.企业在发展壮大的过程中离不开信息化系统的支撑,企业在构 ...
- python编程中的并发------多进程multiprocessing
任务例子:喝水.吃饭动作需要耗时1S 单任务:(耗时20s) for i in range(10): print('a正在喝水') time.sleep(1) print('a正在吃饭') time. ...