[컴][js] plain js 로 만든 간단한 rest api call functions

간단 / 바닐라 / vanila js / javascript fetch / my own / plain js request

plain js 로 만든 간단한 rest api call functions

  • timeout 부분만 추가됐다.
  • GET, POST 가 일관되게 data 를 사용하도록 했다.

사용법:

try{
    const res = await api.req.get({
      url: api.url.logout,        
    })
    window.location.href = "/"
} catch(e){
    console.error(e)
} finally {
    // this.isLoading = false
}

구현:

const req = {}

req._base = async function ({ url, method, headers, data, timeout }) {
  // for timeout
  const controller = new AbortController()
  const timeoutId = setTimeout(() => controller.abort(), timeout || 15000)

  // param
  const fetchParam = {
    method,
    headers,
    signal: controller.signal,
  }

  const { qstring, body } = _handleData(method, data)

  let realUrl = url
  if (qstring) {
    realUrl = `${url}?${qstring}`
  }

  if (body) {
    fetchParam.body = JSON.stringify(data)
  }

  try {
    /**
     * @return 
     *   {
     *     "content": [
     *       {
     *         ...
     *       },
     *       ...
     *     ]
     *     "message": "ok",
     *     "code": 0
     *   }
     */
    const resp = await fetch(realUrl, fetchParam)
    const respJson = await resp.json()
    if (!resp.ok) {
      // HTTP-status is 200-299
      const errorText = {
        status: resp.status,
        statusText: resp.statusText,
        respJson
      }
      throw new Error(`${JSON.stringify(errorText)}`)
    }

    return respJson

  } catch (err) {
    console.error('fetch error', err)
    throw err
  }
}

/**
 * @param {string} url @see the apis.url
 * @param {object} param 
 * @param {number} timeout in milliseconds
 */
req.get = async function ({ url, data, timeout }) {

  const respJson = await req._base({
    url,
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
    data,
    timeout
  })
  return respJson

}

req.post = async function ({ url, data, timeout }) {

  const respJson = await req._base({
    url: url,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data,
    timeout
  })

  return respJson

}

req.patch = async function ({ url, data, timeout }) {

  const respJson = await req._base({
    url: url,
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
    },
    data,
    timeout
  })

  return respJson

}

req.delete = async function ({ url, data, timeout }) {

  const respJson = await req._base({
    url: url,
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json',
    },
    data,
    timeout
  })

  return respJson

}

function _handleData(method, data) {
  if (!data) {
    return {
      qstring: null,
      body: null,
    }
  }

  if (method.toUpperCase() == "GET") {
    const qstring = new URLSearchParams(data)
    return {
      qstring,
      body: null,
    }
  }
  return {
    qstring: null,
    body: JSON.stringify(data)
  }
}

module.exports = {
  url,
  pageUrl,
  req
}

댓글 없음:

댓글 쓰기