Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/itemconsulting/enonic-fp

Functional programming helpers for Enonic XP
https://github.com/itemconsulting/enonic-fp

enonic enonic-xp fp-ts functional-programming typescript

Last synced: about 2 months ago
JSON representation

Functional programming helpers for Enonic XP

Awesome Lists containing this project

README

        

# Enonic FP

[![npm version](https://badge.fury.io/js/enonic-fp.svg)](https://badge.fury.io/js/enonic-fp)

Functional programming helpers for Enonic XP. This library provides [fp-ts](https://github.com/gcanti/fp-ts) wrappers
around the Enonic-interfaces provided by [enonic-types](https://github.com/ItemConsulting/enonic-types), which again
wraps the official standard libraries (in jars).

## Code generation

We recommend using this library together with the
[xp-codegen-plugin](https://github.com/ItemConsulting/xp-codegen-plugin) Gradle plugin. *xp-codegen-plugin* will create TypeScript
`interfaces` for your content-types. Those interfaces will be very useful together with this library.

## Requirements

1. [Enonic 7 setup with Webpack](https://github.com/enonic/starter-webpack)
2. Individual Enonic client libraries installed (this library only contains wrappers around the interfaces)

## Motivation

Most functions in this library wraps the result in an
[IOEither](https://gcanti.github.io/fp-ts/modules/IOEither.ts.html).

This gives us two things:

1. It forces the developer to handle the error case using `fold`
2. It allows us to `pipe` the results from one operation into the next using `chain` (or `map`). Chain expects another
`IOEither` to be returned. When the first `left` is returned, the pipe will short
circuit to the error case in `fold`.

This style of programming encourages us to write re-usable functions that we can compose together using `pipe`.

## Usage

### Example 1: Get content by key service

In this example we have a service that returns Article content – that has a `key` as id – as json. Or if something goes
wrong, we return an _Internal Server Error_ instead.

```typescript
import {fold} from "fp-ts/IOEither";
import {pipe} from "fp-ts/pipeable";
import {get as getContent} from "enonic-fp/content";
import {Article} from "../../site/content-types/article/article"; // 1
import {internalServerError, ok} from "enonic-fp/controller";

export function get(req: XP.Request): XP.Response { // 2
const program = pipe( // 3
getContent(req.params.key!), // 4
fold( // 5
internalServerError,
ok
)
);

return program(); // 6
}
```

1. We import an `interface Article { ... }` generated by
[xp-codegen-plugin](https://github.com/ItemConsulting/xp-codegen-plugin).
2. We use the imported `Request` and `Response` to control the shape of our controller.
3. We use the `pipe` function from *fp-ts* to pipe the result of one function into the next one.
4. We use the `get` function from `content` – here renamed `getContent` so it won't collide with the `get` function in
the controller – to return some content where the type is `IOEither>`.
5. The last thing we usually do in a controller is to unpack the `IOEither`. This is done with
`fold(handleError, handleSuccess)`. _enonic-fp_ comes with a set of functions that creates an `IO` with
the data. There are pre-configured functions that can be used in `fold` for some of the most common http status
numbers. Like `ok()` and `internalServerError()`.
6. We have so far constructed a constant `program` of type `IO`, but we have not yet performed a single
side effect. It's time to perform those side effects, so we run the `IO` by calling it, and return the `Response` we
get back.

### Example 2: Delete content by key and publish

In this example we delete come content by `key`. We are first doing this on the `draft` branch. And then we `publish` it
to the `master` branch.

We will return a http error based on the type of error that happened (trough a lookup in the `errorsKeyToStatus` map).
Or we return a http status `204`, indicating success.

```typescript
import {chain, fold} from "fp-ts/IOEither";
import {pipe} from "fp-ts/pipeable";
import {publish, remove} from "enonic-fp/content";
import {run} from "enonic-fp/context";
import {errorResponse, noContent} from "enonic-fp/controller";

function del(req: XP.Request): XP.Response {
const program = pipe(
runOnBranchDraft(
remove(req.params.key!) // 1
),
chain(() => publish(req.params.key!)), // 2
fold( // 3
errorResponse({ req, i18nPrefix: "articleErrors" }), // 4
noContent // 5
)
);

return program();
}

export {del as delete}; // 6

const runOnBranchDraft = run({ branch: 'draft' }); // 7
```

1. We call the `remove` function with the `key` to delete some content. We want to do this on the _draft_ branch, so we
wrap the call in the `runInDraftContext` function that is defined below.
Remove returns `IOEither`. If the content didn't exist, it will return an `EnonicError` with of
type "[https://problem.item.no/xp/not-found](https://problem.item.no/xp/not-found)", that can be handled in the
`fold()`.
2. We want to publish our change from the _draft_ branch to the _master_ branch. The `publish()` function in
_enonic-fp_ has an overload that only takes the `key` as a `string` and defaults to publish from _draft_ to
_master_.
3. To create our `Response` we call `fold`, where we handle the error and success cases, and return `IO`.
4. The `errorResponse()` function use the `HttpError.status` field to know which http status number to use on the
`Response`. It can optionally take the `Request` and a `i18nPrefix` as parameters.
* The `Request` adds the `HttpError.instance` on the return object, and it will check if `req.mode !== 'live'`,
and if yes, return more details about the error (this is to prevent exploits based on the error messages).
* The usage of `i18nPrefix` is detailed the [i18n for error messages](#i18n-for-error-messages) chapter.
5. Since this is a delete operation we return a
[https status 204](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204) on the success case, which means
"no content".
6. Since delete is a keyword in JavaScript and TypeScript, we have to do this hack to return the `delete` function.
7. This is a curried version of `ContextLib.run`. It returns a new function – here assigned to the constant
`runOnBranchDraft` – that takes an `IO` as parameter (which all the wrapped functions already return as `IOEither`).

### Example 3: Thymeleaf, multiple queries, and http request

In this example we do three queries. First we look up an article by `key`, then we search for comments related to that
article based on the articles key. And then we get a list of open positions in the company, that we want to display on
the web page.

```typescript
import {sequenceT} from "fp-ts/Apply";
import {Json} from "fp-ts/Either";
import {chain, fold, ioEither, IOEither, map} from "fp-ts/IOEither";
import {pipe} from "fp-ts/pipeable";
import {Content, QueryResponse} from "/lib/xp/content";
import {getRenderer} from "enonic-fp/thymeleaf";
import {EnonicError} from "enonic-fp/errors";
import {get as getContent, query} from "enonic-fp/content";
import {bodyAsJson, request} from "enonic-fp/http";
import {Article} from "../../site/content-types/article/article";
import {Comment} from "../../site/content-types/comment/comment";
import {ok, unsafeRenderErrorPage} from "enonic-fp/controller";
import {tupled} from "fp-ts/function";

const view = resolve('./article.html');
const errorView = resolve('../../templates/error.html');
const renderer = getRenderer(view); // 1

export function get(req: XP.Request): XP.Response {
const articleId = req.params.key!;

return pipe(
sequenceT(ioEither)( // 2
getContent(articleId),
getCommentsByArticleKey(articleId),
getOpenPositionsOverHttp()
),
map(tupled(createThymeleafParams)), // 3
chain(renderer), // 4
fold(
unsafeRenderErrorPage(errorView), // 5
ok
)
)();
}

function getCommentsByArticleKey(articleId: string)
: IOEither> {

return query({
contentTypes: ["com.example:comment"],
count: 100,
query: `data.articleId = '${articleId}'`
});
}

function getOpenPositionsOverHttp(): IOEither {
return pipe(
request("https://example.com/api/open-positions"), // 6
chain(bodyAsJson)
);
}

function createThymeleafParams( // 7
article: Content,
comments: QueryResponse,
openPositions: Json
): ThymeleafParams {
return {
id: article._id,
data: article.data,
comments: comments.hits,
openPositions
};
}

interface ThymeleafParams {
readonly id: string;
readonly data: Article;
readonly comments: ReadonlyArray;
readonly openPositions: Json
}
```

1. `getRenderer()` is a curried version of `ThymeleafLib.render()`. It takes `ThymeleafParams` (defined below) as a
type parameter and the `view` as a parameter, and returns a function with this signature:
`(params: ThymeleafParams) => IOEither`, where the string is the finished rendered page.
2. We do a `sequenceT` taking the three `IOEither` as input, and getting an `IOEither` with the results
in a tuple (`IOEither, QueryResponse, Json]>`). The first two are queries in
Enonic, and the last one is over http.
3. We then `map` over the tuple, using `createThymeleafParams()`. But first we use the `tupled` function on
`createThymeleafParams()` to give us _a new version_ of `createThymeleafParams` that takes the parameters as a
tuple, instead of as individual arguments. A good rule of thumb is to always use `tupled` together with `sequenceT`!
4. We use the `render()` function in a `chain()`, since it returns an `IOEither`.
5. If any of the functions in the `pipe` has returned a `Left`, we need to handle the `EnonicError`. In
this case we want to render an error page. The `unsafeRenderErrorPage()` takes the `errorView` (html page) as
parameter, which should be a template for `EnonicError`. If the templating succeeds, an `IO` is created
with the page as the `body`, and with the http status from the `EnonicError`. But if it fails, we just need to let
it fail completely and handled by Enonic XP, because we don't want an infinite loop of failing templating.
6. We use an overloaded version of `HttpLib.request`, which only takes the url as parameter. We then `pipe` it into the
`bodyAsJson` function that parses the json in the `Request.body` and returns an `EnonicError` if it fails.
7. The `createThymeleafParams` function gathers all the data and creates one new object that the Thymeleaf-renderer
will take as input.

## i18n for error messages

### Custom error messages for every endpoint

There is support for adding internationalization for error-messages. This is done, when you generate the `Response`
using the `errorResponse({ req: Request, i18nPrefix: string})` method.

The i18n-key to use to look up the message has the following shape: `${i18nPrefix}.title.${typeString}` where
`typeString` is the last section of `EnonicError.type`. To support every error in *enonic-fp*, `typeString` can only be
one of these:

* bad-request-error
* not-found
* internal-server-error
* missing-id-provider
* publish-error
* unpublish-error
* bad-gateway

If your `i18nPrefix` is e.g `"getArticleError"`, then you can add the following to your *phrases.properties* to get
customized error messages for different endpoints.

```properties
getArticleError.title.bad-request-error=Problems with client parameters
getArticleError.title.not-found=No Article Found
getArticleError.title.internal-server-error=Can not retreive article.
getArticleError.title.missing-id-provider=Missing ID Provider.
getArticleError.title.publish-error=Unable to publish the article.
getArticleError.title.unpublish-error=Unable to unpublish the article
getArticleError.title.bad-gateway=Unable to retreive open positions.
```

### Fallback error messages

We recommend adding the following (but translated) keys to your *phrases.properties* file, as they will provide backup
error messages for all instances where custom error messages have not been specified.

```properties
errors.title.bad-request-error=Bad request error
errors.title.not-found=Not found
errors.title.internal-server-error=Internal Server Error
errors.title.missing-id-provider=Missing ID Provider.
errors.title.publish-error=Unable to publish data
errors.title.unpublish-error=Unable to unpublish data
errors.title.bad-gateway=Bad gateway
```

Alternatively you could use the status number as the `typeString`-part of the key. But this will not be able to separate
different errors with the same `status` (e.g both *internal-server-error*, *missing-id-provider* and *publish-error*
has status = *500*).

```properties
errors.title.400=Bad request error
errors.title.404=Not found
errors.title.500=Internal Server Error
errors.title.502=Bad gateway
```

## Building the project

```bash
npm run build
```