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. Ubuntu Docker搭建GitLab以及常规配置使用

    安装启动实例 1.首先创建一个目录用于存放配置 sudo docker pull docker.io/gitlab/gitlab-ce sudo mkdir -p /root/docker/gitla ...

  2. Prometheus 配置文件详解

    Prometheus 配置文件详解 官方文档:https://prometheus.io/docs/prometheus/latest/configuration/configuration/ 指标说 ...

  3. Java分布式唯一ID生成方案——比UUID效率更高的生成id工具类

    package com.xinyartech.erp.core.util; import java.lang.management.ManagementFactory; import java.net ...

  4. http://www.cnblogs.com/xdp-gacl/p/4200090.html

    孤傲苍狼 只为成功找方法,不为失败找借口! JavaWeb学习总结(五十)——文件上传和下载 在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功 ...

  5. .net HttpClient 回传实体帮助类

    public class HttpClientHelper<T> { /// <summary> /// Get请求 返回实体 /// </summary> /// ...

  6. 两数相加(C#数据结构和算法练习)

    两数相加 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表 ...

  7. C#读写设置修改调整UVC摄像头画面-白平衡

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

  8. 简约而不简单的Django2.2 新手图文教程

     欢迎大家访问我的个人网站<刘江的博客和教程>www.liujiangblog.com  主要分享Python 及Django教程以及相关的博客! 版权所有,转载需注明来源! 2019年7 ...

  9. Java自学-日期 Calendar

    Java的Calendar类 Calendar类即日历类,常用于进行"翻日历",比如下个月的今天是哪天 示例 1 : Calendar与Date进行转换 采用单例模式获取日历对象C ...

  10. consul:健康检查

    官方文档:https://www.consul.io/docs/agent/checks.html consul提供的健康检查有以下几种: 1.script+interval 2.http+inter ...