最近 和别人一块运维 开源 产品,后台需要用到 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. 小程序嵌套h5webview.特定时间跳转小程序页面.调起e证通的人脸核身.成功了返回webview.

    e证通链接. https://cloud.tencent.com/document/product/1007/56643#3.2-.E5.AE.89.E8.A3.85-sdk

  2. form 表单中input 使用disable属性

    记录一下今天踩得坑. 在使用form表单提交的时候,input用了disable属性,在查找了好久之后,找到原因,万万没想到是因为disable. 修改方法:disable改为readonly dis ...

  3. Flutter 3.+更新记录

    Flutter3.3稳定版出来了,于是决定把之前Flutter工程的代码更新下其中里面有些涉及到组件的弃用 在此记录 ElevatedButton 代替了 RaisedButton 为带阴影的悬浮按钮 ...

  4. Linux下获取线程ID tid的方法

    使用Linux Redhat7编写代码的时候,需要使用 gettid() 函数获取线程ID.使用 man gettid 命令查看了一下,gettid()函数的头文件是 #include<sys/ ...

  5. SQL Server性能优化

    源代码文件 1,什么是性能问题? 现有资源没有达到最大吞吐量的前提下,系统不能满足合理的预期表现,则可以定义为有性能问题.性能指标包括:响应时间,吞吐量,可扩展性. 2,初探优化 2.1优化论 一般遇 ...

  6. taobao.tbk.sc.newuser.order.get( 淘宝客-服务商-新用户订单明细查询 )

    淘宝客订单表结构设计(mysql) CREATE TABLE `tbk_order` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `member_id` bi ...

  7. vs2019 文件读取操作

    1 #include<stdio.h> 2 #define INF 10000000 3 int main() 4 { 5 FILE* fin , * fout ; 6 errno_t a ...

  8. HDLbits—— 3-input look-up-table

    // a 3-input look-up-table // In this question, you will design a circuit for an 8x1 memory, // wher ...

  9. 92、kkfile打印当前页

    使用kkfile预览pdf时,有肯能需要打印其中的某一张.如果pdf中有几百张,那么打印加载就会很慢.打印当前页就不会出现这个问题. 这个是我编译后的,有需要的请联系QQ: 1842988062

  10. c中遍历lua的表

    //遍历lua表,index为表在栈中的位置 void traverse_table(lua_State* L, int index) { lua_pushnil(L); stack_dump(L); ...