Getting started

Tutorial

Follow this tutorial to grasp the core concepts of Expry and how it has to be used.


Expry

The main function of this package is the expry function, and it is the one responsible to evaluate the expressions we define. It receives the following arguments:

  • expression: The expression we want to evaluate.

  • variables: The variables we want to use in the expression.

import { expry, Value, Variables } from "expry";

const expression: Value = {
  name: { $concat: ["$name", " ", "$surname"] },
  adult: { $gte: ["$age", 18] },
};

const variables: Variables = {
  name: "John",
  surname: "Doe",
  age: 21,
};

/**
 * {
 *   "name": "John Doe",
 *   "adult": true
 * }
 */
console.log(expry(expression, variables));

The expression that we pass is a value that can be of any type, and in that expression we can reference the variables and use a lot of operators.

If we wanted, we could choose not to pass the variables, since the expression is the only argument that is required.

import { expry, Value } from "expry";

const expression: Value = {
  name: { $concat: ["John", " ", "Doe"] },
  adult: { $gte: [21, 18] },
};

/**
 * {
 *   "name": "John Doe",
 *   "adult": true
 * }
 */
console.log(expry(expression));

Operators

There are many different kinds of operators available, and they are used by creating objects with a key that starts with $.

import { expry, Value } from "expry";

const expression: Value = {
  $add: [1, 2],
};

/**
 * 3
 */
console.log(expry(expression));

Variables

The variables that we pass to the expry function is an object with key-value pairs in which each key corresponds to a variable.

To reference them we have to define strings that start with $.

import { expry, Value, Variables } from "expry";

const expression: Value = {
  $add: ["$a", "$b"],
};

const variables: Variables = {
  a: 1,
  b: 2,
};

/**
 * 3
 */
console.log(expry(expression, variables));

Object variables

When a variable is an object, we can access the properties using the dot notation.

import { expry, Value, Variables } from "expry";

const expression: Value = {
  $add: ["$numbers.a", "$numbers.b"],
};

const variables: Variables = {
  numbers: { a: 1, b: 2 },
};

/**
 * 3
 */
console.log(expry(expression, variables));

Array variables

When a variable is an array, we can access the items using the dot notation.

import { expry, Value, Variables } from "expry";

const expression: Value = {
  $add: ["$numbers.0", "$numbers.1"],
};

const variables: Variables = {
  numbers: [1, 2],
};

/**
 * 3
 */
console.log(expry(expression, variables));

Hash

When you want to treat the $ as a normal character in strings and object properties, you have to use the # character.

import { expry, Value } from "expry";

const expression: Value = {
  "#$add": ["#$a", "#$b"],
};

/**
 * { '$add': [ '$a', '$b' ] }
 */
console.log(expry(expression));