-
Notifications
You must be signed in to change notification settings - Fork 3
Feature - API #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
62afe35
Implement Api
markogresak de76778
Emit declaration info
markogresak 80a8b55
Add prettier script
markogresak 5abc147
Make status and statusText optional
markogresak c90b2b2
Add tests for Api
markogresak 031d408
Copy tests for createUrlWithQuery
markogresak 86af6f1
Disable incremental build by default
markogresak a943747
Do not emit test files
markogresak c32a877
Use Method enum in tests
markogresak d598d9b
Hack test typing error
markogresak e572bd2
Move setupJest out of src folder
markogresak 7fd6b39
Remove dom lib
markogresak 9788564
Rename to successJsonResponse
markogresak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| tabWidth: 4 | ||
| printWidth: 100 | ||
| singleQuote: true | ||
| arrowParens: always | ||
| trailingComma: all |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| module.exports = { | ||
| moduleFileExtensions: ['js', 'ts'], | ||
| transform: { | ||
| '^.+\\.ts$': 'ts-jest', | ||
| }, | ||
| testEnvironment: 'node', | ||
| setupFiles: ['<rootDir>/setupJest.ts'], | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import { GlobalWithFetchMock } from 'jest-fetch-mock'; | ||
|
|
||
| // As suggested in jest-fetch-mock docs | ||
| // https://github.com/jefflau/jest-fetch-mock#typescript-guide | ||
| // With addition of node-fetch mock implementation. | ||
| const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock; | ||
| customGlobal.fetch = require('jest-fetch-mock'); | ||
| customGlobal.fetchMock = customGlobal.fetch; | ||
| jest.setMock('node-fetch', customGlobal.fetch); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| import { Response } from 'node-fetch'; | ||
|
|
||
| import { createUrlWithQuery } from './lib'; | ||
| import { createFakeErrorPayload } from './createRequest'; | ||
| import Api from './Api'; | ||
| import { Method } from './types'; | ||
|
|
||
| const API_URL_CORRECT = 'http://rock.prezly.test/api/v1/contacts'; | ||
| const API_URL_INCORRECT = 'htp:/rock.prezly.test/api/v1/contacts'; | ||
|
|
||
| const DEFAULT_REQUEST_PROPS = { | ||
| body: undefined, | ||
| headers: { | ||
| Accept: 'application/json', | ||
| 'Content-Type': 'application/json;charset=utf-8', | ||
| }, | ||
| }; | ||
|
|
||
| function successJsonResponse(body: object) { | ||
| return new Response(JSON.stringify(body), { | ||
| status: 200, | ||
| statusText: 'OK', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| function errorJSONResponse(body: object) { | ||
| return new Response(JSON.stringify(body), { | ||
| status: 500, | ||
| statusText: 'Internal Server Error', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| describe('Api', () => { | ||
| it('should resolve with correct payload', async () => { | ||
| const expectedPayload = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| const expectedResponse = successJsonResponse(expectedPayload); | ||
| global.fetch.mockResolvedValueOnce(expectedResponse); | ||
|
|
||
| const actualResponse = await Api.get(API_URL_CORRECT); | ||
|
|
||
| expect(actualResponse.status).toEqual(200); | ||
| expect(actualResponse.payload).toEqual(expectedPayload); | ||
| }); | ||
|
|
||
| it('should reject with correct payload', async () => { | ||
| const expectedPayload = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| const expectedResponse = errorJSONResponse(expectedPayload); | ||
| global.fetch.mockResolvedValueOnce(expectedResponse); | ||
|
|
||
| try { | ||
| await Api.get(API_URL_CORRECT); | ||
| } catch ({ status, payload }) { | ||
| expect(status).toEqual(500); | ||
| expect(payload).toEqual(expectedPayload); | ||
| } | ||
| }); | ||
|
|
||
| it('should reject with Invalid URL provided', async () => { | ||
| const errorMessage = 'Invalid URL provided'; | ||
| // Fetch mock doesn't validate the URL so we mock the error. | ||
| global.fetch.mockRejectOnce(new Error(errorMessage)); | ||
| try { | ||
| await Api.get(API_URL_INCORRECT); | ||
| } catch ({ payload }) { | ||
| const expectedErrorResponse = createFakeErrorPayload({ | ||
| status: undefined, | ||
| statusText: errorMessage, | ||
| }); | ||
|
|
||
| expect(payload).toEqual(expectedErrorResponse); | ||
| } | ||
| }); | ||
|
|
||
| it('should create a GET request', async () => { | ||
| const response = successJsonResponse({}); | ||
|
|
||
| global.fetch.mockResolvedValueOnce(response); | ||
|
|
||
| await Api.get(API_URL_CORRECT); | ||
|
|
||
| const expectedUrl = createUrlWithQuery(API_URL_CORRECT); | ||
|
|
||
| expect(global.fetch).toHaveBeenCalledWith(expectedUrl, { | ||
| ...DEFAULT_REQUEST_PROPS, | ||
| method: Method.GET, | ||
| }); | ||
| }); | ||
|
|
||
| it('should create a GET request with query params', async () => { | ||
| const response = successJsonResponse({}); | ||
| global.fetch.mockResolvedValueOnce(response); | ||
|
|
||
| const query = { foo: 'bar' }; | ||
| await Api.get(API_URL_CORRECT, { query }); | ||
|
|
||
| const expectedUrl = createUrlWithQuery(API_URL_CORRECT, query); | ||
|
|
||
| expect(global.fetch).toHaveBeenCalledWith(expectedUrl, { | ||
| ...DEFAULT_REQUEST_PROPS, | ||
| method: Method.GET, | ||
| }); | ||
| }); | ||
|
|
||
| it('should create a POST request', async () => { | ||
| const response = successJsonResponse({}); | ||
| global.fetch.mockResolvedValueOnce(response); | ||
|
|
||
| const query = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| const payload = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| await Api.post(API_URL_CORRECT, { query, payload }); | ||
|
|
||
| const expectedUrl = createUrlWithQuery(API_URL_CORRECT, query); | ||
|
|
||
| expect(global.fetch).toHaveBeenCalledWith(expectedUrl, { | ||
| ...DEFAULT_REQUEST_PROPS, | ||
| method: Method.POST, | ||
| body: JSON.stringify(payload), | ||
| }); | ||
| }); | ||
|
|
||
| it('should create a PUT request', async () => { | ||
| const response = successJsonResponse({}); | ||
| global.fetch.mockResolvedValueOnce(response); | ||
|
|
||
| const query = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| const payload = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| await Api.put(API_URL_CORRECT, { query, payload }); | ||
|
|
||
| const expectedUrl = createUrlWithQuery(API_URL_CORRECT, query); | ||
|
|
||
| expect(global.fetch).toHaveBeenCalledWith(expectedUrl, { | ||
| ...DEFAULT_REQUEST_PROPS, | ||
| method: Method.PUT, | ||
| body: JSON.stringify(payload), | ||
| }); | ||
| }); | ||
|
|
||
| it('should create a PATCH request', async () => { | ||
| const response = successJsonResponse({}); | ||
| global.fetch.mockResolvedValueOnce(response); | ||
|
|
||
| const query = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| const payload = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| await Api.patch(API_URL_CORRECT, { query, payload }); | ||
|
|
||
| const expectedUrl = createUrlWithQuery(API_URL_CORRECT, query); | ||
|
|
||
| expect(global.fetch).toHaveBeenCalledWith(expectedUrl, { | ||
| ...DEFAULT_REQUEST_PROPS, | ||
| method: Method.PATCH, | ||
| body: JSON.stringify(payload), | ||
| }); | ||
| }); | ||
|
|
||
| it('should create a DELETE request', async () => { | ||
| const response = successJsonResponse({}); | ||
| global.fetch.mockResolvedValueOnce(response); | ||
|
|
||
| const query = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| await Api.delete(API_URL_CORRECT, { query }); | ||
|
|
||
| const expectedUrl = createUrlWithQuery(API_URL_CORRECT, query); | ||
|
|
||
| expect(global.fetch).toHaveBeenCalledWith(expectedUrl, { | ||
| ...DEFAULT_REQUEST_PROPS, | ||
| method: Method.DELETE, | ||
| }); | ||
| }); | ||
|
|
||
| it('should create a DELETE request (with body)', async () => { | ||
| const response = successJsonResponse({}); | ||
| global.fetch.mockResolvedValueOnce(response); | ||
|
|
||
| const query = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| const payload = { | ||
| foo: 'bar', | ||
| }; | ||
|
|
||
| await Api.delete(API_URL_CORRECT, { query, payload }); | ||
|
|
||
| const expectedUrl = createUrlWithQuery(API_URL_CORRECT, query); | ||
|
|
||
| expect(global.fetch).toHaveBeenCalledWith(expectedUrl, { | ||
| ...DEFAULT_REQUEST_PROPS, | ||
| method: Method.DELETE, | ||
| body: JSON.stringify(payload), | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { Method, HeadersMap, Response } from './types'; | ||
| import createRequest from './createRequest'; | ||
|
|
||
| const Api = { | ||
| get: <P = any>( | ||
| url: string, | ||
| { query, headers }: { headers?: HeadersMap; query?: object } = {}, | ||
| ): Promise<Response<P>> => | ||
| createRequest(url, { | ||
| method: Method.GET, | ||
| headers, | ||
| query, | ||
| }), | ||
|
|
||
| post: <P = any>( | ||
| url: string, | ||
| { | ||
| headers, | ||
| query, | ||
| payload, | ||
| }: { headers?: HeadersMap; query?: object; payload?: object } = {}, | ||
| ): Promise<Response<P>> => | ||
| createRequest(url, { | ||
| method: Method.POST, | ||
| headers, | ||
| query, | ||
| payload, | ||
| }), | ||
|
|
||
| put: <P = any>( | ||
| url: string, | ||
| { | ||
| headers, | ||
| query, | ||
| payload, | ||
| }: { headers?: HeadersMap; query?: object; payload?: object } = {}, | ||
| ): Promise<Response<P>> => | ||
| createRequest(url, { | ||
| method: Method.PUT, | ||
| headers, | ||
| query, | ||
| payload, | ||
| }), | ||
|
|
||
| patch: <P = any>( | ||
| url: string, | ||
| { | ||
| headers, | ||
| query, | ||
| payload, | ||
| }: { headers?: HeadersMap; query?: object; payload?: object } = {}, | ||
| ): Promise<Response<P>> => | ||
| createRequest(url, { | ||
| method: Method.PATCH, | ||
| headers, | ||
| query, | ||
| payload, | ||
| }), | ||
|
|
||
| delete: <P = any>( | ||
| url: string, | ||
| { | ||
| headers, | ||
| query, | ||
| payload, | ||
| }: { headers?: HeadersMap; query?: object; payload?: object } = {}, | ||
| ): Promise<Response<P>> => | ||
| createRequest(url, { | ||
| method: Method.DELETE, | ||
| headers, | ||
| query, | ||
| payload, | ||
| }), | ||
| }; | ||
|
|
||
| export default Api; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import { ApiErrorPayload, HeadersMap, Response } from './types'; | ||
|
|
||
| export default class ApiError<P = ApiErrorPayload> extends Error implements Response<P> { | ||
| payload: P; | ||
| status: number; | ||
| statusText: string; | ||
| headers: HeadersMap; | ||
|
|
||
| constructor({ | ||
| payload, | ||
| status = 0, | ||
| statusText = 'Unspecified error', | ||
| headers = {}, | ||
| }: { | ||
| payload: P; | ||
| status: number; | ||
| statusText: string; | ||
| headers: HeadersMap; | ||
| }) { | ||
| super(`API Error (${status}): ${statusText}`); | ||
| this.payload = payload; | ||
| this.status = status; | ||
| this.statusText = statusText; | ||
| this.headers = headers; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| export const CONTENT_TYPE = 'application/json;charset=utf-8'; | ||
| export const INVALID_URL_ERROR_MESSAGE = 'Invalid URL provided'; | ||
| export const NETWORK_PROBLEM_ERROR_MESSAGE = 'Network problem'; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.