import axios from 'axios'
import { API, ALLOWED_TYPES } from './constants'

const handleError = err => {
  throw new Error(err)
}

const validateHttpStatus = res => {
  if (res.status !== 200) handleError('Erro ao se conectar com o serviço da SPTrans.')
  return res
}

const handleResponse = res => res.data

const validateParams = params => {
  if (!params) {
    handleError('O método "find" deve receber parâmetros.')
  }

  if (!ALLOWED_TYPES.includes(params.type)) {
    handleError('Parâmetro "type" não permitido.')
  }

  if (params.type === 'linhas' || params.type === 'paradas') {
    if (!params.term) handleError('O parâmetro "term" é obrigatório para este "type".')
  }

  return params
}

const fetchData = params => {
  const { auth, type, term } = params

  const config = {
    method: 'get',
    url: API.endpoint + API[type].route,
    params: {
      [API[type].param]: term
    },
    headers: {
      Cookie: auth
    }
  }

  return axios(config)
    .then(validateHttpStatus)
    .then(handleResponse)
}

export default params =>
  Promise.resolve(params)
    .then(validateParams)
    .then(fetchData)

@@ -309,24 +309,19 @@
 %0A%0Aconst 
-validate
+has
 Params =
@@ -334,31 +334,20 @@
 s =%3E
- %7B
 %0A  
-if (!
 params
-) %7B%0A   
+ %7C%7C
  han
@@ -403,20 +403,46 @@
 .')%0A
-  %7D%0A%0A  if (!
+%0Aconst hasAllowedType = params =%3E %7B%0A  
 ALLO
@@ -472,23 +472,19 @@
 ms.type)
-) %7B%0A   
+ %7C%7C
  handleE
@@ -521,25 +521,99 @@
 mitido.')%0A  
-%7D
+return params%0A%7D%0A%0Aconst hasTerm = params =%3E %7B%0A  const updatedParams = params
 %0A%0A  if (para
@@ -753,16 +753,54 @@
 ype%22.')%0A
+    updatedParams.value = params.term%0A
   %7D%0A%0A  r
@@ -797,33 +797,40 @@
 m%0A  %7D%0A%0A  return 
-p
+updatedP
 arams%0A%7D%0A%0Aconst f
@@ -874,20 +874,21 @@
 , type, 
-term
+value
  %7D = par
@@ -1010,20 +1010,21 @@
 param%5D: 
-term
+value
 %0A    %7D,%0A
@@ -1215,22 +1215,62 @@
 hen(
-validateParams
+hasParams)%0A    .then(hasAllowedType)%0A    .then(hasTerm
 )%0A  

Improve find method code for better readable