Skip to content
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

Add fetch wrapper #3

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function fallible(): Result<number, string> {

const res = fallible();

// Using isOk helper will do this for You, but You can also
// Using isOk helper will do this for you, but you can also
// access the `__kind` field and compare it with `ResultKind` enum directly
if (isOk(res)) {
// Typescript infers res.data's type as `number`
Expand All @@ -65,7 +65,7 @@ const res: Result<number, string> = fallible();
// Call `equip` with the Result of fallible function
const equipped: ResultEquipped<number, string> = equip(res);

// Use as You would Rust's Result
// Use as you would Rust's Result
const squared: number = equipped.map(n => n * n).expect('Squared n');

// Using unwrap can cause a panic: `panicked at 'Squared n: "<err message>"'`
Expand Down
66 changes: 66 additions & 0 deletions package-lock.json

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

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,15 @@
"@types/jest": "^26.0.24",
"clean-terminal-webpack-plugin": "^3.0.0",
"jest": "^27.0.6",
"jest-fetch-mock": "^3.0.3",
"terser-webpack-plugin": "^5.1.4",
"ts-jest": "^27.0.4",
"ts-loader": "^9.2.4",
"tslint": "^6.1.3",
"typedoc": "^0.21.4",
"typescript": "^4.3.5",
"webpack": "^5.47.1",
"webpack-cli": "^4.7.2",
"ts-jest": "^27.0.4",
"tslint": "^6.1.3"
"webpack-cli": "^4.7.2"
},
"files": [
"dist/**/*"
Expand Down
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ export * from './option/consts';
export * from './option/equipped';

// Wrappers for common js functions
export * from './js_wrappers';
export * from './js_wrappers/types';
export * from './js_wrappers/fetch';
export * from './js_wrappers/helpers';
export * from './js_wrappers/parse_json';
36 changes: 0 additions & 36 deletions src/js_wrappers.spec.ts

This file was deleted.

21 changes: 0 additions & 21 deletions src/js_wrappers.ts

This file was deleted.

40 changes: 40 additions & 0 deletions src/js_wrappers/fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { equip } from '../helpers';
import { Ok, Err } from '../result/helpers';
import { catchResult, catchAsyncResult } from './helpers';

import { Result, ResultKind } from '../result/types';
import { SafeResponse, SafeFetchError } from './types';


export async function safeFetch(
input: RequestInfo,
init?: RequestInit,
): Promise<Result<SafeResponse, string>> {
// Catching async error
const caught = await catchAsyncResult(() => fetch(input, init));

// Mapping the result from Response into SafeResponse
return equip(caught).map((res: Response) => {
return {
// Copies
body: res.body,
bodyUsed: res.bodyUsed,
headers: res.headers,
ok: res.ok,
redirected: res.redirected,
status: res.status,
statusText: res.statusText,
type: res.type,
url: res.url,
clone: res.clone,

// Safetied
trailer: res.trailer,
arrayBuffer: res.arrayBuffer,
blob: res.blob,
formData: res.formData,
json: res.json,
text: res.text,
} as any as SafeResponse;
}).inner;
}
29 changes: 29 additions & 0 deletions src/js_wrappers/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Ok, Err } from '../result/helpers';

import { Result } from '../result/types';


/**
* Turns any fallible function's output (T) into Result<T, string>.
*/
export function catchResult<T>(f: () => T): Result<T, string> {
try {
return Ok(f());
} catch(e) {
return Err(String(e));
}
}

/**
* Turns any async fallible function's output (T) into
* Promise<Result<T, string>>.
*/
export async function catchAsyncResult<T>(
f: () => Promise<T>,
): Promise<Result<T, string>> {
try {
return Ok(await f());
} catch(e) {
return Err(String(e));
}
}
92 changes: 92 additions & 0 deletions src/js_wrappers/js_wrappers.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { SafeResponse } from './types';
import { Result, ResultKind } from '../result/types';

import { Ok, Err } from '../result/helpers';

import { safeFetch } from './fetch';
import { parseJson } from './parse_json';
import { catchResult, catchAsyncResult } from './helpers';

import { enableFetchMocks } from 'jest-fetch-mock';
enableFetchMocks();


describe('js wrappers > helpers', () => {
test('catchResult', () => {
function throwsError(): void {
throw new Error('1234');
}
expect(throwsError).toThrowError();

function doesNotThrowError(): number {
return 5;
}
expect(doesNotThrowError).not.toThrowError();

expect(catchResult(throwsError)).toEqual(Err('Error: 1234'));
expect(catchResult(doesNotThrowError)).toEqual(Ok(5));
});

test('catchAsyncResult', async () => {
async function throwsError(): Promise<void> {
throw new Error('1234');
}
expect(throwsError()).rejects.toEqual(new Error('1234'));

async function doesNotThrowError(): Promise<number> {
return 5;
}
expect(doesNotThrowError()).resolves.toEqual(5);

expect(catchAsyncResult(throwsError))
.resolves
.toEqual(Err('Error: 1234'));
expect(catchAsyncResult(doesNotThrowError))
.resolves
.toEqual(Ok(5));
});
});

describe('js wrappers > parse_json', () => {
test('parseJson', () => {
const j1: string = '{';
const res1: Result<number, string> = parseJson(j1);
expect(res1.__kind).toEqual(ResultKind.Err);
expect(res1.data).toEqual('SyntaxError: Unexpected end of JSON input');

const j2: string = '{ "test": 2 }';
const res2: Result<object, string> = parseJson(j2);
expect(res2.__kind).toEqual(ResultKind.Ok);
expect(res2.data).toEqual({ test: 2 });
});
});

describe('js wrappers > fetch', () => {
it('should return an error on invalid url call', async () => {
// Using jest-fetch-mock
(fetch as any).mockAbortOnce()

const fetched: Result<SafeResponse, string> = await safeFetch('asdf');

expect(fetched)
.toEqual(Err('ReferenceError: DOMException is not defined'));
});

it('should return valid json', async () => {
// Using jest-fetch-mock
(fetch as any).mockResponseOnce(JSON.stringify({ data: '2137' }));

const fetched: Result<SafeResponse, string> = await safeFetch('asdf');

expect(fetched.__kind).toEqual(ResultKind.Ok);

const json: Result<{ data: string }, string>
= await (fetched.data as SafeResponse).json();

console.log({json});
// const fetched: Result<SafeResponse, string> = await safeFetch('asdf');
//
// expect(fetched)
// .toEqual(Err('ReferenceError: DOMException is not defined'));
});
});
Loading