在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.被装饰对象无参数: ...
随机推荐
- nginx进程模型解析
nginx进程模型解析 概念 master会发送请求给worker,用于处理用户的请求,模型图如下 nginx进程分类 master进程(只有1个) 接受信号传递给worker wo ...
- 解决用anaconda安装scrapy后,在使用scrapy时报错
python版本为3.7 因为用anaconda安装scrapy非常方便,会自动下载所依赖的包, 所以就使用anaconda安装scrapy, 非常舒服,安装很成功 conda install scr ...
- “既生 ExecutorService, 何生 CompletionService?”
前言 在 我会手动创建线程,为什么要使用线程池? 中详细的介绍了 ExecutorService,可以将整块任务拆分做简单的并行处理: 在 不会用Java Future,我怀疑你泡茶没我快 中又详细的 ...
- js对象的数据属性和访问器属性
js面向对象 ECMA-262第5版在定义只有内部才用的特性(attribute)时,描述了属性(property)的各种特征.ECMA-262定义这些特性是为了实现javascript引擎用的,因此 ...
- .netcore tif文件转jpg,并通过webapi返回
网上能搜到很多关于c# tif转jpg的代码.最简单的就是下面这段获得转换后的图片图片对象.在netcore 中使用这段代码时由于netcore框架已经不自带System.Drawing命名空间了所有 ...
- Core + Vue 后台管理基础框架9——统一日志
1.背景 前阵子有园友留言,提到日志相关的东西,同时,最近圈子里也有提到日志这个东西.一个充分.集中的统一日志平台还是很有必要的,否则系统出问题了只能靠猜或者干瞪眼.何谓充分,日志记录满足最低要求.出 ...
- Java callback回调
package com.callback; public interface CSCallBack { public void process(String status); } package co ...
- 准确率99.9%的离线IP地址定位库
Ip2region是什么? ip2region - 准确率99.9%的离线IP地址定位库,0.0x毫秒级查询,ip2region.db数据库只有数MB,提供了java,php,c,python,nod ...
- 企业项目实战 .Net Core + Vue/Angular 分库分表日志系统 | 简单的分库分表设计
前言 项目涉及到了一些设计模式,如果你看的不是很明白,没有关系坚持下来,写完之后去思考去品,你就会有一种突拨开云雾的感觉,所以请不要在半途感觉自己看不懂选择放弃,如果我哪里写的详细,或者需要修正请联系 ...
- 【Apollo】(2)--- Apollo架构设计
Apollo架构设计 上一篇博客有讲到:[Apollo](1)--- Apollo入门介绍篇 这篇来写Apollo的核心架构设计 一.整体架构 Apollo整体架构图,已由作者宋顺已经给出: 这幅图所 ...