Skip to content
This repository has been archived by the owner on May 7, 2022. It is now read-only.

Commit

Permalink
fix(✏️): do not throw inside apisauce transforms
Browse files Browse the repository at this point in the history
  • Loading branch information
osamaqarem committed Jun 18, 2020
1 parent 43c75ea commit 3f285ee
Showing 1 changed file with 42 additions and 18 deletions.
60 changes: 42 additions & 18 deletions template/src/services/network/github/githubService.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,67 @@
import { create } from 'apisauce'
import { create, ApisauceInstance, ApiResponse } from 'apisauce'
import BuildConfig from "react-native-config"
import { RepoReadme } from './models'
import HttpException from '../../../common/exceptions/HttpException'

// API client instance
const client = create({
// Apisauce instance
const instance = create({
baseURL: BuildConfig.GITHUB_API_BASE_URL,
timeout: 30 * 1000,
headers: {
accept: 'application/vnd.github.v3+json'
'Accept': 'application/vnd.github.v3+json'
}
})

// Logging
__DEV__ && client.addMonitor(res => console.tron(res))
type Args = Parameters<ApisauceInstance['get']>

// By default, apisauce does not throw on failure.
// For SWR to work, the fetcher needs to throw on failure.
client.addResponseTransform(response => {
if (!response.ok) {
const error = new HttpException(response.status || 'unknown', response.problem, response.config?.url || 'unknown', response)
/**
* Wrapper around API instance.
* By default, apisauce does not throw on failure.
* For SWR to work, the fetcher needs to throw on failure.
*/
const client = {
/**
* We're forwarding the types and arguments and then throwing on error.
*/
...instance,
get: async <T>(...args: Args) => {
const res = await instance.get(...args) as ApiResponse<T>
return util.throwOnError<T>(res)
}
// override more methods as needed
}

__DEV__ && console.tron(error)
// Logging
__DEV__ && client.addMonitor(res => console.log(res))

throw error
}
})

/**
* API implementation
*/

// API Paths
const paths = {
getRepoReadme: () => "/repos/osamaq/react-native-template/readme",
}

// API implementation
const api = {
getRepoReadme: () => client.get<RepoReadme>(paths.getRepoReadme()),
}

// API utilities
const util = {
throwOnError: <T>(response: ApiResponse<T>) => {
if (!response.ok) {
const error = new HttpException(response.status || 'unknown', response.problem, response.config?.url || 'unknown', response)

__DEV__ && console.log(error)

throw error
} else {
// all good!
return response.data!
}
}
}

export const githubService = {
api,
paths,
Expand Down

0 comments on commit 3f285ee

Please sign in to comment.