zoukankan      html  css  js  c++  java
  • 在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,并使用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');
    });
    

    项目源码

  • 相关阅读:
    c++ 左值、右值;左值引用、右值引用
    leetcode 837 新21点
    c++ 继承和组合
    ubuntu 16.04 常用命令小结
    vim 常用命令小结(转)
    leetcode 1371. 每个元音包含偶数次的最长子字符串 (状压 + 前缀和 +hash)
    leetcode 974 和可被K整除的子数组
    leetcode 910 最小差值II
    关于 mysqladmin
    PHP闭包(Closure)初探
  • 原文地址:https://www.cnblogs.com/xueyubao/p/13658566.html
Copyright © 2011-2022 走看看