fetch-json.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // fetch wrapper to make simple JSON requests:
  2. // - send the CSRF token in the request
  3. // - set the JSON content-type in the request headers
  4. // - throw errors on non-ok response
  5. // - parse JSON response body, unless response is empty
  6. import OError from '@overleaf/o-error'
  7. type FetchPath = string
  8. // Custom config types are merged with `fetch`s RequestInit type
  9. type FetchConfig = {
  10. swallowAbortError?: boolean
  11. body?: Record<string, unknown>
  12. } & Omit<RequestInit, 'body'>
  13. export function getJSON<T = any>(path: FetchPath, options?: FetchConfig) {
  14. return fetchJSON<T>(path, { ...options, method: 'GET' })
  15. }
  16. export function postJSON<T = any>(path: FetchPath, options?: FetchConfig) {
  17. return fetchJSON<T>(path, { ...options, method: 'POST' })
  18. }
  19. export function putJSON<T = any>(path: FetchPath, options?: FetchConfig) {
  20. return fetchJSON<T>(path, { ...options, method: 'PUT' })
  21. }
  22. export function deleteJSON<T = any>(path: FetchPath, options?: FetchConfig) {
  23. return fetchJSON<T>(path, { ...options, method: 'DELETE' })
  24. }
  25. function getErrorMessageForStatusCode(statusCode?: number) {
  26. if (!statusCode) {
  27. return 'Unknown Error'
  28. }
  29. const statusCodes: { readonly [K: number]: string } = {
  30. 400: 'Bad Request',
  31. 401: 'Unauthorized',
  32. 403: 'Forbidden',
  33. 404: 'Not Found',
  34. 429: 'Too Many Requests',
  35. 500: 'Internal Server Error',
  36. 502: 'Bad Gateway',
  37. 503: 'Service Unavailable',
  38. }
  39. return statusCodes[statusCode] ?? `Unexpected Error: ${statusCode}`
  40. }
  41. export class FetchError extends OError {
  42. public url: string
  43. public options?: RequestInit
  44. public response?: Response
  45. public data?: any
  46. constructor(
  47. message: string,
  48. url: string,
  49. options?: RequestInit,
  50. response?: Response,
  51. data?: any
  52. ) {
  53. // On HTTP2, the `statusText` property is not set,
  54. // so this `message` will be undefined. We need to
  55. // set a message based on the response `status`, so
  56. // our error UI rendering will work
  57. if (!message) {
  58. message = getErrorMessageForStatusCode(response?.status)
  59. }
  60. super(message, { statusCode: response ? response.status : undefined })
  61. this.url = url
  62. this.options = options
  63. this.response = response
  64. this.data = data
  65. }
  66. getUserFacingMessage() {
  67. const statusCode = this.response?.status
  68. const defaultMessage = getErrorMessageForStatusCode(statusCode)
  69. const message = this.data?.message?.text || this.data?.message
  70. if (message && message !== defaultMessage) return message
  71. const statusCodes: { readonly [K: number]: string } = {
  72. 400: 'Invalid Request. Please correct the data and try again.',
  73. 403: 'Session error. Please check you have cookies enabled. If the problem persists, try clearing your cache and cookies.',
  74. 429: 'Too many attempts. Please wait for a while and try again.',
  75. }
  76. return statusCode && statusCodes[statusCode]
  77. ? statusCodes[statusCode]
  78. : 'Something went wrong. Please try again.'
  79. }
  80. }
  81. function fetchJSON<T>(
  82. path: FetchPath,
  83. {
  84. body = {},
  85. headers = {},
  86. method = 'GET',
  87. credentials = 'same-origin',
  88. swallowAbortError = true,
  89. ...otherOptions
  90. }: FetchConfig
  91. ) {
  92. const options: RequestInit = {
  93. ...otherOptions,
  94. headers: {
  95. ...headers,
  96. 'Content-Type': 'application/json',
  97. 'X-Csrf-Token': window.csrfToken,
  98. Accept: 'application/json',
  99. },
  100. credentials,
  101. method,
  102. }
  103. if (method !== 'GET' && method !== 'HEAD') {
  104. options.body = JSON.stringify(body)
  105. }
  106. // The returned Promise and the `.then(handleSuccess, handleError)` handlers are needed
  107. // to avoid calling `finally` in a Promise chain (and thus updating the component's state)
  108. // after a component has unmounted.
  109. // `resolve` will be called when the request succeeds, `reject` will be called when the request fails,
  110. // but nothing will be called if the request is cancelled via an AbortController.
  111. return new Promise<T>((resolve, reject) => {
  112. fetch(path, options).then(
  113. response => {
  114. return parseResponseBody(response).then(
  115. data => {
  116. if (response.ok) {
  117. resolve(data)
  118. } else {
  119. // the response from the server was not 2xx
  120. reject(
  121. new FetchError(
  122. response.statusText,
  123. path,
  124. options,
  125. response,
  126. data
  127. )
  128. )
  129. }
  130. },
  131. error => {
  132. // parsing the response body failed
  133. reject(
  134. new FetchError(
  135. 'There was an error parsing the response body',
  136. path,
  137. options,
  138. response
  139. ).withCause(error)
  140. )
  141. }
  142. )
  143. },
  144. error => {
  145. // swallow the error if the fetch was cancelled (e.g. by cancelling an AbortController on component unmount)
  146. if (swallowAbortError && error.name === 'AbortError') {
  147. return
  148. }
  149. // the fetch failed
  150. reject(
  151. new FetchError(
  152. 'There was an error fetching the JSON',
  153. path,
  154. options
  155. ).withCause(error)
  156. )
  157. }
  158. )
  159. })
  160. }
  161. async function parseResponseBody(response: Response) {
  162. const contentType = response.headers.get('Content-Type')
  163. if (!contentType) {
  164. return {}
  165. }
  166. if (/application\/json/.test(contentType)) {
  167. return response.json()
  168. }
  169. if (/text\/plain/.test(contentType)) {
  170. const message = await response.text()
  171. return { message }
  172. }
  173. if (/text\/html/.test(contentType)) {
  174. const message = await response.text()
  175. // only use HTML responses which don't start with `<`
  176. if (!/^\s*</.test(message)) {
  177. return { message }
  178. }
  179. }
  180. // response body ignored as content-type is either not set (e.g. 204
  181. // responses) or unsupported
  182. return {}
  183. }
  184. export function getUserFacingMessage(error: Error): string {
  185. if (error instanceof FetchError) {
  186. return error.getUserFacingMessage()
  187. } else {
  188. // checking existence of `error` to prevent errors when called from Javascript
  189. return error?.message
  190. }
  191. }