Skip to content

Latest commit

 

History

History

morphix

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

Morphix

Micro templating with function pipes support

npm version size ossf scorecard license

🚀 Getting Started

This package is available in the Node Package Repository and can be easily installed with npm or yarn

$ npm i @sigyn/morphix
# or
$ yarn add @sigyn/morphix

📚 Usage

import { morphix } from "@sigyn/morphix";

await morphix("Hello {name | capitalize}", { name: "john" });

Important

morphix() is asynchrone because it supports async functions

🌐 API

morphix

async function morphix(
  template: string,
  data: Record<string, any> | unknown[],
  options: MorphixOptions = {}
): Promise<string>

template Type: string

Text with placeholders for data properties.

data Type: object | unknown[]

Data to interpolate into template.

The keys should be a valid JS identifier or number (a-z, A-Z, 0-9).

Options

type MorphixFunction = (value: string) => Promise<string> | string;

export interface MorphixOptions {
  /**
   * Performs arbitrary operations for each interpolation.
   * If the returned value is undefined, the behavior depends on the ignoreMissing option.
   * Otherwise, the returned value is converted to a string and embedded into the template.
   */
  transform?: (data: { value: unknown; key: string }) => unknown;
  /**
   * By default, Morphix throws a MissingValueError when a placeholder resolves to undefined.
   * If this option is set to true, it simply ignores the unresolved placeholder and leaves it as is.
   *
   * @default false
   */
  ignoreMissing?: boolean;
  customFunctions?: Record<string, MorphixFunction>;
}

Note

MissingValueError is exported, which is useful for instance and type checking.

📦 Functions

capitalize

Capitalize the first letter.

dnsresolve

Retrieve host of a given IP. It uses dns.reverse.

If it fails to retrieve the host, it returns the ip instead.

Adding custom functions

Morphix lets you inject your own custom functions.

import { morphix } from "@sigyn/morphix";
import assert from "node:assert";

const transformedData = await morphix(
  "{ data | lower }",
  { data: "HELLO WORLD" },
  {
    customFunctions: {
      lower: (value) => value.toLowerCase()
    }
  }
);
assert.strictEqual(
  transformedData,
  "hello world"
);

Credits

This package is heavily inspired by pupa. Morphix is a fork that includes function support and does not support HTML escape.

License

MIT