Skip to content

Instantly share code, notes, and snippets.

@robinheinze
Last active April 7, 2021 21:15
Show Gist options
  • Save robinheinze/1e9aabdc33b1079ed75d61d1dc32194d to your computer and use it in GitHub Desktop.
Save robinheinze/1e9aabdc33b1079ed75d61d1dc32194d to your computer and use it in GitHub Desktop.
API (Ice and Fire)
export const DEFAULT_API_CONFIG: ApiConfig = {
url: env.API || "https://opentdb.com/api.php",
timeout: 10000,
}
import { ApisauceInstance, create, ApiResponse } from "apisauce"
import { getGeneralApiProblem } from "./api-problem"
import { ApiConfig, DEFAULT_API_CONFIG } from "./api-config"
import * as Types from "./api.types"
import { QuestionSnapshot } from "../../models/question/question"
import * as uuid from "react-native-uuid"
const API_PAGE_SIZE = 50
const convertQuestion = (raw: any): QuestionSnapshot => {
const id = uuid.v1().toString()
return {
id: id,
category: raw.category,
type: raw.type,
difficulty: raw.difficulty,
question: raw.question,
correctAnswer: raw.correct_answer,
incorrectAnswers: raw.incorrect_answers,
}
}
export class Api {
...
/**
* Gets a list of trivia questions.
*/
async getQuestions(): Promise<Types.GetQuestionsResult> {
// make the api call
const response: ApiResponse<any> = await this.apisauce.get("", { amount: API_PAGE_SIZE })
// the typical ways to die when calling an api
if (!response.ok) {
const problem = getGeneralApiProblem(response)
if (problem) return problem
}
// transform the data into the format we are expecting
try {
const rawQuestions = response.data.results
const convertedQuestions: QuestionSnapshot[] = rawQuestions.map(convertQuestion)
return { kind: "ok", questions: convertedQuestions }
} catch (e) {
__DEV__ && console.tron.log(e.message)
return { kind: "bad-data" }
}
}
}
import { QuestionSnapshot } from "../../models/question"
export type GetQuestionsResult = { kind: "ok"; questions: QuestionSnapshot[] } | GeneralApiProblem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment