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)等一系列的知识,小菜鸟创建了一个群.希望光临本博客的人能够进来交流.寻求 ...
随机推荐
- comment out one line in the file with sed
sed -i "/test2/s/^/#/" test.log https://jaminzhang.github.io/linux/sed-command-usage-summa ...
- macOS Big Sur 设置JAVA_HOME
默认JAVA_HOME指向的是: /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home 这个不是我们自己安装的jdk,另外本 ...
- Python——02.变量及标识符
变量概念: -- 字面量:与字面上显示值一致的量称作字面量,在程序中可直接使用字面量:abc,123, 我是XX,等等 -- 变量:变量可通过赋值保存字面量,变量是可变的,跟随赋值的字面量不同而变化 ...
- 正则表达式re.compile()的使用
re 模块提供了不少有用的函数,用以匹配字符串,比如: compile 函数match 函数search 函数findall 函数finditer 函数split 函数sub 函数subn 函数re ...
- Java 向上转型
向上转型: 对象的向上转型,其实就是多态写法: 父类名称 对象名 = new 子类名称(); 注意:向上转型一定是安全的,从小范围转向大范围.(从小范围的猫,向上转化为更大范围的动物)
- Xcode基础文件概念
Xcode基础概念 Schema.Target.Project 和 Workspace 是组成一个 Xcode 工程最核心的单元,也是我们首先需要理解的部分. Target Target 是我们工程中 ...
- vs2019 文件读取操作
1 #include<stdio.h> 2 #define INF 10000000 3 int main() 4 { 5 FILE* fin , * fout ; 6 errno_t a ...
- C语言学习--练习--合并两个字符串
将两个字符串合并追加在一起, 类似于python的str1+str2 #include<stdio.h> #include<string.h> #include<stdl ...
- S-HR查询用户组织范围
SELECT org.FNumber FNumber,org.FName_L2 orgName FROM T_PM_OrgRange orgRange LEFT JOIN T_ORG_admin or ...
- git rebase之abort,continue,skip
git rebase --abort 会放弃合并,回到rebase操作之前的状态,之前的提交的不会丢 git rebase --skip 会将引起冲突的commit丢弃掉 git rebase --c ...