Skip to content

Commit

Permalink
Simplify AJAX utility module (#2612)
Browse files Browse the repository at this point in the history
simplifies ajax utility module
  • Loading branch information
josemigallas authored Sep 16, 2021
1 parent d97943f commit bb09058
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { Card } from '@patternfly/react-core'
import { ApplicationPlansTable } from 'Plans'
import * as alert from 'utilities/alert'
import {
post,
ajax,
safeFromJsonString,
confirm
Expand All @@ -24,7 +23,7 @@ const ApplicationPlansTableCard = ({ plans: initialPlans, count, searchHref }: P
const [plans, setPlans] = React.useState<ApplicationPlan[]>(initialPlans)
const [isLoading, setIsLoading] = React.useState<boolean>(false)

const handleActionCopy = (path) => post(path)
const handleActionCopy = (path) => ajax(path, 'POST')
.then(data => data.json()
.then(res => {
if (data.status === 201) {
Expand Down Expand Up @@ -62,7 +61,7 @@ const ApplicationPlansTableCard = ({ plans: initialPlans, count, searchHref }: P
})
.finally(() => setIsLoading(false))

const handleActionPublishHide = (path) => post(path)
const handleActionPublishHide = (path) => ajax(path, 'POST')
.then(data => data.json()
.then(res => {
if (data.status === 200) {
Expand Down
4 changes: 2 additions & 2 deletions app/javascript/src/Plans/components/DefaultPlanSelectCard.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @flow

import * as React from 'react'
import { post, createReactWrapper } from 'utilities'
import { ajax, createReactWrapper } from 'utilities'
import {
Form,
FormGroup,
Expand Down Expand Up @@ -31,7 +31,7 @@ const DefaultPlanSelectCard = ({ product, initialDefaultPlan, path }: Props): Re
const body = plan.id >= 0 ? new URLSearchParams({ id: plan.id.toString() }) : undefined
const url = path.replace(':id', String(product.id))

post(url, body)
ajax(url, 'POST', body)
.then(data => {
if (data.ok) {
alert.notice('Default plan was updated')
Expand Down
29 changes: 16 additions & 13 deletions app/javascript/src/utilities/ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,25 @@

export type Method = 'GET' | 'POST' | 'DELETE'

const ajax = (url: string, method: Method, body?: URLSearchParams): Promise<Response> => {
type FetchFunction = (url: string, method: Method, body?: URLSearchParams) => Promise<Response>

const _ajax = (headers: Object) => {
const meta = document.querySelector('meta[name="csrf-token"]')
const token = (meta && meta.getAttribute('content')) || ''

return fetch(url, {
method: method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-CSRF-Token': token
},
body
})
return function (url, method, body?) {
return fetch(url, {
method: method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-CSRF-Token': token
},
body
})
}
}

const post = (url: string, body?: URLSearchParams): Promise<Response> => {
return ajax(url, 'POST', body)
}
const ajax: FetchFunction = _ajax({ 'ContentType': 'application/x-www-form-urlencoded; charset=UTF-8' })
const ajaxJSON: FetchFunction = _ajax({ 'Content-Type': 'application/json; charset=UTF-8' })

export { ajax, post }
export { ajax, ajaxJSON }
12 changes: 6 additions & 6 deletions spec/javascripts/Plans/components/DefaultPlanSelectCard.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ const noticeSpy = jest.spyOn(alert, 'notice')
const errorSpy = jest.spyOn(alert, 'error')

jest.mock('utilities/ajax')
import * as ajax from 'utilities/ajax'
const post = (ajax.post: JestMockFn<empty, any>)
import * as AJAX from 'utilities/ajax'
const ajax = (AJAX.ajax: JestMockFn<empty, any>)

const plan = { id: 1, name: 'My Plan' }
const props = {
Expand All @@ -26,7 +26,7 @@ it('should render', () => {
})

it('should show a success message if request goes well', async () => {
post.mockResolvedValue({ ok: true })
ajax.mockResolvedValue({ ok: true })
const wrapper = mount(<DefaultPlanSelectCard {...props} />)

await act(async () => {
Expand All @@ -37,7 +37,7 @@ it('should show a success message if request goes well', async () => {
})

it('should show an error message when selected plan does not exist', async () => {
post.mockResolvedValueOnce({ status: 404 })
ajax.mockResolvedValueOnce({ status: 404 })
const wrapper = mount(<DefaultPlanSelectCard {...props} />)

await act(async () => {
Expand All @@ -48,7 +48,7 @@ it('should show an error message when selected plan does not exist', async () =>
})

it('should show an error message when server returns an error', async () => {
post.mockResolvedValue({ status: 403 })
ajax.mockResolvedValue({ status: 403 })
const wrapper = mount(<DefaultPlanSelectCard {...props} />)

await act(async () => {
Expand All @@ -62,7 +62,7 @@ it('should show an error message when connection fails', async () => {
// $FlowExpectedError[cannot-write] suppress error logs during test
console.error = jest.fn()

post.mockRejectedValue()
ajax.mockRejectedValue()
const wrapper = mount(<DefaultPlanSelectCard {...props} />)

await act(async () => {
Expand Down

0 comments on commit bb09058

Please sign in to comment.