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

    项目源码

  • 相关阅读:
    js中的计时器事件`setTimeout()` 和 `setInterval()`
    我的人生“意义”
    我活着的“形而上学”
    关于“我的”恶意
    不排他,与“我”的可能性
    【原创诗歌】自觉原理第十六章让你想照亮前程
    【原创诗歌】读书的梦:羡慕与期待
    【原创】楼兰老家
    【原创诗歌】青春咒语
    【原创】仓央嘉措,在心底活着
  • 原文地址:https://www.cnblogs.com/xueyubao/p/13658566.html
Copyright © 2020-2023  润新知