Skip to content

Commit

Permalink
Refactor api entrypoint
Browse files Browse the repository at this point in the history
  • Loading branch information
EduardoPicolo committed Aug 28, 2022
1 parent e615f29 commit fe66d21
Show file tree
Hide file tree
Showing 20 changed files with 231 additions and 245 deletions.
9 changes: 2 additions & 7 deletions src/components/Footnote/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
Tooltip,
useDisclosure
} from "@chakra-ui/react"
import axios from "axios"

import { ServicesStatus } from "@components/Footnote/ServicesStatus"
import { useRequest } from "@hooks/useRequest"
Expand All @@ -17,21 +16,17 @@ type Releases = {
name: string
}

const githubApi = axios.create({
baseURL: "https://api.github.com"
})

export const Footnote = () => {
const { isOpen, onOpen, onClose } = useDisclosure()

const { data } = useRequest<Releases[]>(
process.env.NODE_ENV !== "development"
? {
baseURL: "https://api.github.com",
url: "/repos/fga-eps-mds/2022-1-schedula-front/releases",
method: "GET"
}
: null,
githubApi
: null
)

const version = useMemo(
Expand Down
35 changes: 10 additions & 25 deletions src/components/Footnote/useServicesData.tsx
Original file line number Diff line number Diff line change
@@ -1,79 +1,64 @@
import { useMemo } from "react"
import axios from "axios"

import { useRequest } from "@hooks/useRequest"
import { detalhadorApi, localidadesApi, usuariosApi } from "@services/api"
import { serviceStatus } from "@services/request"
import { serviceStatus } from "@services"

type Releases = {
tag_name: string
name: string
}

const githubApi = axios.create({
baseURL: "https://api.github.com"
})

export const useServicesData = () => {
const {
data: chamadosStatus,
isLoading: isLoadingChamadosStatus,
error: errorChamados
} = useRequest<ServiceStatus>(
serviceStatus(detalhadorApi.defaults.baseURL as string),
detalhadorApi
)
} = useRequest<ServiceStatus>(serviceStatus("chamados"))

const {
data: usuariosStatus,
isLoading: isLoadingUsuariosStatus,
error: errorUsuarios
} = useRequest<ServiceStatus>(
serviceStatus(usuariosApi.defaults.baseURL as string),
usuariosApi
)
} = useRequest<ServiceStatus>(serviceStatus("usuarios"))

const {
data: localidadesStatus,
isLoading: isLoadingLocalidadesStatus,
error: errorLocalidades
} = useRequest<ServiceStatus>(
serviceStatus(localidadesApi.defaults.baseURL as string),
localidadesApi
)
} = useRequest<ServiceStatus>(serviceStatus("localidades"))

const { data: usuariosVersion, isLoading: isLoadingUserVersion } = useRequest<
Releases[]
>(
process.env.NODE_ENV !== "development"
? {
baseURL: "https://api.github.com",
url: "/repos/fga-eps-mds/2022-1-schedula-gestor-de-usuarios/releases",
method: "GET"
}
: null,
githubApi
: null
)

const { data: chamadosVersion, isLoading: isLoadingChamadosVersion } =
useRequest<Releases[]>(
process.env.NODE_ENV !== "development"
? {
baseURL: "https://api.github.com",
url: "/repos/fga-eps-mds/2022-1-schedula-detalhador-de-chamados/releases",
method: "GET"
}
: null,
githubApi
: null
)

const { data: localidadesVersion, isLoading: isLoadingLocalidadesVersion } =
useRequest<Releases[]>(
process.env.NODE_ENV !== "development"
? {
baseURL: "https://api.github.com",
url: "/repos/fga-eps-mds/2022-1-schedula-gerenciador-de-localidades/releases",
method: "GET"
}
: null,
githubApi
: null
)

const apiVersions = useMemo(
Expand Down
26 changes: 10 additions & 16 deletions src/hooks/useRequest.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import {
AxiosError,
AxiosInstance,
AxiosRequestConfig,
AxiosResponse
} from "axios"
import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios"
import get from "lodash/get"
import useSWR, { SWRConfiguration, SWRResponse } from "swr"

export type GetRequest = AxiosRequestConfig | null
import { api } from "@services/api"

export type ApiData<Data> =
| { data: Data; error: null | string; message: string }
| undefined
export type GetRequest = AxiosRequestConfig | null

interface Return<Data, Error>
extends Pick<
Expand All @@ -32,28 +25,29 @@ export interface Config<Data = unknown, Error = unknown>
dataPath?: keyof Data | string | string[]
}

export function useRequest<Data = unknown, Error = unknown>(
export function useRequest<T, Data = ApiResponse<T>, Error = unknown>(
request: GetRequest,
fetcher: AxiosInstance,
{ fallbackData, dataPath: path, ...config }: Config<ApiData<Data>, Error> = {}
): Return<ApiData<Data>, Error> {
{ fallbackData, dataPath: path, ...config }: Config<Data, Error> = {}
): Return<Data, Error> {
const {
data: response,
error,
isValidating,
mutate
} = useSWR<AxiosResponse<ApiData<Data>>, AxiosError<Error>>(
} = useSWR(
request && JSON.stringify(request),
/**
* NOTE: Typescript thinks `request` can be `null` here, but the fetcher
* function is actually only called by `useSWR` when it isn't.
*/
() => fetcher.request<ApiData<Data>>(request!),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- see above
() => api.request<Data>(request!),
{
...config,
fallbackData: fallbackData && {
status: 200,
statusText: "InitialData",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- see above
config: request!,
headers: {},
data: fallbackData
Expand Down
23 changes: 10 additions & 13 deletions src/pages/categorias/[id]/problemas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ import { Item } from "@components/ListItem"
import { Modal } from "@components/Modal/Modal"
import { PageHeader } from "@components/PageHeader"
import { RefreshButton } from "@components/RefreshButton"
import { ApiData, useRequest } from "@hooks/useRequest"
import { detalhadorApi } from "@services/api"
import { getProblemCategory } from "@services/DetalhadorChamados"
import { useRequest } from "@hooks/useRequest"
import { getProblemCategory } from "@services/Chamados"
import {
createProblemType,
deleteProblemType,
Expand All @@ -37,24 +36,23 @@ const ListaProblemas = () => {

const { data: categoria, isLoading: isLoadingCategory } =
useRequest<CategoriaProblema>(
category_id ? getProblemCategory(category_id) : null,
detalhadorApi
category_id ? getProblemCategory(category_id) : null
)

const {
data: problemas,
isLoading,
isValidating,
mutate
} = useRequest<TipoProblema[]>(getProblemTypes(category_id), detalhadorApi)
} = useRequest<TipoProblema[]>(getProblemTypes(category_id))

const { isOpen, onOpen, onClose } = useDisclosure()

const [problemToEdit, setProblemToEdit] = useState<TipoProblema>()

const handleDelete = useCallback(
async ({ id }: TipoProblema) => {
const response = await request(deleteProblemType(id), detalhadorApi)
const response = await request(deleteProblemType(id))

if (response.type === "success") {
toast.success("Tipo de problema deletado com sucesso!")
Expand All @@ -70,7 +68,7 @@ const ListaProblemas = () => {
message: "",
data: newProblemas || ([] as TipoProblema[])
}
} as AxiosResponse<ApiData<TipoProblema[]>>,
} as AxiosResponse<ApiResponse<TipoProblema[]>>,
{ revalidate: false }
)

Expand All @@ -94,11 +92,10 @@ const ListaProblemas = () => {
async (data: ProblemTypePayload) => {
console.log("DATA: ", data)

const response = await request<{ data: TipoProblema }>(
const response = await request<TipoProblema>(
problemToEdit
? updateProblemType(problemToEdit.id)(data)
: createProblemType({ ...data, category_id }),
detalhadorApi
: createProblemType({ ...data, category_id })
)

if (response.type === "success") {
Expand All @@ -112,7 +109,7 @@ const ListaProblemas = () => {
? problemas?.data.map((problema) =>
problema.id === problemToEdit?.id ? response.value.data : problema
)
: [...(problemas?.data || []), response.value.data]
: [...(problemas?.data || []), response.value?.data]

mutate(
{
Expand All @@ -121,7 +118,7 @@ const ListaProblemas = () => {
message: "",
data: newProblemas
}
} as AxiosResponse<ApiData<TipoProblema[]>>,
} as AxiosResponse<ApiResponse<TipoProblema[]>>,
{ revalidate: false }
)

Expand Down
22 changes: 10 additions & 12 deletions src/pages/categorias/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,13 @@ import { Item } from "@components/ListItem"
import { Modal } from "@components/Modal/Modal"
import { PageHeader } from "@components/PageHeader"
import { RefreshButton } from "@components/RefreshButton"
import { ApiData, useRequest } from "@hooks/useRequest"
import { detalhadorApi } from "@services/api"
import { useRequest } from "@hooks/useRequest"
import {
createProblemCategory,
deleteProblemCategory,
getProblemCategories,
updateProblemCategory
} from "@services/DetalhadorChamados"
} from "@services/Chamados"
import { request } from "@services/request"

const ListaCategoria = () => {
Expand All @@ -31,15 +30,15 @@ const ListaCategoria = () => {
isLoading,
isValidating,
mutate
} = useRequest<CategoriaProblema[]>(getProblemCategories(), detalhadorApi, {})
} = useRequest<CategoriaProblema[]>(getProblemCategories)

const { isOpen, onOpen, onClose } = useDisclosure()

const [categoriaToEdit, setCategoria] = useState<CategoriaProblema>()

const handleDelete = useCallback(
async ({ id }: CategoriaProblema) => {
const response = await request(deleteProblemCategory(id), detalhadorApi)
const response = await request(deleteProblemCategory(id))

if (response.type === "success") {
toast.success("Categoria deletada com sucesso!")
Expand All @@ -55,7 +54,7 @@ const ListaCategoria = () => {
message: "",
data: newCategorias || ([] as CategoriaProblema[])
}
} as AxiosResponse<ApiData<CategoriaProblema[]>>,
} as AxiosResponse<ApiResponse<CategoriaProblema[]>>,
{ revalidate: false }
)

Expand Down Expand Up @@ -86,11 +85,10 @@ const ListaCategoria = () => {
async (data: CategoriaProblemaPayload) => {
console.log("DATA: ", data)

const response = await request<{ data: CategoriaProblema }>(
const response = await request<CategoriaProblema>(
categoriaToEdit
? updateProblemCategory(categoriaToEdit.id)(data)
: createProblemCategory(data),
detalhadorApi
: createProblemCategory(data)
)

if (response.type === "success") {
Expand All @@ -101,10 +99,10 @@ const ListaCategoria = () => {
const newCategorias = categoriaToEdit
? categorias?.data.map((categoria) =>
categoria.id === categoriaToEdit?.id
? response.value.data
? response.value?.data
: categoria
)
: [...(categorias?.data || []), response.value.data]
: [...(categorias?.data || []), response.value?.data]

mutate(
{
Expand All @@ -113,7 +111,7 @@ const ListaCategoria = () => {
message: "",
data: newCategorias
}
} as AxiosResponse<ApiData<CategoriaProblema[]>>,
} as AxiosResponse<ApiResponse<CategoriaProblema[]>>,
{ revalidate: false }
)

Expand Down
14 changes: 6 additions & 8 deletions src/pages/cidades/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ import { Item } from "@components/ListItem"
import { Modal } from "@components/Modal/Modal"
import { PageHeader } from "@components/PageHeader"
import { RefreshButton } from "@components/RefreshButton"
import { ApiData, useRequest } from "@hooks/useRequest"
import { localidadesApi } from "@services/api"
import { useRequest } from "@hooks/useRequest"
import {
createCity,
deleteCity,
Expand All @@ -31,11 +30,11 @@ const ListaCidades = () => {
isLoading,
isValidating,
mutate
} = useRequest<City[]>(getCities(), localidadesApi, {})
} = useRequest<City[]>(getCities)

const handleDelete = useCallback(
async ({ id }: City) => {
const response = await request(deleteCity(id), localidadesApi)
const response = await request(deleteCity(id))

if (response.type === "success") {
toast.success("Cidade deletada com sucesso!")
Expand All @@ -49,7 +48,7 @@ const ListaCidades = () => {
message: "",
data: newCidades || ([] as City[])
}
} as AxiosResponse<ApiData<City[]>>,
} as AxiosResponse<ApiResponse<City[]>>,
{ revalidate: false }
)

Expand Down Expand Up @@ -79,8 +78,7 @@ const ListaCidades = () => {
console.log("DATA: ", data)

const response = await request<{ data: City }>(
cidadesToEdit ? updateCity(cidadesToEdit.id)(data) : createCity(data),
localidadesApi
cidadesToEdit ? updateCity(cidadesToEdit.id)(data) : createCity(data)
)

if (response.type === "success") {
Expand All @@ -101,7 +99,7 @@ const ListaCidades = () => {
message: "",
data: newCidades
}
} as AxiosResponse<ApiData<CategoriaProblema[]>>,
} as AxiosResponse<ApiResponse<CategoriaProblema[]>>,
{ revalidate: false }
)

Expand Down
Loading

0 comments on commit fe66d21

Please sign in to comment.