在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');
});

项目源码

在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. 蒲公英 · JELLY技术周刊 Vol.17: 90 行代码实现 React Hooks

    蒲公英 · JELLY技术周刊 Vol.17 React Hooks 相信大家都不陌生,自被设计出以来就备受好评,在很多场景中都有极高的使用率,其中原理更是很多大厂面试中的必考题,很多朋友都能够如数家 ...

  2. Python中ansible的使用

    #!/usr/bin/env python # -*- coding: utf8 -*- # @Author: huangmanyao from ansible import constants fr ...

  3. 写给程序员的机器学习入门 (八 补充) - 使用 GPU 训练模型

    在之前的文章中我训练模型都是使用的 CPU,因为家中黄脸婆不允许我浪费钱买电脑.终于的,附近一个废品回收站的朋友转让给我一台破烂旧电脑,所以我现在可以体验使用 GPU 训练模型了

  4. eclipse中 sec/test/resource 文件夹消失怎么设置?

    右键改包--->build path --->Configure bulid path 按 add Folder 搞定.....

  5. POJ2806 Square

    题目描述 给定\(2*1\)和\(2 * 2\)两种规格的地砖,请问\(2 * n\)的地面总共有多少种方法? 下面是铺满\(2*17\)的地面的示意图. 输入输出格式 输入 多组数据,每组数据包括1 ...

  6. Spring注解驱动开发04(给容器中注册组件的方式)

    给容器中注册组件的方式 1. 组件注解标注 + 包扫描(适用于自己写的类) //控制层组件 @Controller public class PersonController { } //业务逻辑层组 ...

  7. java 工具类Integer

    Integer 是lang包下的工具类 为了更加熟悉Integer中的方法使用和理解 进行了一部分代码和原代码的总结 Intrger工具类方法: * * int parseInt(String s) ...

  8. LINUX进程ps -ef和ps -aux的区别及格式详解

    Linux下显示系统进程的命令ps,最常用的有ps -ef 和ps aux.这两个到底有什么区别呢?两者没太大差别,讨论这个问题,要追溯到Unix系统中的两种风格,System V风格和BSD 风格, ...

  9. python安装numpy、scipy、gensim以及报错unable to import 'smart_open.gcs', disabling that module处理

    首先,安装gensim库,必须先安装numpy+mkl和scipy 安装顺序是依次安装numpy+kml.scipy.gensim,根据自己Python下载的版本进行下载 如果你的库里面有numpy. ...

  10. codeforce Round #605(Div.3)

    A. Three Friends 题目链接 题目意思:有三个好朋友a,b,c.他们在一个坐标轴上,他们的位置分别是xa 和xb ,xc,他们三个人都可以往前或者往后走一步,只能走一步.问你他们走了(也 ...