Api.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // a library to wrap and simplify api calls
  2. import apisauce from '../Lib/apisauce'
  3. // our "constructor"
  4. const create = (baseURL = '') => {
  5. // ------
  6. // STEP 1
  7. // ------
  8. //
  9. // Create and configure an apisauce-based api object.
  10. //
  11. const api = apisauce.create({
  12. // base URL is read from the "constructor"
  13. baseURL,
  14. // here are some default headers
  15. headers: {
  16. 'Cache-Control': 'no-cache',
  17. 'Accept': 'application/json',
  18. 'Content-Type': 'application/json'
  19. },
  20. // 10 second timeout...
  21. timeout: 10000
  22. })
  23. // Force OpenWeather API Key on all requests
  24. // api.addRequestTransform((request) => {
  25. // request.params['APPID'] = '0e44183e8d1018fc92eb3307d885379c'
  26. // })
  27. // Wrap api's addMonitor to allow the calling code to attach
  28. // additional monitors in the future. But only in __DEV__ and only
  29. // if we've attached Reactotron to console (it isn't during unit tests).
  30. if (__DEV__ && console.tron) {
  31. console.tron.log('Hello, I\'m an example of how to log via Reactotron.')
  32. api.addMonitor(console.tron.apisauce)
  33. }
  34. // ------
  35. // STEP 2
  36. // ------
  37. //
  38. // Define some functions that call the api. The goal is to provide
  39. // a thin wrapper of the api layer providing nicer feeling functions
  40. // rather than "get", "post" and friends.
  41. //
  42. // I generally don't like wrapping the output at this level because
  43. // sometimes specific actions need to be take on `403` or `401`, etc.
  44. //
  45. // Since we can't hide from that, we embrace it by getting out of the
  46. // way at this level.
  47. //
  48. const register = (options) => api.post('/users', options)
  49. // ------
  50. // STEP 3
  51. // ------
  52. //
  53. // Return back a collection of functions that we would consider our
  54. // interface. Most of the time it'll be just the list of all the
  55. // methods in step 2.
  56. //
  57. // Notice we're not returning back the `api` created in step 1? That's
  58. // because it is scoped privately. This is one way to create truly
  59. // private scoped goodies in JavaScript.
  60. //
  61. return {
  62. // a list of the API functions from step 2
  63. register
  64. }
  65. }
  66. // let's return back our create method as the default.
  67. export default {
  68. create
  69. }