Provides Result and Optional monads, inspired by railway oriented programming.
npm install rop-monads
npm install rop-monadsor
yarn add rop-monads
`Using rop-monads
#### Optional
`typescript
import { Optional } from 'rop-monads';const age: Optional = Optional.of(getPerson()) // getPerson() returns an optional object that contains an age
.map(person => person.age);
`
#### Result`typescript
import { Result } from 'rop-monads';const todos: Result = apiCall()// returns a result
.flatMap(json => transformJson(json)) // the transform function can return a result as the json decoding can fail
todos.match({
ok: todos => handleTodos(todos),
err: failure => handleFailure(failure)
});
`Using
Result in HTTP controllers for example with express.jsError.ts
`typescript
type NotFoundError = {
kind: "NOT_FOUND";
reason: string;
};type InternalError = {
kind: "INTERNAL";
reason: Error;
};
type PersonError = NotFoundError | InternalError
`PersonController.ts
`typescript
const personService = getPersonService();function httpHandleFailure(res: express.Response, failure: PersonError) {
switch (failure.kind) {
case "NOT_FOUND":
log("failed to find person it does not exist", failure.reason);
return res.status(404).send({ status: 404, message: "person does not exist" });
case "INTERNAL":
log("failed to find person", failure.reason.message);
return res.status(500).send({ status: 500, message: "something went wrong" });
}
}
// assumed that all functions used are not async
app.get('/person/:id', (req, res) => {
getIdFromParams(req) // returns a Result
.flatMap(id => personService.findPerson(id))
.map(person => encodePerson(person))
.match({
ok: personJson => res.status(200).send(personJson),
err: failure => httpHandleFailure(res, failure)
});
});
``For more on how to use this library checkout our API documentation.