fetch-json.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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) as
  70. | string
  71. | undefined
  72. if (message && message !== defaultMessage) return message
  73. const statusCodes: { readonly [K: number]: string } = {
  74. 400: 'Invalid Request. Please correct the data and try again.',
  75. 403: 'Session error. Please check you have cookies enabled. If the problem persists, try clearing your cache and cookies.',
  76. 429: 'Too many attempts. Please wait for a while and try again.',
  77. }
  78. return statusCode && statusCodes[statusCode]
  79. ? statusCodes[statusCode]
  80. : 'Something went wrong. Please try again.'
  81. }
  82. }
  83. function fetchJSON<T>(
  84. path: FetchPath,
  85. {
  86. body = {},
  87. headers = {},
  88. method = 'GET',
  89. credentials = 'same-origin',
  90. swallowAbortError = true,
  91. ...otherOptions
  92. }: FetchConfig
  93. ) {
  94. const options: RequestInit = {
  95. ...otherOptions,
  96. headers: {
  97. ...headers,
  98. 'Content-Type': 'application/json',
  99. 'X-Csrf-Token': window.csrfToken,
  100. Accept: 'application/json',
  101. },
  102. credentials,
  103. method,
  104. }
  105. if (method !== 'GET' && method !== 'HEAD') {
  106. options.body = JSON.stringify(body)
  107. }
  108. // The returned Promise and the `.then(handleSuccess, handleError)` handlers are needed
  109. // to avoid calling `finally` in a Promise chain (and thus updating the component's state)
  110. // after a component has unmounted.
  111. // `resolve` will be called when the request succeeds, `reject` will be called when the request fails,
  112. // but nothing will be called if the request is cancelled via an AbortController.
  113. return new Promise<T>((resolve, reject) => {
  114. fetch(path, options).then(
  115. response => {
  116. return parseResponseBody(response).then(
  117. data => {
  118. if (response.ok) {
  119. resolve(data)
  120. } else {
  121. // the response from the server was not 2xx
  122. reject(
  123. new FetchError(
  124. response.statusText,
  125. path,
  126. options,
  127. response,
  128. data
  129. )
  130. )
  131. }
  132. },
  133. error => {
  134. // parsing the response body failed
  135. reject(
  136. new FetchError(
  137. 'There was an error parsing the response body',
  138. path,
  139. options,
  140. response
  141. ).withCause(error)
  142. )
  143. }
  144. )
  145. },
  146. error => {
  147. // swallow the error if the fetch was cancelled (e.g. by cancelling an AbortController on component unmount)
  148. if (swallowAbortError && error.name === 'AbortError') {
  149. return
  150. }
  151. // the fetch failed
  152. reject(
  153. new FetchError(
  154. 'There was an error fetching the JSON',
  155. path,
  156. options
  157. ).withCause(error)
  158. )
  159. }
  160. )
  161. })
  162. }
  163. async function parseResponseBody(response: Response) {
  164. const contentType = response.headers.get('Content-Type')
  165. if (!contentType) {
  166. return {}
  167. }
  168. if (/application\/json/.test(contentType)) {
  169. return response.json()
  170. }
  171. if (/text\/plain/.test(contentType)) {
  172. const message = await response.text()
  173. return { message }
  174. }
  175. if (/text\/html/.test(contentType)) {
  176. const message = await response.text()
  177. // only use HTML responses which don't start with `<`
  178. if (!/^\s*</.test(message)) {
  179. return { message }
  180. }
  181. }
  182. // response body ignored as content-type is either not set (e.g. 204
  183. // responses) or unsupported
  184. return {}
  185. }
  186. export function getUserFacingMessage(error: Error | null) {
  187. if (!error) {
  188. return undefined
  189. }
  190. if (error instanceof FetchError) {
  191. return error.getUserFacingMessage()
  192. }
  193. return error.message
  194. }