overnightjs 提供了基于注解的expressjs应用开发,包含了比较全的express 开发支持,使用简单,以下是一个简单的试用

项目准备

项目使用pkg 进行了打包处理

  • 初始化
yarn  init -y
  • 添加依赖
yarn add @overnightjs/core @overnightjs/logger express http-status-codes
yarn add @types/express pkg typescript --dev
  • pacakge.json 文件
    添加了npm script 以及pkg 打包的配置
 
{
  "name": "ts-express-decrator",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "node dist/index.js",
    "live": "tsc -w",
    "package": "pkg --options expose-gc -d ."
  },
  "bin": "dist/index.js",
  "pkg": {
    "scripts": "dist/**/*.js"
  },
  "dependencies": {
    "@overnightjs/core": "^1.6.8",
    "@overnightjs/logger": "^1.1.8",
    "express": "^4.17.1",
    "http-status-codes": "^1.3.2"
  },
  "devDependencies": {
    "@types/express": "^4.17.1",
    "pkg": "^4.4.0",
    "typescript": "^3.6.3"
  }
}
  • typescript config
{
  "compilerOptions": {
    "target": "es5",                           
    "module": "commonjs",                       
    "declaration": true,                    
    "outDir": "./dist",                         
    "removeComments": true,                 
    "strict": true,                           
    "rootDirs": [],
    "esModuleInterop": true,  
    "experimentalDecorators": true,         
    "emitDecoratorMetadata": true     
  }
}
 

代码编写

  • 代码结构
src
├── SampleServer.ts
├── UserController.ts
└── index.ts
  • 代码说明
    index.ts 为应用的入口,SampleServer.ts 为 express server 的定义,UserController.ts 是一个rest 服务的定义
    SampleServer.ts 代码:
 
import * as bodyParser from 'body-parser';
import { Server } from '@overnightjs/core';
import { Logger } from '@overnightjs/logger';
import { UserController } from './UserController';
export class SampleServer extends Server {
    constructor() {
        super(process.env.NODE_ENV === 'development'); // setting showLogs to true
        this.app.use(bodyParser.json());
        this.app.use(bodyParser.urlencoded({extended: true}));
        this.setupControllers();
    }
    private setupControllers(): void {
        const userController = new UserController();
        // super.addControllers() must be called, and can be passed a single controller or an array of 
        // controllers. Optional router object can also be passed as second argument.
        super.addControllers([userController]/*, optional router here*/);
    }
    public start(port: number): void {
        this.app.listen(port, () => {
            Logger.Imp('Server listening on port: ' + port);
        })
    }
}

UserController.ts:

import { OK } from 'http-status-codes';
import { Controller, Get, Post } from '@overnightjs/core';
import { Logger } from '@overnightjs/logger';
import { Request, Response } from 'express';
@Controller('user/say-hello')
export class UserController {
    @Get()
    private get(req: Request, res: Response): any {
        Logger.Info('get called');
        return res.status(OK).json({
            message: 'get_called',
        });
    }
    @Post()
    private post(req: Request, res: Response): any {
        Logger.Info('post called');
        return res.status(OK).json({
            message: 'post_called',
        });
    }
}
  • index.ts
import { SampleServer } from "./SampleServer";
let myServer = new SampleServer()
myServer.start(3000)

构建&&启动

  • 构建
yarn live
  • 打包
yarn packagee
  • 运行打包的应用

    mac 系统,当然打包是跨平台的

./ts-express-decrator-macos 
[2019-10-08T07:01:21.168Z]: Server listening on port: 3000
  • 访问效果
curl -i http://localhost:3000/user/say-hello
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 24
ETag: W/"18-aJruZ7f86jURaNXHzg+3fDFbLjs"
Date: Tue, 08 Oct 2019 07:02:02 GMT
Connection: keep-alive
{"message":"get_called"}% 

说明

使用overnightjs 开发express 应用还是很方便的,当然 routing-controllers 也是一个不错的选择(更新还很频繁),而且typestack 团队开发
的好多typescript 的框架也是很好用的。

参考资料

https://github.com/seanpmaxwell/overnight
https://github.com/typestack/routing-controllers

使用overnightjs typescript 注解开发expressjs 应用的更多相关文章

  1. SpringMVC注解开发初步

    一.(补充)视图解析器---XmlViewResolver 作用:分离配置信息. 在视图解析器---BeanNameViewResolver的基础之上进行扩充,新建一个myView.xml分离信息 在 ...

  2. SpringMVC的注解开发入门

    1.Spring MVC框架简介 支持REST风格的URL 添加更多注解,可完全注解驱动 引入HTTP输入输出转换器(HttpMessageConverter) 和数据转换.格式化.验证框架无缝集成 ...

  3. Struts2框架之-注解开发

    Struts2主要解决了从JSP到Action上的流程管理,如何进行Uri和action类中每个方法的绑定这是重点,在这里先简单看一下配置文件中的简单配置: <span style=" ...

  4. Java自定义注解开发

    一.背景 最近在自己搞一个项目时,遇到可需要开发自定义注解的需求,对于没有怎么关注这些java新特性的来说,比较尴尬,索性就拿出一些时间,来进行研究下自定义注解开发的步骤以及使用方式.今天在这里记下, ...

  5. 基于Nodejs生态圈的TypeScript+React开发入门教程

    基于Nodejs生态圈的TypeScript+React开发入门教程   概述 本教程旨在为基于Nodejs npm生态圈的前端程序开发提供入门讲解. Nodejs是什么 Nodejs是一个高性能Ja ...

  6. Annotation(四)——Struts2注解开发

    Hibernate和Spring框架的开发前边总结了,这次看一下流行的MVC流程框架Struts2的注解开发吧.Struts2主要解决了从JSP到Action上的流程管理,如何进行Uri和action ...

  7. Annotation(三)——Spring注解开发

    Spring框架的核心功能IoC(Inversion of Control),也就是通过Spring容器进行对象的管理,以及对象之间组合关系的映射.通常情况下我们会在xml配置文件中进行action, ...

  8. Annotation(一)——注解开发介绍

    <p>在编程中,一直强调的一点就是注释的编写,注释的规范等等.尤其是越是核心,程序越复杂,逻辑越多的清空下,注释的编写对我们以后的阅读代码,维护软件起着至关重要的作用.一款软件有着好的注释 ...

  9. spring注解开发中常用注解以及简单配置

    一.spring注解开发中常用注解以及简单配置 1.为什么要用注解开发:spring的核心是Ioc容器和Aop,对于传统的Ioc编程来说我们需要在spring的配置文件中邪大量的bean来向sprin ...

随机推荐

  1. MIME类型对应表:

    MIME类型对应表: 常用MIME类型: 扩展名 MIME类型 .iso ISO File .rar application/x-rar-compressed .zip application/zip ...

  2. golang学习笔记 ---interface

    1. 什么是interface接口 interface 是GO语言的基础特性之一.可以理解为一种类型的规范或者约定.它跟java,C# 不太一样,不需要显示说明实现了某个接口,它没有继承或子类或“im ...

  3. golang 学习笔记 -- 类型

    int 和 uint的实际宽度会根据计算架构不同而不同,386下4个字节, amd64下8个字节 byte可看做uint8的别名类型 rune可看做int32的别名类型,专用于存储Unicode编码的 ...

  4. C#读写修改设置调整UVC摄像头画面-缩放

    有时,我们需要在C#代码中对摄像头的缩放进行读和写,并立即生效.如何实现呢? 建立基于SharpCamera的项目 首先,请根据之前的一篇博文 点击这里 中的说明,建立基于SharpCamera的摄像 ...

  5. docker学习之路-nginx镜像(翻译)

    本篇来自https://hub.docker.com/_/nginx/?tab=description 它是docker hub上nginx的官方网站,上面有关于nginx的使用描述等.从这里你可以找 ...

  6. Eclipse集成Git做团队开发

    在日常开发工作中,我们通常使用版本控制软件管理团队的源代码,常用的SVN.Git.与SVN相比,Git有分支的概念,可以从主分支创建开发分支,在开发分支测试没有问题之后,再合并到主分支上去,从而避免了 ...

  7. js多个参数(追加参数)

    /** * 多个参数 * @param fn * @param args * @param scope */ function multipleArguments(fn,args,scope){ if ...

  8. js学习之数据结构和算法

    js中的数据结构 1.列表 待办事项列表.购物清单.最佳十名榜单等等. 适用: 1)数据结构较为简单, 2)不需要在一个长序列中查找元素,或者对其进行排序 2.栈 一摞盘子 ----- 添加删除只能从 ...

  9. Spring Boot加载application.properties配置文件顺序规则

    SpringApplication会从以下路径加载所有的application.properties文件: 1.file:./config/(当前目录下的config文件夹) 2.file:./(当前 ...

  10. Python 常用语句

    条件语句 a=input("请输入数字a的值:\n") a=int(a) #从控制台接收到的都是字符串类型,需要转换 if a==0: #也可以写成if(a==0): print( ...