Skip to content

Commit

Permalink
fix: use PUT method, fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
schmanu committed Feb 19, 2024
1 parent 9bfbf4d commit 89429d1
Show file tree
Hide file tree
Showing 4 changed files with 113 additions and 15 deletions.
6 changes: 3 additions & 3 deletions src/endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function postEndpoint<T extends keyof paths>(
params?: paths[T] extends PostEndpoint ? paths[T]['post']['parameters'] : never,
): Promise<paths[T] extends PostEndpoint ? paths[T]['post']['responses'][200]['schema'] : never> {
const url = makeUrl(baseUrl, path as string, params?.path, params?.query)
return fetchData(url, params?.body, params?.headers)
return fetchData(url, 'POST', params?.body, params?.headers)
}

export function putEndpoint<T extends keyof paths>(
Expand All @@ -27,7 +27,7 @@ export function putEndpoint<T extends keyof paths>(
params?: paths[T] extends PutEndpoint ? paths[T]['put']['parameters'] : never,
): Promise<paths[T] extends PutEndpoint ? paths[T]['put']['responses'][200]['schema'] : never> {
const url = makeUrl(baseUrl, path as string, params?.path, params?.query)
return fetchData(url, params?.body, params?.headers)
return fetchData(url, 'PUT', params?.body, params?.headers)
}

export function getEndpoint<T extends keyof paths>(
Expand All @@ -40,7 +40,7 @@ export function getEndpoint<T extends keyof paths>(
return fetchData(rawUrl)
}
const url = makeUrl(baseUrl, path as string, params?.path, params?.query)
return fetchData(url, undefined, params?.headers)
return fetchData(url, undefined, undefined, params?.headers)
}

export function deleteEndpoint<T extends keyof paths>(
Expand Down
11 changes: 8 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,15 @@ async function parseResponse<T>(resp: Response): Promise<T> {
return json
}

export async function fetchData<T>(url: string, body?: unknown, headers?: Record<string, string>): Promise<T> {
export async function fetchData<T>(
url: string,
method?: 'POST' | 'PUT',
body?: unknown,
headers?: Record<string, string>,
): Promise<T> {
let options:
| {
method: 'POST'
method: 'POST' | 'PUT'
headers: Record<string, string>
body: string
}
Expand All @@ -68,7 +73,7 @@ export async function fetchData<T>(url: string, body?: unknown, headers?: Record
const requestHeaders: Record<string, string> = headers ?? {}
requestHeaders['Content-Type'] = 'application/json'
options = {
method: 'POST',
method: method ?? 'POST',
body: typeof body === 'string' ? body : JSON.stringify(body),
headers: requestHeaders,
}
Expand Down
67 changes: 59 additions & 8 deletions tests/endpoint.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { fetchData } from '../src/utils'
import { getEndpoint, postEndpoint } from '../src/endpoint'
import { getEndpoint, postEndpoint, putEndpoint } from '../src/endpoint'

jest.mock('../src/utils', () => {
const originalModule = jest.requireActual('../src/utils')
Expand All @@ -17,7 +17,12 @@ describe('getEndpoint', () => {
success: true,
})

expect(fetchData).toHaveBeenCalledWith('https://test.test/v1/balances/supported-fiat-codes')
expect(fetchData).toHaveBeenCalledWith(
'https://test.test/v1/balances/supported-fiat-codes',
undefined,
undefined,
undefined,
)
})

it('should accept a path param', async () => {
Expand All @@ -27,7 +32,7 @@ describe('getEndpoint', () => {
}),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith('https://test.test/v1/chains/4/safes/0x123')
expect(fetchData).toHaveBeenCalledWith('https://test.test/v1/chains/4/safes/0x123', undefined, undefined, undefined)
})

it('should accept several path params', async () => {
Expand All @@ -38,7 +43,12 @@ describe('getEndpoint', () => {
}),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith('https://test.test/v1/chains/4/safes/0x123/balances/usd')
expect(fetchData).toHaveBeenCalledWith(
'https://test.test/v1/chains/4/safes/0x123/balances/usd',
undefined,
undefined,
undefined,
)
})

it('should accept query params', async () => {
Expand All @@ -49,10 +59,15 @@ describe('getEndpoint', () => {
}),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith('https://test.test/v1/chains/4/safes/0x123/balances/usd?exclude_spam=true')
expect(fetchData).toHaveBeenCalledWith(
'https://test.test/v1/chains/4/safes/0x123/balances/usd?exclude_spam=true',
undefined,
undefined,
undefined,
)
})

it('should accept body', async () => {
it('should accept POST request with body', async () => {
const body = {
to: '0x123',
value: 'test',
Expand All @@ -77,7 +92,12 @@ describe('getEndpoint', () => {
}),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith('https://test.test/v1/chains/4/transactions/0x123/propose', body)
expect(fetchData).toHaveBeenCalledWith(
'https://test.test/v1/chains/4/transactions/0x123/propose',
'POST',
body,
undefined,
)
})

it('should accept a raw URL', async () => {
Expand All @@ -101,6 +121,37 @@ describe('getEndpoint', () => {
}),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith('https://test.test/v1/chains/4/data-decoder', { data: '0x123' })
expect(fetchData).toHaveBeenCalledWith(
'https://test.test/v1/chains/4/data-decoder',
'POST',
{ data: '0x123' },
undefined,
)
})

it('should accept PUT request with body', async () => {

Check failure on line 132 in tests/endpoint.test.ts

View workflow job for this annotation

GitHub Actions / jest-github-action

getEndpoint > should accept PUT request with body

Error: expect(jest.fn()).toHaveBeenCalledWith(...expected) - Expected + Received - "https://test.test//v1/chains/4/safes/0x123/emails/0x456", + "https://test.test/v1/chains/4/safes/0x123/emails/0x456", "PUT", {"emailAddress": "[email protected]"}, {"Safe-Wallet-Signature": "0x234", "Safe-Wallet-Signature-Timestamp": "1708357611224"}, Number of calls: 1 at /home/runner/work/safe-gateway-typescript-sdk/safe-gateway-typescript-sdk/tests/endpoint.test.ts:150:23 at Generator.next (<anonymous>) at fulfilled (/home/runner/work/safe-gateway-typescript-sdk/safe-gateway-typescript-sdk/tests/endpoint.test.ts:5:58)
const body = {
emailAddress: '[email protected]',
}

const headers = {
'Safe-Wallet-Signature': '0x234',
'Safe-Wallet-Signature-Timestamp': jest.now().toString(),
}

await expect(
putEndpoint('https://test.test', '/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}', {
path: { chainId: '4', safe_address: '0x123', signer: '0x456' },
body,
headers,
}),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith(
'https://test.test//v1/chains/4/safes/0x123/emails/0x456',
'PUT',
body,
headers,
)
})
})
44 changes: 43 additions & 1 deletion tests/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe('utils', () => {
})
})

await expect(fetchData('/test/safe', '123')).resolves.toEqual({ success: true })
await expect(fetchData('/test/safe', 'POST', '123')).resolves.toEqual({ success: true })

expect(fetch).toHaveBeenCalledWith('/test/safe', {
method: 'POST',
Expand All @@ -62,6 +62,48 @@ describe('utils', () => {
})
})

it('should forward headers', async () => {
fetchMock.mockImplementation(() => {
return Promise.resolve({
ok: true,
text: () => Promise.resolve('{"success": "true"}'),
json: () => Promise.resolve({ success: true }),
})
})

await expect(fetchData('/test/safe', 'POST', '123', { TestHeader: '123456' })).resolves.toEqual({ success: true })

expect(fetch).toHaveBeenCalledWith('/test/safe', {
method: 'POST',
body: '123',
headers: {
TestHeader: '123456',
'Content-Type': 'application/json',
},
})
})

it('should use PUT if specified', async () => {
fetchMock.mockImplementation(() => {
return Promise.resolve({
ok: true,
text: () => Promise.resolve('{"success": "true"}'),
json: () => Promise.resolve({ success: true }),
})
})

await expect(fetchData('/test/safe', 'PUT', '123', { TestHeader: '123456' })).resolves.toEqual({ success: true })

expect(fetch).toHaveBeenCalledWith('/test/safe', {
method: 'PUT',
body: '123',
headers: {
TestHeader: '123456',
'Content-Type': 'application/json',
},
})
})

it('should throw if response is not OK', async () => {
fetchMock.mockImplementation(() => {
return Promise.resolve({
Expand Down

0 comments on commit 89429d1

Please sign in to comment.