装饰器编写get请求

2022-10-23  本文已影响0人  Nick_4438

说明

本文演示使用装饰器编写get请求的方法

准备工作

mkdir demo
touch index.ts
npm i axios -S

编写代码

import axios from "axios";


const Get = (url: string) => {
    return (target: any, key: any, descriptor: PropertyDescriptor) => {
        const fnc = descriptor.value
        axios.get(url).then(res => {
            fnc(res, {
                status: 200,
                success: true
            })
        }).catch(e => {
            fnc(e, { status: 500, success: false })
        })
    }
}

class Controller {
    constructor() {
    }
    @Get('https://api.apiopen.top/api/getHaoKanVideo?page=0&size=10')
    getList(res: any, status: any) {
        console.log(res.data.result.list,status)
    }

}

测试执行ts-node .\index.ts,返回数据如下

[
  {
    id: 9899,
    title: '劳斯莱斯当火车开,也只有大老板敢,观众笑炸了锅丨快乐营',
    userName: '高能综艺大赏',
    userPic: 'https://pic.rmb.bdstatic.com/bjh/user/f74bb94a2b77148b89cc805c5f2efbc5.jpeg?x-bce-process=image/resize,m_lfit,w_200,h_200&autime=34660',      
    coverUrl: 'https://f7.baidu.com/it/u=2083395567,3277230239&fm=222&app=108&f=JPEG@s_2,w_681,h_381,q_100',
    playUrl: 'http://vd4.bdstatic.com/mda-nbr7vzz3bt3qchw1/cae_h264_delogo/1645854226747166384/mda-nbr7vzz3bt3qchw1.mp4',
    duration: '03:37'
  },
    ......
         {
    id: 7514,
    title: '为什么都说女不养狗男不养猫?看狗干的好事,你就明白了',
    userName: '小奇大怪',
    userPic: 'https://pic.rmb.bdstatic.com/bjh/user/0056c3435244dd763cd6423f19fddff3.jpeg?x-bce-process=image/resize,m_lfit,w_200,h_200&autime=36154',      
    coverUrl: 'https://f7.baidu.com/it/u=3513587627,1137795773&fm=222&app=108&f=JPEG@s_2,w_681,h_381,q_100',
    playUrl: 'http://vd2.bdstatic.com/mda-nb789v9cijmrnq30/cae_h264_delogo/1644303665642707226/mda-nb789v9cijmrnq30.mp4',
    duration: '01:08'
  }
] { status: 200, success: true }
上一篇下一篇

猜你喜欢

热点阅读