Guest User

Untitled

a guest
Mar 24th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. export const parseAPIResponse = response =>
  2. new Promise(resolve => resolve(response.text()))
  3. .catch(err =>
  4. // eslint-disable-next-line prefer-promise-reject-errors
  5. Promise.reject({
  6. type: 'NetworkError',
  7. status: response.status,
  8. message: err,
  9. }))
  10. .then((responseBody) => {
  11. // Attempt to parse JSON
  12. try {
  13. const parsedJSON = JSON.parse(responseBody);
  14. if (response.ok) return parsedJSON;
  15. if (response.status >= 500) {
  16. // eslint-disable-next-line prefer-promise-reject-errors
  17. return Promise.reject({
  18. type: 'ServerError',
  19. status: response.status,
  20. body: parsedJSON,
  21. });
  22. }
  23. if (response.status <= 501) {
  24. // eslint-disable-next-line prefer-promise-reject-errors
  25. return Promise.reject({
  26. type: 'ApplicationError',
  27. status: response.status,
  28. body: parsedJSON,
  29. });
  30. }
  31. } catch (e) {
  32. // We should never get these unless response is mangled
  33. // Or API is not properly implemented
  34. // eslint-disable-next-line prefer-promise-reject-errors
  35. return Promise.reject({
  36. type: 'InvalidJSON',
  37. status: response.status,
  38. body: responseBody,
  39. });
  40. }
  41. });
  42.  
  43.  
  44.  
  45. handleSubmit(e) {
  46. e.preventDefault()
  47.  
  48. const body = {
  49. email: this.state.email,
  50. }
  51.  
  52. let resStatus = 0
  53. fetch(Config.REST_API_URL + 'users/registration-request', {
  54. method: 'POST',
  55. headers: {
  56. Accept: 'application/json',
  57. 'Content-Type': 'application/json',
  58. },
  59. body: JSON.stringify(body),
  60. })
  61. .then(res => {
  62. resStatus = res.status
  63. return res.json()
  64. })
  65. .then(res => {
  66. switch (resStatus) {
  67. case 201:
  68. console.log('success')
  69. break
  70. case 400:
  71. if (res.code === 'ValidationFailed') {
  72. // My custom error messages from the API.
  73. console.log(res.fieldMessages)
  74. } else {
  75. console.log('this is a client (probably invalid JSON) error, but also might be a server error (bad JSON parsing/validation)')
  76. }
  77. break
  78. case 500:
  79. console.log('server error, try again')
  80. break
  81. default:
  82. console.log('unhandled')
  83. break
  84. }
  85. })
  86. .catch(err => {
  87. console.error(err)
  88. })
  89. }
Add Comment
Please, Sign In to add comment