文章加密

;

2019年11月21日 星期四

async await

async function(){  // 如果沒有async,在function內什麼都沒寫的情況下console.log他會印出undefined。如果有async,console.log的話會是promise
    //....
   var s1 = await axios...
   console.log(s1) . // 可以直接在這裡取得api 的res,而會不是undefined, null之類的
}

但async await需要babel才可以在各大瀏覽器支持,babel解析出來其實就是promise.then,只是太多{}寫起來醜,所以加入async await

// utilities/api-handler.lib.ts
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { requestSuccess, requestFail, responseSuccess, responseFail } from './error-handler.lib';
import Vue from 'vue';

class HttpModel {
    constructor() {}
    /**
     * axios API handler
     * @author rourou
     * @description 一律透過此method呼叫api
     */
    async request<T>(cfg: AxiosRequestConfig, isLogin = false) {
        const host = window.location.hostname.split('.');
        cfg.baseURL = `${Vue.$clientSideProcess.env.VUE_APP_API_URL}.${host[1]}.${host[2]}.${host[3]}/api/${Vue.$clientSideProcess.env.VUE_APP_API_VERSION}/${Vue.$clientSideProcess.env.VUE_APP_CLIENT_ID}/`;

        // cfg.baseURL = `http://192.168.50.175/api/v1/222222`;
        if (process.env.NODE_ENV === 'development') {
            cfg.baseURL = `/backoffice/api/${Vue.$clientSideProcess.env.VUE_APP_API_VERSION}/${Vue.$clientSideProcess.env.VUE_APP_CLIENT_ID}/`;
        }
        if (isLogin) {
            cfg.headers = {
                'content-type': 'application/x-www-form-urlencoded',
            };
        } else {
            cfg.headers = {
                Authorization: `Bearer ${localStorage.getItem(window.location.hostname)}`,
                'content-type': 'application/x-www-form-urlencoded',
            };
        }
        const instance = axios.create();
        instance.interceptors.request.use(config => requestSuccess(config), err => requestFail(err));
        instance.interceptors.response.use(response => responseSuccess(response), error => responseFail(error));
        let result;
        try {
            result = await instance.request<T>(cfg);
            return Promise.resolve(result);
        } catch (throwError) {
            return Promise.reject(throwError);
        }
    }
}

const model = new HttpModel();

export default model;

// api/chart.ts
import Handler from '@/utilities/api-handler.lib';
import * as Model from '@/models/interfaces/chart';
import * as Qs from 'qs';

export default {
    /**
     * @description
     */
    async getTopup(payload: Model.IAPeriodOfTimeRequest): Promise<Model.ITopUpResponse> {
        const config = {
            url: `/report/topup/stats?${Qs.stringify(payload)}`,
            method: 'get',
        };
        const result = await Handler.request<Model.ITopUpResponse>(config);
        return <Model.ITopUpResponse>result.data;
    },
    async getFirstTopup(payload: Model.IAPeriodOfTimeRequest): Promise<Model.IFirstTopup> {
        const config = {
            url: `/report/topup/first-topup/stats?${Qs.stringify(payload)}`,
            method: 'get',
        };
        const result = await Handler.request<Model.IFirstTopup>(config);
        return <Model.IFirstTopup>result.data;
    },
    /**
     * @description
     */
    async getOnlineUsersNumber(): Promise<Model.IGetOnlineUsersNumber> {
        const config = {
            url: `/report/users/online`,
            method: 'get',
        };
        const result = await Handler.request<Model.IGetOnlineUsersNumber>(config);
        return <Model.IGetOnlineUsersNumber>result.data;
    },
    async getWithdrawal(payload: Model.IAPeriodOfTimeRequest): Promise<Model.IWithdrawalResponse> {
        const config = {
            url: `/report/withdrawal/stats?${Qs.stringify(payload)}`,
            method: 'get',
        };
        const result = await Handler.request<Model.IWithdrawalResponse>(config);
        return <Model.IWithdrawalResponse>result.data;
    },
    async getBetsSum(payload: Model.IGameBetSumRequest): Promise<Model.IGameBetSumResponse> {
        const config = {
            url: `/report/game-bets-sum?${Qs.stringify(payload)}`,
            method: 'get',
        };
        const result = await Handler.request<Model.IGameBetSumResponse>(config);
        return <Model.IGameBetSumResponse>result.data;
    },
};


沒有留言:

張貼留言