Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export const parseAPIResponse = response =>
- new Promise(resolve => resolve(response.text()))
- .catch(err =>
- // eslint-disable-next-line prefer-promise-reject-errors
- Promise.reject({
- type: 'NetworkError',
- status: response.status,
- message: err,
- }))
- .then((responseBody) => {
- // Attempt to parse JSON
- try {
- const parsedJSON = JSON.parse(responseBody);
- if (response.ok) return parsedJSON;
- if (response.status >= 500) {
- // eslint-disable-next-line prefer-promise-reject-errors
- return Promise.reject({
- type: 'ServerError',
- status: response.status,
- body: parsedJSON,
- });
- }
- if (response.status <= 501) {
- // eslint-disable-next-line prefer-promise-reject-errors
- return Promise.reject({
- type: 'ApplicationError',
- status: response.status,
- body: parsedJSON,
- });
- }
- } catch (e) {
- // We should never get these unless response is mangled
- // Or API is not properly implemented
- // eslint-disable-next-line prefer-promise-reject-errors
- return Promise.reject({
- type: 'InvalidJSON',
- status: response.status,
- body: responseBody,
- });
- }
- });
- handleSubmit(e) {
- e.preventDefault()
- const body = {
- email: this.state.email,
- }
- let resStatus = 0
- fetch(Config.REST_API_URL + 'users/registration-request', {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- })
- .then(res => {
- resStatus = res.status
- return res.json()
- })
- .then(res => {
- switch (resStatus) {
- case 201:
- console.log('success')
- break
- case 400:
- if (res.code === 'ValidationFailed') {
- // My custom error messages from the API.
- console.log(res.fieldMessages)
- } else {
- console.log('this is a client (probably invalid JSON) error, but also might be a server error (bad JSON parsing/validation)')
- }
- break
- case 500:
- console.log('server error, try again')
- break
- default:
- console.log('unhandled')
- break
- }
- })
- .catch(err => {
- console.error(err)
- })
- }
Add Comment
Please, Sign In to add comment