@x/expressions
TypeScript icon, indicating that this package has built-in type declarations

0.7.14 • Public • Published

@x/expressions

Composable, portable and extensible reactive expressions.

  • Compose complete object models from any stream of events.
  • Serialise expressions for transport or persistence.
  • Create reusable partial expressions.

Installation

yarn add @x/expressions

Usage

The @x/expressions API is heavily inspired by ReactiveX but with a focus on reuse and extensibility, along with providing the ability to serialize expressions. Complete, reactive models can be composed from messages published through the expression, then serialized and transmitted over a network or persisted to a data store.

@x/socket allows you to create flexible, secured APIs that seamlessly distribute your expressions to consumers over any socket. For a complete system to manage the distribution and persistence of your expressions and models, check out Unify.

A Simple Example

The following model could be applied to construct a collection of reviews from a stream of events:

const reviews = o => o.groupBy(
  'reviewId',
  o => o.assign({
    'reviewId': o => o.select('reviewId'),
    '...details': o => o.topic('review').accumulate('details'),
    'likes': o => o.topic('like').groupBy(
      'userId',
      o => o.select('liked'),
      o => o.where(x => x.liked === false)
    ).count()
  }),
  o => o.topic('report').count().where(x => x > 1)
)

This expression creates a collection of unique reviews published using the review topic. The model includes a count of unique user likes that can be removed. Reviews are removed from the collection if more than one corresponding report messages are published.

To create a simple message source:

const { subject } = require('@x/expressions')

const source = subject()
const result = reviews(source)

source.publish({ topic: 'review', reviewId: 1, details: { text: 'Awesome!' } })
source.publish({ topic: 'review', reviewId: 2, details: { text: 'It is amazing!' } })
source.publish({ topic: 'review', reviewId: 3, details: { text: '^%$#!!1!' } })
source.publish({ topic: 'like', reviewId: 1, userId: 1, liked: true })
source.publish({ topic: 'like', reviewId: 2, userId: 1, liked: true })
source.publish({ topic: 'like', reviewId: 1, userId: 2, liked: true })
source.publish({ topic: 'report', reviewId: 3, userId: 1 })
source.publish({ topic: 'report', reviewId: 3, userId: 2 })

console.log(result())
/*
[
  { reviewId: 1, text: 'Awesome!', likes: 2 },
  { reviewId: 2, text: 'It is amazing!', likes: 1 }
]
*/

Disconnecting Expressions

Calling disconnect on an expression observable will stop the returned expression from receiving updates. If there are other subscribers to any part of the expression tree, they will remain connected. If not, the expression is disconnected from the root source.

Serializing Expressions

Serializing expressions to a plain Javascript object is as simple as calling the serialize function from the top level library export:

const { serialize } = require('@x/expressions')

const serializationInfo = serialize(result)

console.log(serializationInfo)
/*
{
  definition: { ... }
  state: { ... }
}
*/

Deserializing is as simple as the reverse, but requires that the result be attached to an existing observable:

const { deserialize, subject } = require('@x/expressions')

const source = subject()
const deserialzed = deserialize(source, serializationInfo)

If the expression definition is already known, you can deserialize with just the state. The definition can be extracted from an expression using the extractDefinition function:

const { extractDefinition, deserialize, subject } = require('@x/expressions')

const source = subject()
const definition = extractDefinition(reviews)
const state = serializationInfo.state
const deserialized = deserialize(source, { definition, state })

Creating Reusable Expressions, a.k.a vocabulary

Where you have the same logic being repeated multiple times in several expressions, you can create vocabulary and re-use that piece of vocabulary within expressions:

const { addVocabulary } = require('@x/expressions')

addVocabulary('likes',
  o => o.topic('like').groupBy('userId',
    o => o.select('liked'),
    o => o.where(x => x.liked === false)
  )
)
const reviews = o => o.groupBy('reviewId',
  o => o.compose(
    o => o.select('reviewId'),
    o => o.topic('review').accumulate('details'),
    o => o.likes().count(),
    (reviewId, review, likes) => ({ reviewId, ...review, likes })
  ),
  o => o.topic('report').count().where(x => x > 1)
)

Multiple pieces of vocabulary can be added in the same call to addVocabulary by passing an object with corresponding vocabulary entries.

Handling Errors in Expressions

The @x/expressions library builds on the error handling ability of @x/observable by attaching a property named errorObservable to expression observables. This property contains an observable that emits details about any errors that occur in any operator that is part of the expression.

The object emitted contains two properties - frames that contains an array of the frames that were executed up to the point of the error, and error that contains the error object itself.

const { subject } = require('@x/expressions')

const source = subject()
const expression = source.where(x => x + nonExistentVariable).map(x => x * 2)
expression.errorObservable.subscribe(error => console.log(error))
source.publish(2)  // logs `{ frames, error }`

Documentation

For examples of more complex expressions that use grouping and composing operators, check out the expressions guide on the Unify documentation site.

API references are available for stream operators and aggregate operators. You can find documentation for the @x/expressions API functions here.

For documentation on the entire Unify platform, please visit the documentation site.

License

The MIT License (MIT)

Copyright © 2022 Dale Anderson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Readme

Keywords

none

Package Sidebar

Install

npm i @x/expressions

Weekly Downloads

99

Version

0.7.14

License

MIT

Unpacked Size

65.4 kB

Total Files

60

Last publish

Collaborators

  • danderson00