generated from Marius9595/boilerplate-ts
-
Notifications
You must be signed in to change notification settings - Fork 5
🎉 Support asynchronous operations #72
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
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
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,112 @@ | ||
| import { AsyncEither } from './async-either'; | ||
| import { describe, expect, it } from 'vitest'; | ||
| import { Either } from './either'; | ||
|
|
||
| const mockFetch = (url: string): Promise<string> => { | ||
| if (url.includes('users/1')) { | ||
| return Promise.resolve(JSON.stringify({ id: 1, name: 'Alice' })); | ||
| } else if (url.includes('posts/1')) { | ||
| return Promise.resolve(JSON.stringify([{ title: 'First post' }, { title: 'Second post' }])); | ||
| } else { | ||
| return Promise.reject(new Error(`Resource not found: ${url}`)); | ||
| } | ||
| }; | ||
|
|
||
| type User = { id: number; name: string }; | ||
|
|
||
| const fetchUser = (id: number): AsyncEither<Error, User> => { | ||
| return AsyncEither.fromPromise( | ||
| mockFetch(`/api/users/${id}`).then(JSON.parse), | ||
| (error) => new Error(`Failed to fetch user: ${(error as Error).message}`) | ||
| ); | ||
| }; | ||
|
|
||
| type Post = { title: string }; | ||
|
|
||
| const fetchPosts = (id: number): AsyncEither<Error, Post[]> => { | ||
| return AsyncEither.fromPromise( | ||
| mockFetch(`/api/posts/${id}`).then(JSON.parse), | ||
| (error) => new Error(`Failed to fetch posts: ${error}`) | ||
| ); | ||
| }; | ||
|
|
||
| type Response<T> = { | ||
| status: number; | ||
| body: T; | ||
| }; | ||
|
|
||
| const successResponse = (posts: Post[]): Response<string[]> => ({ | ||
| status: 200, | ||
| body: posts.map((post) => post.title), | ||
| }); | ||
|
|
||
| const failureResponse = (error: string): Response<string> => ({ | ||
| status: 500, | ||
| body: error, | ||
| }); | ||
|
|
||
| const divide = (a: number, b: number): Either<string, number> => { | ||
| if (b === 0) return Either.left<string, number>('Division by zero'); | ||
| return Either.right<string, number>(a / b); | ||
| }; | ||
|
|
||
| describe('AsyncEither should', () => { | ||
| it('handle right values', async () => { | ||
| const result = await AsyncEither.fromSafePromise<string, number>(Promise.resolve(5)) | ||
| .map((x) => x * 2) | ||
| .fold({ | ||
| ifRight: (value) => `Value: ${value}`, | ||
| ifLeft: (error) => error, | ||
| }); | ||
|
|
||
| expect(result).toBe('Value: 10'); | ||
| }); | ||
|
|
||
| it('handle left values', async () => { | ||
| const result = await AsyncEither.fromPromise(Promise.reject('Something went wrong'), (reason) => reason as string) | ||
| .mapLeft((error) => `Error: ${error}`) | ||
| .fold({ | ||
| ifRight: (value) => `Value: ${value}`, | ||
| ifLeft: (error) => error, | ||
| }); | ||
|
|
||
| expect(result).toBe('Error: Something went wrong'); | ||
| }); | ||
|
|
||
| it('interoperate with synchronous Either', async () => { | ||
| const syncEither = divide(10, 2); | ||
|
|
||
| const result = await AsyncEither.fromSync(syncEither) | ||
| .map((value) => value * 3) | ||
| .fold({ | ||
| ifRight: (value) => `value is ${value}`, | ||
| ifLeft: (error) => error, | ||
| }); | ||
|
|
||
| expect(result).toBe('value is 15'); | ||
| }); | ||
|
|
||
| it('compose successive async operations', async () => { | ||
| const getPostsByUser = (user: User) => { | ||
| return fetchPosts(user.id); | ||
| }; | ||
|
|
||
| async function fetchPostsByUser(id: number) { | ||
| return await fetchUser(id) | ||
| .flatMap(getPostsByUser) | ||
| .map(successResponse) | ||
| .flatMapLeft((error) => Either.left('Unsuccessful operation: ' + error.message)) | ||
| .mapLeft(failureResponse) | ||
| .fold<Response<string | string[]>>({ | ||
| ifRight: (titles) => titles, | ||
| ifLeft: (error) => error, | ||
| }); | ||
| } | ||
|
|
||
| await expect(fetchPostsByUser(1)).resolves.toEqual({ status: 200, body: ['First post', 'Second post'] }); | ||
| await expect(fetchPostsByUser(2)).resolves.toEqual({ | ||
| status: 500, | ||
| body: 'Unsuccessful operation: Failed to fetch user: Resource not found: /api/users/2', | ||
| }); | ||
| }); | ||
| }); |
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.