midway 框架学习
最近 和别人一块运维 开源 产品,后台需要用到 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 框架学习的更多相关文章
- IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API
IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习之保护API. 使用IdentityServer4 来实现使用客户端凭据保护ASP.N ...
- Hadoop学习笔记—18.Sqoop框架学习
一.Sqoop基础:连接关系型数据库与Hadoop的桥梁 1.1 Sqoop的基本概念 Hadoop正成为企业用于大数据分析的最热门选择,但想将你的数据移植过去并不容易.Apache Sqoop正在加 ...
- Spring框架学习一
Spring框架学习,转自http://blog.csdn.net/lishuangzhe7047/article/details/20740209 Spring框架学习(一) 1.什么是Spring ...
- EF框架学习手记
转载: [ASP.NET MVC]: - EF框架学习手记 1.EF(Entity Framework)实体框架EF是ADO.NET中的一组支持开发面向数据的软件应用程序的技术,是微软的一个ORM框架 ...
- web框架学习列表
转载自鲁塔弗的博客,原文网址:http://lutaf.com/148.htm web framework层出不穷,特别是ruby/python,各有10+个,php/java也是一大堆 根据我自己的 ...
- 2013 最新的 play web framework 版本 1.2.3 框架学习文档整理
Play framework框架学习文档 Play framework框架学习文档 1 一.什么是Playframework 3 二.playframework框架的优点 4 三.Play Frame ...
- SSH 框架学习之初识Java中的Action、Dao、Service、Model-收藏
SSH 框架学习之初识Java中的Action.Dao.Service.Model-----------------------------学到就要查,自己动手动脑!!! 基础知识目前不够,有感性 ...
- 各种demo——CI框架学习
各种demo——CI框架学习 寒假学习一下CI框架,请各位多多指教! 一.CI的HelloWorld! 注意:CI禁止直接通过文件目录来访问控制器. ./application/controlle ...
- phalcon(费尔康)框架学习笔记
phalcon(费尔康)框架学习笔记 http://www.qixing318.com/article/phalcon-framework-to-study-notes.html 目录结构 pha ...
- Yii框架学习 新手教程(一)
本人小菜鸟一仅仅,为了自我学习和交流PHP(jquery,linux,lamp,shell,javascript,server)等一系列的知识,小菜鸟创建了一个群.希望光临本博客的人能够进来交流.寻求 ...
随机推荐
- 报错:tar: This does not look like a tar archive
一.现象 解压时报错: 二.解决办法 gzip -d xxxx.tar.gz (对于.tar.gz文件的处理方式) tar -xf xxxx.tar (对于.tar文件处理方式) 三.查看
- 向日葵RCE复现
CNVD-2022-10270/CNVD-2022-03672 向日葵RCE复现 前言 向日葵是一款免费的集远程控制电脑手机.远程桌面连接.远程开机.远程管理.支持内网穿透的一体化远程控制管理工具软件 ...
- VMware vSphere Client(4.1/5.0/5.1/5.5/6.0) 客户端下载地址
前言 VMware作为商业虚拟化方案的佼佼者不知不觉中已经成长为一颗苍天大树,面对OpenStack和Docker的夹击希望VMware可以继续勇往直前,从vSphere 6.5开始终于彻底告别Cli ...
- linux运维之道学习笔记
linux常用命令 1.find命令 find / "*.log" 查找/目录下.log结尾的档案 find / -mtime -3 查找/目录下三天内被修改的档案 find / ...
- 前后端API交互数据加密——AES与RSA混合加密完整实例(转载)
前言 前段时间看到一篇文章讲如何保证API调用时数据的安全性(传送门:https://blog.csdn.net/ityouknow/article/details/80603617),文中讲到利用R ...
- kubectl的vistor模式
package main import ( "encoding/json" "encoding/xml" "log" ) type Visi ...
- React中store、action和reducer之间的关系
redux的三剑客store ----->物流仓库中心store,把它想象成一个物流仓库中心,数据(state)就是一个个包裹 action ---->包裹的包装 store.dispat ...
- PHP统计在线用户数量
一段经典的php统计在线用户数量的代码,一起学习分享. <?php /** * Created by PhpStorm. * User: jifei * Date: 15/11/24 * ...
- 397. 整数替换 (Medium
问题描述 397. 整数替换 (Medium) 给定一个正整数 n ,你可以做如下操作: 如果 n 是偶数,则用 n / 2 替换 n. 如果 n 是奇数,则可以用 n + 1 或 n - 1 替换 ...
- 爬取白鲸nft排名前25项目,持有nft大户地址数据。
https://moby.gg/rankings?tab=Market SELECT address '钱包地址', COUNT (1) '持有nft项目数', SUM (balance) '持有nf ...