Skip to main content

@w5s/http

W5S HTTP client module (@w5s/http)

NPM Version License

Installation

npm install @w5s/http

Usage

import { requestSend, HTTPError, ResponseParser, Client } from '@w5s/http';
import { Type } from '@w5s/core';
import { Task } from '@w5s/task';
import { TimeoutError } from '@w5s/error';

const client = Client();
const getText = (id: number) => ({
url: `http://localhost/${id}`,
});
const FooObject = Type.Object({
foo: Type.boolean,
});

declare function logDebug(message: unknown): Task<void, never>;
declare function logError(message: unknown): Task<void, never>;

export function program() {
const responseTask = requestSend(client, getText(123));
const parsed = Task.andThen(responseTask, ResponseParser.json(FooObject));
const log = Task.andThen(parsed, (response) => logDebug(response.foo));
const handled = Task.orElse(log, (error) => {
switch (error.name) {
case HTTPError.InvalidURL.errorName: {
return logError(`A wrong url was passed. Got ${error.input}`);
}
case HTTPError.NetworkError.errorName: {
return logError('A network error occurred');
}
case HTTPError.ParserError.errorName: {
return logError('A parser error occurred');
}
case TimeoutError.errorName: {
return logError('Operation timed out');
}
default: {
return logError('Unknown');
}
}
});

return handled;
}

Task.run(program()); // Result<{ foo: boolean }, FetchNetworkError|FetchParseError>

License

MIT © Julien Polo julien.polo@gmail.com

Index

Constructor

Headers

Headers: any

HTTP header record constructor

@example
const headersFromIterable = Headers([
['key1', 'value1'],
['key2', 'value2']
]);// { key1: 'value1, key2: 'value2' }
const headersFromObject = Headers({
key1: 'value1',
key2: 'value2'
});// { key1: 'value1, key2: 'value2' }
@param

a record or iterable to initialize

Other

HTTPError

Union type of http client errors

Method

Method: string

ReferrerPolicy

ReferrerPolicy: Enum.ValueOf<typeof ReferrerPolicy>

RequestCache

RequestCache: Enum.ValueOf<typeof RequestCache>

RequestCredentials

RequestCredentials: Enum.ValueOf<typeof RequestCredentials>

RequestDestination

RequestDestination: Enum.ValueOf<typeof RequestDestination>

RequestRedirect

RequestRedirect: Enum.ValueOf<typeof RequestRedirect>

ResponseType

ResponseType: Enum.ValueOf<typeof ResponseType>

constReferrerPolicy

ReferrerPolicy: any = ...

constRequestCache

RequestCache: any = ...

constRequestCredentials

RequestCredentials: any = ...

constRequestDestination

RequestDestination: any = ...

constRequestRedirect

RequestRedirect: any = ...

constResponse

Response: any = ...

constResponseType

ResponseType: any = ...