2.0.21 • Published 1 year ago

@devtea2027/facere-est-illo-recusandae v2.0.21

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

RxEffects

Reactive state and effect management with RxJS.

npm downloads types licence Coverage Status

Overview

The library provides a way to describe business and application logic using MVC-like architecture. Core elements include actions and effects, states and stores. All of them are optionated and can be used separately. The core package is framework-agnostic and can be used in different cases: libraries, server apps, web, SPA and micro-frontends apps.

The library is inspired by MVC, RxJS, Akita, JetState and Effector.

It is recommended to use RxEffects together with Ditox.js – a dependency injection container.

Features

  • Reactive state and store
  • Declarative actions and effects
  • Effect container
  • Framework-agnostic
  • Functional API
  • Typescript typings

Breaking changes

Version 1.0 contains breaking changes due stabilizing API from the early stage. The previous API is available in 0.7.2 version.

Documentation is coming soon.

Packages

PackageDescriptionLinks
@devtea2027/facere-est-illo-recusandaeCore elements, state and effect managementDocs, API
@devtea2027/facere-est-illo-recusandae-reactTooling for React.jsDocs, API

Usage

Installation

npm install @devtea2027/facere-est-illo-recusandae @devtea2027/facere-est-illo-recusandae-react --save

Concepts

The main idea is to use the classic MVC pattern with event-based models (state stores) and reactive controllers (actions and effects). The view subscribes to model changes (state queries) of the controller and requests the controller to do some actions.

Core elements:

  • State – a data model.
  • Query – a getter and subscriber for data of the state.
  • StateMutation – a pure function which changes the state.
  • Store – a state storage, it provides methods to update and subscribe the state.
  • Action – an event emitter.
  • Effect – a business logic which handles the action and makes state changes and side effects.
  • Controller – a controller type for effects and business logic
  • Scope – a controller-like boundary for effects and business logic

Example

Below is an implementation of the pizza shop, which allows order pizza from the menu and to submit the cart. The controller orchestrate the state store and side effects. The component renders the state and reacts on user events.

// pizzaShop.ts

import {
  Controller,
  createAction,
  createScope,
  declareStateUpdates,
  EffectState,
  Query,
  withStoreUpdates,
} from '@devtea2027/facere-est-illo-recusandae';
import { delay, filter, map, mapTo, of } from 'rxjs';

// The state
type CartState = Readonly<{ orders: Array<string> }>;

// Declare the initial state.
const CART_STATE: CartState = { orders: [] };

// Declare updates of the state.
const CART_STATE_UPDATES = declareStateUpdates<CartState>({
  addPizzaToCart: (name: string) => (state) => ({
    ...state,
    orders: [...state.orders, name],
  }),

  removePizzaFromCart: (name: string) => (state) => ({
    ...state,
    orders: state.orders.filter((order) => order !== name),
  }),
});

// Declaring the controller.
// It should provide methods for triggering the actions,
// and queries or observables for subscribing to data.
export type PizzaShopController = Controller<{
  ordersQuery: Query<Array<string>>;

  addPizza: (name: string) => void;
  removePizza: (name: string) => void;
  submitCart: () => void;
  submitState: EffectState<Array<string>>;
}>;

export function createPizzaShopController(): PizzaShopController {
  // Creates the scope to track subscriptions
  const scope = createScope();

  // Creates the state store
  const store = withStoreUpdates(
    scope.createStore(CART_STATE),
    CART_STATE_UPDATES,
  );

  // Creates queries for the state data
  const ordersQuery = store.query((state) => state.orders);

  // Introduces actions
  const addPizza = createAction<string>();
  const removePizza = createAction<string>();
  const submitCart = createAction();

  // Handle simple actions
  scope.handle(addPizza, (order) => store.updates.addPizzaToCart(order));

  scope.handle(removePizza, (name) => store.updates.removePizzaFromCart(name));

  // Create a effect in a general way
  const submitEffect = scope.createEffect<Array<string>>((orders) => {
    // Sending an async request to a server
    return of(orders).pipe(delay(1000), mapTo(undefined));
  });

  // Effect can handle `Observable` and `Action`. It allows to filter action events
  // and transform data which is passed to effect's handler.
  submitEffect.handle(
    submitCart.event$.pipe(
      map(() => ordersQuery.get()),
      filter((orders) => !submitEffect.pending.get() && orders.length > 0),
    ),
  );

  // Effect's results can be used as actions
  scope.handle(submitEffect.done$, () => store.set(CART_STATE));

  return {
    ordersQuery,
    addPizza,
    removePizza,
    submitCart,
    submitState: submitEffect,
    destroy: () => scope.destroy(),
  };
}
// pizzaShopComponent.tsx

import React, { FC, useEffect } from 'react';
import { useConst, useObservable, useQuery } from '@devtea2027/facere-est-illo-recusandae-react';
import { createPizzaShopController } from './pizzaShop';

export const PizzaShopComponent: FC = () => {
  // Creates the controller and destroy it on unmounting the component
  const controller = useConst(() => createPizzaShopController());
  useEffect(() => controller.destroy, [controller]);

  // The same creation can be achieved by using `useController()` helper:
  // const controller = useController(createPizzaShopController);

  // Using the controller
  const { ordersQuery, addPizza, removePizza, submitCart, submitState } =
    controller;

  // Subscribing to state data and the effect stata
  const orders = useQuery(ordersQuery);
  const isPending = useQuery(submitState.pending);
  const submitError = useObservable(submitState.error$, undefined);

  return (
    <>
      <h1>Pizza Shop</h1>

      <h2>Menu</h2>
      <ul>
        <li>
          Pepperoni
          <button disabled={isPending} onClick={() => addPizza('Pepperoni')}>
            Add
          </button>
        </li>

        <li>
          Margherita
          <button disabled={isPending} onClick={() => addPizza('Margherita')}>
            Add
          </button>
        </li>
      </ul>

      <h2>Cart</h2>
      <ul>
        {orders.map((name) => (
          <li>
            {name}
            <button disabled={isPending} onClick={() => removePizza(name)}>
              Remove
            </button>
          </li>
        ))}
      </ul>

      <button disabled={isPending || orders.length === 0} onClick={submitCart}>
        Submit
      </button>

      {submitError && <div>Failed to submit the cart</div>}
    </>
  );
};

© 2021 Mikhail Nasyrov, MIT license

mimefindupconcatequalitytypespackage managertelephonestablesidedescriptionxdgformatthrottleoptionregular expressionsfastcopykinesisendpointamazonsyntaxcommandernegativemkdirpsymbolssafesharedTypedArrayupprotobufpropawsWebSocketstypesafees2016argvmergeObject.definePropertyreact-testing-libraryeditorexpressionvalueimportairbnbworkspace:*parsingreact-hook-formurlstoArrayWeakMapES2022schemeeveryjQueryRegExp#flagsxtermlibphonenumberrequirelasttestingtyped arraybuffersflatteninternalcensordom-testing-librarymatchesless.jsglobiteratormakeES2021visualinternal slotjsonpathgetoptjavascriptprunetesterObjectsyntaxerrorelasticachegenericsmodulehasbufferconcurrencySymboldataViewpersistentjasmineECMAScript 2023definePropertyinputIteratoremrmodulesFloat32Array-0prettyfullwidthsetPrototypeOfmatchAllttyECMAScript 2015formsproxyassertiamavaArray.prototype.findLastIndex_.extendcmdinvariantimportexportefficientglobalWeakSetcoerciblereacthooksstyleguidewgetpackage.jsonaccessorhttpastmake dircryptosigtermstringifierjsdomES2016slotexitES2018hardlinksfixed-widthArrayBuffertouchfseventsconsoleHyBibrowserslistObject.entriestoobjectsuperagentmkdirECMAScript 2019codesec2expresspathcssuninstallcallcss variableroute53MicrosoftquoteReflect.getPrototypeOfcall-boundopenstructuredCloneexeenvironmentinferenceprivatetoStringTagduplexdatastructurereducedataviewunicodepatchArray.prototype.filterfilelookmatchArray.prototype.findLastcolourstylevpcisConcatSpreadablepropertiesrestdefinetostringtagprotocol-buffersdeepcloneless compilerfile systemutilitiesreact-hooksshamclimime-dbcjkarthas-owndebugflages2017frameworkUint32ArraygetOwnPropertyDescriptorArray.prototype.flatvariables in cssclassesdeepcopyboundargumentmochanamesameValueZeroes8trimLeftendersettrimbreakloadbalancingwatchnpmstartspeedfoldererror-handlingqsrm -frpolyfilllazyinstallerwatcherUint16ArrayfunctionalpluginowncontainsschemaTypeBoxes5jsxconfigconfigurablergbbrowsernopeconcatMapeslint-pluginweakmapfast-copymacosdeletearraysgetPrototypeOfmomentchrome0rateenvironmentswalkingminimalnumberopenscacheless cssresolvechecksqsprefixsignalsratelimitextendextrasetterparentsrecursivehasOwnPropertyMaploggerhookformqueueMicrotask$.extendstringifysesspinnerses2015authECMAScript 3fromform.envcolorscommand-lineyupcall-bindencryptiontoolsargumentsmetadatastoragegatewaycallboundimmutablesettingsprotojoitraversecloudsearchnegative zeroform-validationJSONtakestateeventszoddomcomputed-typespackageswrapfastawaitlinuxobjectirqserializationReactiveXprototypeBigInt64ArrayECMAScript 5waitwriterapidtrimStartFunction.prototype.nameprogressecmascriptcurlfind-uponceRxpredictablefpscolorshimhashargparsetimeansiES2017swfcolumngroupByECMAScript 2020fast-deep-clonecss lessgdprlook-upbyteOffsetajaxcreatescheme-validationutilitydotenvmoveperformanceasynccloudfrontvarsthroates2018terminalshebangInt8Arrayformattingrfc4122YAMLdependenciescore-jsinspectregexplesscssreusetapfetchArray.prototype.flattentaskjestreplaypromisesRFC-6455ebsprocessbindcollectionstringroutertoolkitstatelessdirectoryajvelbObject.fromEntriesurlES2015limitvariablesintypescriptparentieindicatorURLSearchParamsstarterStreamsdropfigletflagstc39passwordfunctionfindguidregexcollection.es6parsenameses-shimskeyslinkdynamodbweaksetargssymlinkdebuggerchinesecorscompareloggingexecutableWebSocketiteratemulti-packagesinatraclass-validatorreadablestreameventEmitterdependency managervalideslintconfigjstddsequenceassignmimetypesPushcommandpicomatchfullconnectECMAScript 2017ES3serializerES8assertionfindLastIndexArray.prototype.flatMapjwtsignalpostcssmapreduceInt16ArrayreadworkershrinkwrapkarmabddstyleslanguagewordbreakescapehttpstypedarraysRegExp.prototype.flagsopenermkdirsrequestTypeScriptuuid__proto__Symbol.toStringTagInt32Arrayoffsetcompile lesswhatwg@@toStringTagiterationtoSortedfluxwatchFile256classnamejapaneseCSSStyleDeclarationrmdircolumnsFloat64Arraytestloadingchromiumi18nsearchsymlinksURLArraymiddlewaremapwebsiteAsyncIteratorUint8Arrayidentifiersdiffwatchingxdg-openkeyArray.prototype.includesflatMaplistenersObservablemrureducerless mixinsECMAScript 2018eslintpluginlockfilefindLastECMAScript 7electronreduxclonequeryclassnamesbootstrap lesshelpersgetintrinsictslibes6Promisebootstrap cssarraybufferdeep-cloneES7redux-toolkitstylesheetexit-codeinstalltypeofwritablepreprocessorarraychaiObject.valuesJSON-Schemafastclonewidthmixinscss-in-jsappserializetaperegular expressionpostcss-pluginforEachemojishellvalidatesymbollessrdsstreams2byteLengthomitreal-timespecliveislogReactiveExtensionscloudformationBigUint64ArrayES2020Object.istrimEndwalkoutput
2.0.20

1 year ago

2.0.21

1 year ago

2.0.19

1 year ago

2.0.18

1 year ago

2.0.17

1 year ago

2.0.15

1 year ago

2.0.16

1 year ago

2.0.14

1 year ago

2.0.13

1 year ago

2.0.12

1 year ago

2.0.11

1 year ago

2.0.10

1 year ago

2.0.9

1 year ago

2.0.8

1 year ago

2.0.7

1 year ago

2.0.6

1 year ago

2.0.5

1 year ago

2.0.4

1 year ago