{"id":19795383,"url":"https://github.com/itemconsulting/enonic-fp","last_synced_at":"2026-06-16T14:32:15.591Z","repository":{"id":57225543,"uuid":"204909991","full_name":"ItemConsulting/enonic-fp","owner":"ItemConsulting","description":"Functional programming helpers for Enonic XP","archived":false,"fork":false,"pushed_at":"2023-07-18T20:25:42.000Z","size":428,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":12,"default_branch":"main","last_synced_at":"2025-01-11T04:49:44.611Z","etag":null,"topics":["enonic","enonic-xp","fp-ts","functional-programming","typescript"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ItemConsulting.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2019-08-28T10:52:05.000Z","updated_at":"2022-02-23T14:05:22.000Z","dependencies_parsed_at":"2024-01-15T17:39:50.430Z","dependency_job_id":"c0ec5c04-bf09-4999-8c07-7e7397edbeae","html_url":"https://github.com/ItemConsulting/enonic-fp","commit_stats":{"total_commits":133,"total_committers":1,"mean_commits":133.0,"dds":0.0,"last_synced_commit":"2b2fa80537cb680b5a89d3758c32b524e863db88"},"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ItemConsulting%2Fenonic-fp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ItemConsulting%2Fenonic-fp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ItemConsulting%2Fenonic-fp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ItemConsulting%2Fenonic-fp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ItemConsulting","download_url":"https://codeload.github.com/ItemConsulting/enonic-fp/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241137476,"owners_count":19916145,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["enonic","enonic-xp","fp-ts","functional-programming","typescript"],"created_at":"2024-11-12T07:16:12.877Z","updated_at":"2026-06-16T14:32:15.561Z","avatar_url":"https://github.com/ItemConsulting.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Enonic FP\n\n[![npm version](https://badge.fury.io/js/enonic-fp.svg)](https://badge.fury.io/js/enonic-fp)\n\nFunctional programming helpers for Enonic XP. This library provides [fp-ts](https://github.com/gcanti/fp-ts) wrappers \naround the Enonic-interfaces provided by [enonic-types](https://github.com/ItemConsulting/enonic-types), which again \nwraps the official standard libraries (in jars).\n\n## Code generation\n\nWe recommend using this library together with the \n[xp-codegen-plugin](https://github.com/ItemConsulting/xp-codegen-plugin) Gradle plugin. *xp-codegen-plugin* will create TypeScript \n`interfaces` for your content-types. Those interfaces will be very useful together with this library.\n\n## Requirements\n\n 1. [Enonic 7 setup with Webpack](https://github.com/enonic/starter-webpack)\n 2. Individual Enonic client libraries installed (this library only contains wrappers around the interfaces) \n\n## Motivation\n\nMost functions in this library wraps the result in an \n[IOEither\u003cEnonicError, A\u003e](https://gcanti.github.io/fp-ts/modules/IOEither.ts.html).\n\nThis gives us two things:\n\n 1. It forces the developer to handle the error case using `fold`\n 2. It allows us to `pipe` the results from one operation into the next using `chain` (or `map`). Chain expects another\n    `IOEither\u003cEnonicError, A\u003e` to be returned. When the first `left\u003cEnonicError\u003e` is returned, the pipe will short \n    circuit to the error case in `fold`.\n\nThis style of programming encourages us to write re-usable functions that we can compose together using `pipe`.\n\n## Usage\n\n### Example 1: Get content by key service\n\nIn this example we have a service that returns Article content – that has a `key` as id – as json. Or if something goes \nwrong, we return an _Internal Server Error_ instead.\n\n```typescript\nimport {fold} from \"fp-ts/IOEither\";\nimport {pipe} from \"fp-ts/pipeable\";\nimport {get as getContent} from \"enonic-fp/content\";\nimport {Article} from \"../../site/content-types/article/article\"; // 1\nimport {internalServerError, ok} from \"enonic-fp/controller\";\n\nexport function get(req: XP.Request): XP.Response { // 2\n  const program = pipe( // 3\n    getContent\u003cArticle\u003e(req.params.key!), // 4\n    fold( // 5\n      internalServerError,\n      ok\n    )\n  );\n\n  return program(); // 6\n}\n```\n\n 1. We import an `interface Article { ... }` generated by \n    [xp-codegen-plugin](https://github.com/ItemConsulting/xp-codegen-plugin).\n 2. We use the imported `Request` and `Response` to control the shape of our controller.\n 3. We use the `pipe` function from *fp-ts* to pipe the result of one function into the next one.\n 4. We use the `get` function from `content` – here renamed `getContent` so it won't collide with the `get` function in \n    the controller – to return some content where the type is `IOEither\u003cEnonicError, Content\u003cArticle\u003e\u003e`.\n 5. The last thing we usually do in a controller is to unpack the `IOEither`. This is done with \n    `fold(handleError, handleSuccess)`. _enonic-fp_ comes with a set of functions that creates an `IO\u003cResponse\u003e` with\n    the data. There are pre-configured functions that can be used in `fold` for some of the most common http status \n    numbers. Like `ok()` and `internalServerError()`.\n 6. We have so far constructed a constant `program` of type `IO\u003cResponse\u003e`, but we have not yet performed a single \n    side effect. It's time to perform those side effects, so we run the `IO` by calling it, and return the `Response` we\n    get back.\n\n\n### Example 2: Delete content by key and publish\n\nIn this example we delete come content by `key`. We are first doing this on the `draft` branch. And then we `publish` it\nto the `master` branch. \n\nWe will return a http error based on the type of error that happened (trough a lookup in the `errorsKeyToStatus` map). \nOr we return a http status `204`, indicating success.\n\n```typescript\nimport {chain, fold} from \"fp-ts/IOEither\";\nimport {pipe} from \"fp-ts/pipeable\";\nimport {publish, remove} from \"enonic-fp/content\";\nimport {run} from \"enonic-fp/context\";\nimport {errorResponse, noContent} from \"enonic-fp/controller\";\n\nfunction del(req: XP.Request): XP.Response {\n  const program = pipe(\n    runOnBranchDraft(\n      remove(req.params.key!) // 1\n    ),\n    chain(() =\u003e publish(req.params.key!)),  // 2\n    fold( // 3\n      errorResponse({ req, i18nPrefix: \"articleErrors\" }), // 4\n      noContent // 5\n    )\n  );\n\n  return program();\n}\n\nexport {del as delete}; // 6\n\nconst runOnBranchDraft = run({ branch: 'draft' }); // 7\n```\n\n 1. We call the `remove` function with the `key` to delete some content. We want to do this on the _draft_ branch, so we \n    wrap the call in  the `runInDraftContext` function that is defined below. \n    Remove returns `IOEither\u003cEnonicError, void\u003e`. If the content didn't exist, it will return an `EnonicError` with of\n    type \"[https://problem.item.no/xp/not-found](https://problem.item.no/xp/not-found)\", that can be handled in the \n    `fold()`.\n 2. We want to publish our change from the _draft_ branch to the _master_ branch. The `publish()` function in \n    _enonic-fp_ has an overload that only takes the `key` as a `string` and defaults to publish from _draft_ to \n    _master_.\n 3. To create our `Response` we call `fold`, where we handle the error and success cases, and return `IO\u003cResponse\u003e`.\n 4. The `errorResponse()` function use the `HttpError.status` field to know which http status number to use on the \n    `Response`. It can optionally take the `Request` and a `i18nPrefix` as parameters. \n      * The `Request` adds the `HttpError.instance` on the return object, and it will check if `req.mode !== 'live'`,\n        and if yes, return more details about the error (this is to prevent exploits based on the error messages).\n      * The usage of `i18nPrefix` is detailed  the [i18n for error messages](#i18n-for-error-messages) chapter. \n 5. Since this is a delete operation we return a \n    [https status 204](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204) on the success case, which means \n    \"no content\".\n 6. Since delete is a keyword in JavaScript and TypeScript, we have to do this hack to return the `delete` function.\n 7. This is a curried version of `ContextLib.run`. It returns a new function – here assigned to the constant \n    `runOnBranchDraft` – that takes an `IO` as parameter (which all the wrapped functions already return as `IOEither`).\n\n### Example 3: Thymeleaf, multiple queries, and http request\n\nIn this example we do three queries. First we look up an article by `key`, then we search for comments related to that \narticle based on the articles key. And then we get a list of open positions in the company, that we want to display on\nthe web page.\n\n```typescript\nimport {sequenceT} from \"fp-ts/Apply\";\nimport {Json} from \"fp-ts/Either\";\nimport {chain, fold, ioEither, IOEither, map} from \"fp-ts/IOEither\";\nimport {pipe} from \"fp-ts/pipeable\";\nimport {Content, QueryResponse} from \"/lib/xp/content\";\nimport {getRenderer} from \"enonic-fp/thymeleaf\";\nimport {EnonicError} from \"enonic-fp/errors\";\nimport {get as getContent, query} from \"enonic-fp/content\";\nimport {bodyAsJson, request} from \"enonic-fp/http\";\nimport {Article} from \"../../site/content-types/article/article\";\nimport {Comment} from \"../../site/content-types/comment/comment\";\nimport {ok, unsafeRenderErrorPage} from \"enonic-fp/controller\";\nimport {tupled} from \"fp-ts/function\";\n\nconst view = resolve('./article.html');\nconst errorView = resolve('../../templates/error.html');\nconst renderer = getRenderer\u003cThymeleafParams\u003e(view); // 1\n\nexport function get(req: XP.Request): XP.Response {\n  const articleId = req.params.key!;\n\n  return pipe(\n    sequenceT(ioEither)( // 2\n      getContent\u003cArticle\u003e(articleId),\n      getCommentsByArticleKey(articleId),\n      getOpenPositionsOverHttp()\n    ),\n    map(tupled(createThymeleafParams)), // 3\n    chain(renderer), // 4\n    fold(\n      unsafeRenderErrorPage(errorView), // 5\n      ok\n    )\n  )();\n}\n\nfunction getCommentsByArticleKey(articleId: string)\n  : IOEither\u003cEnonicError, QueryResponse\u003cComment\u003e\u003e {\n\n  return query\u003cComment\u003e({\n    contentTypes: [\"com.example:comment\"],\n    count: 100,\n    query: `data.articleId = '${articleId}'`\n  });\n}\n\nfunction getOpenPositionsOverHttp(): IOEither\u003cEnonicError, Json\u003e {\n  return pipe(\n    request(\"https://example.com/api/open-positions\"), // 6\n    chain(bodyAsJson)\n  );\n}\n\nfunction createThymeleafParams( // 7\n  article: Content\u003cArticle\u003e,\n  comments: QueryResponse\u003cComment\u003e,\n  openPositions: Json\n): ThymeleafParams {\n  return {\n    id: article._id,\n    data: article.data,\n    comments: comments.hits,\n    openPositions\n  };\n}\n\ninterface ThymeleafParams {\n  readonly id: string;\n  readonly data: Article;\n  readonly comments: ReadonlyArray\u003cComment\u003e;\n  readonly openPositions: Json\n}\n```\n\n 1. `getRenderer()` is a curried version of `ThymeleafLib.render()`. It takes `ThymeleafParams` (defined below) as a \n    type parameter and the `view` as a parameter, and returns a function with this signature:  \n    `(params: ThymeleafParams) =\u003e IOEither\u003cEnonicError, string\u003e`, where the string is the finished rendered page.\n 2. We do a `sequenceT` taking the three `IOEither\u003cEnonicError, A\u003e` as input, and getting an `IOEither` with the results \n    in a tuple (`IOEither\u003cEnonicError, [Content\u003cArticle\u003e, QueryResponse\u003cComment\u003e, Json]\u003e`). The first two are queries in \n    Enonic, and the last one is over http.\n 3. We then `map` over the tuple, using `createThymeleafParams()`. But first we use the `tupled` function on \n    `createThymeleafParams()` to give us _a new version_ of `createThymeleafParams` that takes the parameters as a \n    tuple, instead of as individual arguments. A good rule of thumb is to always use `tupled` together with `sequenceT`!\n 4. We use the `render()` function in a `chain()`, since it returns an `IOEither\u003cEnonicError, string\u003e`.\n 5. If any of the functions in the `pipe` has returned a `Left\u003cEnonicError\u003e`, we need to handle the `EnonicError`. In\n    this case we want to render an error page. The `unsafeRenderErrorPage()` takes the `errorView` (html page) as \n    parameter, which should be a template for `EnonicError`. If the templating succeeds, an `IO\u003cResponse\u003e` is created\n    with the page as the `body`, and with the http status from the `EnonicError`. But if it fails, we just need to let\n    it fail completely and handled by Enonic XP, because we don't want an infinite loop of failing templating.\n 6. We use an overloaded version of `HttpLib.request`, which only takes the url as parameter. We then `pipe` it into the\n    `bodyAsJson` function that parses the json in the `Request.body` and returns an `EnonicError` if it fails. \n 7. The `createThymeleafParams` function gathers all the data and creates one new object that the Thymeleaf-renderer\n    will take as input.\n \n## i18n for error messages\n\n### Custom error messages for every endpoint\n\nThere is support for adding internationalization for error-messages. This is done, when you generate the `Response`\nusing the `errorResponse({ req: Request, i18nPrefix: string})` method.\n\nThe i18n-key to use to look up the message has the following shape: `${i18nPrefix}.title.${typeString}` where \n`typeString` is the last section of `EnonicError.type`. To support every error in *enonic-fp*, `typeString` can only be \none of these:\n\n * bad-request-error\n * not-found\n * internal-server-error\n * missing-id-provider\n * publish-error\n * unpublish-error\n * bad-gateway\n\nIf your `i18nPrefix` is e.g `\"getArticleError\"`, then you can add the following to your *phrases.properties* to get\ncustomized error messages for different endpoints.\n\n```properties\ngetArticleError.title.bad-request-error=Problems with client parameters\ngetArticleError.title.not-found=No Article Found\ngetArticleError.title.internal-server-error=Can not retreive article.\ngetArticleError.title.missing-id-provider=Missing ID Provider.\ngetArticleError.title.publish-error=Unable to publish the article.\ngetArticleError.title.unpublish-error=Unable to unpublish the article\ngetArticleError.title.bad-gateway=Unable to retreive open positions.\n```\n\n### Fallback error messages\n\nWe recommend adding the following (but translated) keys to your *phrases.properties* file, as they will provide backup\nerror messages for all instances where custom error messages have not been specified.\n\n```properties\nerrors.title.bad-request-error=Bad request error\nerrors.title.not-found=Not found\nerrors.title.internal-server-error=Internal Server Error\nerrors.title.missing-id-provider=Missing ID Provider.\nerrors.title.publish-error=Unable to publish data\nerrors.title.unpublish-error=Unable to unpublish data\nerrors.title.bad-gateway=Bad gateway\n```\n\nAlternatively you could use the status number as the `typeString`-part of the key. But this will not be able to separate\ndifferent errors with the same `status` (e.g both *internal-server-error*, *missing-id-provider* and *publish-error* \nhas status = *500*).\n\n```properties\nerrors.title.400=Bad request error\nerrors.title.404=Not found\nerrors.title.500=Internal Server Error\nerrors.title.502=Bad gateway\n```\n\n## Building the project\n\n```bash\nnpm run build\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fitemconsulting%2Fenonic-fp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fitemconsulting%2Fenonic-fp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fitemconsulting%2Fenonic-fp/lists"}