Utils

Archimedes has baked in some utils that are usually needed in most projects:

  • Maybe
  • Datetime
  • HttpClient
  • Observer
  • Extended Error
  • Is Promise
  • Types
    • Class

Installation#

```bash
npm i @archimedes/utils -SE
```
```bash
yarn add @archimedes/utils -E
```

Maybe#

This is a monad that improves null and undefined handling. It implements the null object pattern. It's best used with deep nullable and optional object structures, in other cases you might be better off with using the nullish coalescing operator and optional chaining operator.

You can create a Maybe like so:

Maybe.from(42)

When you use a Maybe in order to access a value you have to use the method getOrElse:

const maybe = Maybe.from(42)
maybe.getOrElse(0)

This is best used with objects:

type Type = { foo: Maybe<{ bar: string }> }
const maybeMap = Maybe.from<Type>({ foo: Maybe.from({ bar: 'qux' }) })
expect(maybeMap.flatMap(x => x.foo).map(x => x.bar)).toEqual(Maybe.from('qux'))

You can use the map method to map an existing value to another one. If the Maybe doesn't have a value then the map is not called. If you want to unwrap a Maybe inside a Maybe you can use the flatMap method.

Datetime#

This utility improves Date handling. Every date you create is in UTC timezone.

HttpClient#

A simple fetch wrapper that has improved TypeScript support, middlewares and overall a simpler API than fetch.

const httpClient = HttpClient.create({ baseUrl: 'http://localhost:8080' })
httpClient.get('/users')

Observer#

This interface allows you to implement the Observer pattern.

Extended error#

Small utility to extend from when creating custom errors in order to maintain proper stack trace for where our error was thrown (only available in V8):

export class CustomError extends ExtendedError {
constructor() {
super('This is a custom error')
}
}