로메오의 블로그

[VUE + TYPESCRIPT] proxy server 구현 본문

Frontend/Vue

[VUE + TYPESCRIPT] proxy server 구현

romeoh 2022. 3. 24. 14:15
반응형

VUE.JS 목록

 

vue.config.js

module.exports = {
  transpileDependencies: ['vuetify'],
  devServer: {
    proxy: {
      '/assistant': {
        target: process.env.VUE_APP_API_PUBLIC_URL,
        changeOrigin: true
      }
    }
  }
}

 

.env.development

VUE_APP_DEV=_DEVELOPMENT

VUE_APP_API_PUBLIC_URL='http://localhost:8091'
VUE_APP_API_PATH='/api/v1/'

 

restApi.ts

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

export enum ServiceUrl {
  BASE = process.env.VUE_APP_API_PUBLIC_URL
}

export default abstract class HttpClient {
  public apiUrl?: string;
  protected readonly instance: AxiosInstance;

  public constructor (
    serviceUrl?: ServiceUrl,
    apiUrl?: string
  ) {
    this.apiUrl = apiUrl
    this.instance = axios.create({
      baseURL: process.env.VUE_APP_API_PATH,
      headers: {
        'Cache-Control': 'no-cache',
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json; charset = utf-8'
      }
    })
    this._requestInterceptor()
    this._responseInterceptor()
  }

  /**
   * 인증처리
   */
  public setAxiosAuth = () => {
    // console.log('setAxiosAuth')
  }

  /**
   * 요청 Interceptor
   */
  private _requestInterceptor = () => {
    this.instance.interceptors.request.use(this._handleRequest)
  };

  private _handleRequest = (req: any) => {
    // loading 추가
    return req
  };

  /**
   * 응답 Interceptor
   */
  private _responseInterceptor = () => {
    this.instance.interceptors.response.use(
      this._handleResponse,
      this._handleError
    )
  };

  private _handleResponse = (res: AxiosResponse) => {
    // loading 제거
    return res.data
  };

  /**
   * 오류 처리
   */
  protected _handleError = (error: any) => {
    console.error(error)
  }
}

/**
 * RestApi 객체
 */
export class RestApi<T> extends HttpClient {
  public apiUrl: string;
  private _type!: { new(): T}

  public constructor (
    apiUrl: string,
    _type: { new(): T}
  ) {
    super(undefined, apiUrl)
    this.apiUrl = apiUrl
    this._type = _type
  }

  /**
   * Get 조회
   */
  public get = async () => {
    await this.setAxiosAuth()
    const res: any = await this.instance.get<T>(`${this.apiUrl}`)
    return this.castType(res)
  }

  /**
   * Post 전송
   */
  public post = async (item: any) => {
    await this.setAxiosAuth()
    const res: any = await this.instance.post<T>(`${this.apiUrl}`, item)
    return this.castType(res)
  }

  castType = (item: any) => Object.assign(new this._type(), item);
}

 

사용하기

export class Dialogue {
  date?: string;
  number?: string;
}

export default class TestView extends Vue {
  /**
   * RestApi 정의
   */
  testApi = new RestApi('/request/path', Dialogue)

  async postApi () {
    const data = {
      date: '20201221',
      number: '00000002'
    }
    const res: Dialogue = await this.testApi.post(data)
    console.log(res)
  }

  async getApi () {
    const res = await this.testApi.get()
    console.log(res)
  }
}

 

 

 

VUE.JS 목록

반응형
Comments