最近 和别人一块运维 开源 产品,后台需要用到 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. 脚本执行sudo命令时: 免手动确认和免输入密码

    1.sudo 命令有时候需要手动输入yes来确认执行 或者 软件在安装包下载完毕后还需要你输入y进行确认安装 .那如果是用脚本执行sudo 命令就可以用-y 参数来确认执行 sudo yum inst ...

  2. 关系型数据库,基表Guid 主键设值

    在我们开发过程,为了自动适应新增修改,可以对基表,Guid 类型进行如下设置: public bool IsTransient() {       return this.Id == Guid.Emp ...

  3. Azkaban 4.0.0 系列(一)-- Solo-Server

    下载 链接 https://github.com/azkaban/azkaban/releases/4.0.0.tar.gz 解压 tar -xzvf 4.0.0.tar.gz -C 自定义目标目录 ...

  4. docker 可视化平台Portainer搭建

    1.部署步骤 docker pull portainer/portainer docker run -d -p 9001:9000 \--restart=always \-v /var/run/doc ...

  5. 更改svn地址

    svn修改了服务器地址之后,本地要更新一下地址: 1. 在svn目录上右键,选TortoiseSVN->Relocate 2. 在To URL中填写新的地址,点击OK

  6. leetcode 310. 最小高度树 【时间击败70.67%】 【内存击败89.04%】

    数组替代队列,从超时到击败70%,用tree[0]替代new一个新的ArrayList,上升10% 思想是遍历一遍,删除度为1的节点,答案只可能为1或2 1 public List<Intege ...

  7. redis acl 修改密码

    #redis acl 修改密码 acl setuser readwrite on >111111111 ~* &* +@allacl setuser readonly on >11 ...

  8. 基于.NET Core3.1的SQLiteHelper增删改帮助类

    安装驱动包 install-package Microsoft.Data.Sqlite -version 3.1.7 install-package System.Data.SQLite.Core - ...

  9. 每日一抄 Go语言聊天服务器

    server.go package main import ( "bufio" "fmt" "log" "net" ) ...

  10. 第八章 mysql的主从复制

    mysql的主从复制 一 主从复制搭建 1. 准备三台主机  (这个是多实例) 3307 master3308 salve13309 salve2 2. master 节点设置 [mysqld] lo ...