首页 > 解决方案 > Typescript 将 OOP 代码替换为功能代码

问题描述

我有这个类型的文件,其中包含用于使用 axios 和 typescript 调用 https 方法的类

治疗Apits

import HttpApiService from "./HttpApiService";
import { IContact } from "../models/contact";


const API_BASE = `${process.env.REACT_APP_API_URI}`;

const CONTACT_ENDPOINT = `${API_BASE}/contacts`;


export class MyTreatmentApi extends HttpApiService {
  constructor() {
    super(`${API_BASE}`);
  }

  createContact = (data: IContact) => {
    return super.create(`${CONTACT_ENDPOINT}`, data);
  };

}

export const MyTreatmentService = new MyTreatmentApi ();

这从HttpService扩展而来

该文件实现所有 Http 操作;从创建 axios 实例,然后进行 http 调用并处理响应

import axios, { AxiosInstance, AxiosPromise, AxiosResponse } from 'axios';

export enum EnumContentType {
  JSON = "application/json",
  XML = "application/xml",
  FORM = "application/x-www-form-urlencoded",
}

class HttpApiService {
  private _axiosInstance: AxiosInstance | undefined;
  private _baseURL: string;
  private _token: string | null;

  constructor(baseURL: string) {
    this._baseURL = baseURL;
    this._token = null;

    this.createAxiosInstance();
  }

  private defaultOptions = (): any => {
    // Set the AUTH token for any request

    const authHttpHeader = "Bearer token" // Token goes here
    this._token = authHttpHeader;

    const options = {
      baseURL: this._baseURL,
      // withCredentials: true, // Window Authentification
      headers: {
        'Accept': 'application/json',
        // 'Authorization': `${authHttpHeader}` // OAuth Authetification
      }
    };
    return options;
  };

  /**
   * Create instance
   */
  private createAxiosInstance() {
    this._axiosInstance = axios.create(this.defaultOptions());

    // this.checkAutorization()

    // Add a request interceptor
    this._axiosInstance.interceptors.request.use(
      config => config,
      error => {
        return Promise.reject(error);
      }
    );

    // Add a response interceptor
    this._axiosInstance.interceptors.response.use(
      this.handleSuccess,
      this.handleError
    );
  }

  protected getToken() {
    return this._token;
  }


  protected create(endpoint: string, data: {}, conf = {}): AxiosPromise {
    return this.post(endpoint, data, conf)
  }

  protected post(endpoint: string, data: {}, conf = {}): AxiosPromise {
    return new Promise((resolve, reject) => {
      this._axiosInstance!
        .post(`${endpoint}`, data, conf)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  protected delete(endpoint: string, id: any, conf = {}): AxiosPromise {
    return new Promise((resolve, reject) => {
      this._axiosInstance!
        .delete(`${endpoint}/${id}`, conf)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  handleSuccess(response: AxiosResponse) {
    // console.log('handleSuccess' + JSON.stringify(response))
    return response;
  }

  handleError = (err: any) => {
    console.log(`HttpService::Error : ${err}`)
    if (!err.response) {
        console.log(`Network error: ${err}`);
    } else {
      if (err.response !== undefined) {
        const { status } = err.response;
        if (status === 401 || status === 500) {
          console.log(`HttpService::Error(401 or 500) : ${err.response.data.Message}`)
        }
      }
    }
    return Promise.reject(err);
  };

}

export default HttpApiService;

我的任务是将其转换为功能代码,而不使用打字稿类

比直接传递给这样的东西:

 export const MyTreatmentService = (ep: Endpoint) => ({
   create: async (
     payload: any // TODO
   ): Promise<any> => {

   },
 });

建议??

标签: typescriptecmascript-6axios

解决方案


推荐阅读