Skip to content

Commit

Permalink
chore: Add fetch wrapper (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kunal Nagar authored Dec 22, 2021
1 parent 5a22b44 commit e33610d
Show file tree
Hide file tree
Showing 7 changed files with 100 additions and 11 deletions.
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
dist/
lib/
node_modules/
node_modules/
tsconfig.json
60 changes: 53 additions & 7 deletions dist/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/destinations/zenduty.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ACTION_SHORT_SUMMARY } from '../constants'
import { Alert } from '../entities'
import fetch from 'node-fetch'
import { request } from '../utils'

export const sendAlertsToZenduty = async (
apiKey: string,
Expand Down Expand Up @@ -37,7 +37,7 @@ export const sendAlertsToZenduty = async (
}
// eslint-disable-next-line i18n-text/no-en
const bearer = `Token ${apiKey}`
await fetch('https://www.zenduty.com/api/incidents/', {
await request('https://www.zenduty.com/api/incidents/', {
method: 'POST',
headers: {
Authorization: bearer,
Expand Down
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './request'
12 changes: 12 additions & 0 deletions src/utils/request/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import fetch, { Response as FetchResponse, RequestInit } from 'node-fetch'

type RequestOptions = Pick<RequestInit, 'method' | 'body' | 'headers'>
type Response = Pick<FetchResponse, 'headers' | 'json' | 'ok' | 'text'>

export const request = async (
url: string,
options?: RequestOptions,
): Promise<Response> =>
fetch(url, {
...options,
})
29 changes: 29 additions & 0 deletions src/utils/request/request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { request } from '.'
import fetch from 'node-fetch'

jest.mock('node-fetch')

const URL = 'someUrl'

describe('request', () => {
it('request: should perform a GET request with empty options object', async () => {
await request(URL)
expect(fetch).toHaveBeenCalledTimes(1)
expect(fetch).toHaveBeenCalledWith(URL, {})
})

it('request: should perform a POST request with body and headers', async () => {
const options = {
method: 'POST',
body: JSON.stringify({
key1: 'value1',
}),
headers: {
Authorization: 'Bearer token',
},
}
await request(URL, options)
expect(fetch).toHaveBeenCalledTimes(1)
expect(fetch).toHaveBeenCalledWith(URL, options)
})
})

0 comments on commit e33610d

Please sign in to comment.