最近 和别人一块运维 开源 产品,后台需要用到 midway框架,所以进行学习。

首先就是midway的搭建,

首先 npm init midway ,初始化项目,选择 koa-v3 template

启动项目 npm run dev,此刻对应后台地址可以访问。

编写Controller

import { Controller,Get } from '@midwayjs/decorator';

@Controller('/')
export class WeatherController{ @Get('/weather')
async getWeatherInfo():Promise<string>{
return "Hello Weather!";
}
}

添加参数处理

import { Controller,Get,Query } from '@midwayjs/decorator';

@Controller('/')
export class WeatherController{
@Get('/weather')
async getWeatherInfo(@Query('id') cityId:string):Promise<string>
{
return cityId;
}
}

编写Service

import { Provide } from '@midwayjs/decorator';
import { makeHttpRequest } from '@midwayjs/core';
import { WeatherInfo } from '../interface'; @Provide()
export class WeatherService{
async getWeather(cityId:string):Promise<WeatherInfo> {
const result = await makeHttpReauest(`http://www.weather.com.cn/data/cityinfo/${cityId}.html`,{
dataType:'json'
});
if(result.state===200){
return result.data;
}
}
}

在service里面 @Provide()是用来注入

在Controller中进行注入

@Inject()

weather:Weather;

weather.controller.ts代码修改如下

import { Controller,Get,Inject,Query } from '@midwayjs/decorator';
import { WeatherInfo } from '../interface';
import { WeatherService } from '../service/weather.service'; @Controller('/')
export class WeatherController{ @Inject()
weatherService:WeatherService; @Get('/weather')
async getWeatherInfo(@Query('cityId') cityid:string):Promise<WeatherInfo>{
return this.weatherService.getWeather(cityid);
}
}

模板渲染

使用view-nunjucks组件

npm i @midwayjs/view-nunjucks --save

安装好组件之后在src/configuration.ts文件中启用组件

 import * as view from '@midwayjs/view-nunjucks';

@Configuration({

  import[view],

       importConfigs:[join(_dirname,'./config')]

})

然后在src/config/config.default.ts中配置组件,指定 nunjucks模板。

import { MidwayConfig } from '@midwayjs/core';

export default{
view:{
defaultViewEngine: 'nunjucks'
}
}

然后在根目录设置模板内容,view/info.html

<!DOCTYPE html>
<html>
<head>
<title>天气预报</title>
<style>
.weather_bg {
background-color: #0d68bc;
height: 150px;
color: #fff;
font-size: 12px;
line-height: 1em;
text-align: center;
padding: 10px;
} .weather_bg label {
line-height: 1.5em;
text-align: center;
text-shadow: 1px 1px 1px #555;
background: #afdb00;
width: 100px;
display: inline-block;
margin-left: 10px;
} .weather_bg .temp {
font-size: 32px;
margin-top: 5px;
padding-left: 14px;
}
.weather_bg sup {
font-size: 0.5em;
}
</style>
</head>
<body>
<div class="weather_bg">
<div>
<p>
{{city}}({{WD}}{{WS}})
</p>
<p class="temp">{{temp}}<sup>℃</sup></p>
<p>
气压<label>{{AP}}</label>
</p>
<p>
湿度<label>{{SD}}</label>
</p>
</div>
</div>
</body>
</html>

然后调整Controller代码,将返回JSON变成模板渲染

主要是用 @midwayjs/koa 里面的Context

this.ctx.render('info',result.weather);

错误处理

定义错误 在src/error/weather.error.ts

import { MidwayError } from '@midwayjs/core';

export class WeatherEmptyDataError extends MidwayError{

  constructor(err?:Error){

    super('weather data is empty',{

      cause:error
    });
    if(err?.stack){       this.stack = err.stack;
    }
  } }

在service代码中进行抛出错误

throw new WeatherEmptyDataError

通过拦截器进行错误处理

在src/filter/weather.filter.ts中进行处理

import { Catch } from '@midwayjs/decorator';

import { Context } from '@midwayjs/koa';

import { WeatherEmptyDataError } from '../error/weather.error';

@Catch(WeatherEmptyDataError)

export class WeatherErrorFilter{

  async catch(err:WeatherEmptyDataError,ctx:context){

    ctx.logger.error(err);
    return '<html><body><h1>weather data is empty</h1></body></html>';
  } }

然后在生命周期ready时候启用filter

在ContainerLifeCycle中的OnReady

里面启用this.app.useFilter([ WeatherErrorFilter ]);

单元测试

import { createApp, close, createHttpRequest } from '@midwayjs/mock';
import { Framework, Application } from '@midwayjs/koa'; describe('test/controller/weather.test.ts', () => { let app: Application;
beforeAll(async () => {
// create app
app = await createApp<Framework>();
}); afterAll(async () => {
// close app
await close(app);
}); it('should test /weather with success request', async () => {
// make request
const result = await createHttpRequest(app).get('/weather').query({ cityId: 101010100 }); expect(result.status).toBe(200);
expect(result.text).toMatch(/北京/);
}); it('should test /weather with fail request', async () => {
const result = await createHttpRequest(app).get('/weather'); expect(result.status).toBe(200);
expect(result.text).toMatch(/weather data is empty/);
});
});

midway 框架学习的更多相关文章

  1. IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API

    IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习之保护API. 使用IdentityServer4 来实现使用客户端凭据保护ASP.N ...

  2. Hadoop学习笔记—18.Sqoop框架学习

    一.Sqoop基础:连接关系型数据库与Hadoop的桥梁 1.1 Sqoop的基本概念 Hadoop正成为企业用于大数据分析的最热门选择,但想将你的数据移植过去并不容易.Apache Sqoop正在加 ...

  3. Spring框架学习一

    Spring框架学习,转自http://blog.csdn.net/lishuangzhe7047/article/details/20740209 Spring框架学习(一) 1.什么是Spring ...

  4. EF框架学习手记

    转载: [ASP.NET MVC]: - EF框架学习手记 1.EF(Entity Framework)实体框架EF是ADO.NET中的一组支持开发面向数据的软件应用程序的技术,是微软的一个ORM框架 ...

  5. web框架学习列表

    转载自鲁塔弗的博客,原文网址:http://lutaf.com/148.htm web framework层出不穷,特别是ruby/python,各有10+个,php/java也是一大堆 根据我自己的 ...

  6. 2013 最新的 play web framework 版本 1.2.3 框架学习文档整理

    Play framework框架学习文档 Play framework框架学习文档 1 一.什么是Playframework 3 二.playframework框架的优点 4 三.Play Frame ...

  7. SSH 框架学习之初识Java中的Action、Dao、Service、Model-收藏

    SSH 框架学习之初识Java中的Action.Dao.Service.Model-----------------------------学到就要查,自己动手动脑!!!   基础知识目前不够,有感性 ...

  8. 各种demo——CI框架学习

    各种demo——CI框架学习   寒假学习一下CI框架,请各位多多指教! 一.CI的HelloWorld! 注意:CI禁止直接通过文件目录来访问控制器. ./application/controlle ...

  9. phalcon(费尔康)框架学习笔记

    phalcon(费尔康)框架学习笔记 http://www.qixing318.com/article/phalcon-framework-to-study-notes.html 目录结构   pha ...

  10. Yii框架学习 新手教程(一)

    本人小菜鸟一仅仅,为了自我学习和交流PHP(jquery,linux,lamp,shell,javascript,server)等一系列的知识,小菜鸟创建了一个群.希望光临本博客的人能够进来交流.寻求 ...

随机推荐

  1. py06

    元祖tuple 与列表类似可以存多个值,但是不同的是元祖本身不能被修改 #一:基本使用:tuple# 1 用途:记录多个值,当多个值没有改的需求,此时用元组更合适 # 2 定义方式:在()内用逗号分隔 ...

  2. python存储xml格式数据

    例子 import xml.dom.minidom # 在内存中创建一个空的文档 doc = xml.dom.minidom.Document() # 创建一个根节点Managers对象 root = ...

  3. String和StringBuffer与StringBuilder的区别

    1.String.StringBuffer.StringBuilder都不可以被继承,在JDK中它们都被定义为final类. 2.执行速度:StringBuilder > StringBuffe ...

  4. Vulnhub 靶场 LOOZ: 1

    Vulnhub 靶场 LOOZ: 1 前期准备: 靶机地址:https://www.vulnhub.com/entry/looz-1,732/ kali攻击机ip:192.168.147.190 靶机 ...

  5. linux 下用其他用户来执行命令

    sudo su - username -l -c "supervisorctl restart apps" -l , –login:加了这个参数之后,就好像是重新登陆一样,大部分环 ...

  6. HDLbits——Shift18

    // Build a 64-bit arithmetic shift register, // with synchronous load. The shifter can shift both le ...

  7. Blob下载

    下载方式 const aBlob = new Blob( array, options ); export function downLoadFile(data: ArrayBuffer, fileN ...

  8. No.1.6

    结构伪类选择器 根据元素在HTML中的结构关系查找元素 选择器 说明 E:first-child{} 匹配父元素中的第一个子元素,并且是E元素 E:last-child{} 匹配父元素中的最后一个子元 ...

  9. abap 自定义搜索帮助

    ABAP 选择屏幕 自定义搜索帮助 物料号为例 如图展示的物料,是不经过自定义搜索帮助处理的,如果我只需要物料描述和物料号,且只限定20开头的物料,就需要用到自定义搜索帮助了 当使用自定义帮助后 效果 ...

  10. wxPython绘图API

    简单介绍一个Pthon的绘图库wxPython. GDI+(图形绘制接口),CoreGraphics和Cairo库形成wxPython绘图API的框架.wx.GraphicsContext是主要绘制对 ...