2.3.5 • Published 22 days ago

rx-store-core v2.3.5

Weekly downloads
-
License
ISC
Repository
github
Last release
22 days ago

RxStore Core

A Rxjs based Type-safe state management tool (JavaScript Environment Independent)

Install

npm install rx-store-core

Use a Normal Reactive Store (NRS):

Import

import { NRS } from "rx-store-core";

Overview

const initiator = {
  height: () => 0, // this is a data default value factory
  id: () => "",
  complex: () => ({
    uid: "",
    name: "",
  }),
  keys: (): string[] => [], // you can define function return type to achieve type safety when we observe it
  groups: (): Array<{ num: 0, score: 0, alias: "" }> => [],
}

type Initiator = keyof initiator;

const {
  /* @params {[key in keyof Initiator]: Initiator[key]} */
  /* @Return NRS instance */
  /* @Description  the only way to trigger data change */
  setState,

  /* @params 
      key: K keyof Initiator,
      observer: (result: ReturnType<S[K]>) => void,
      comparator?: (prev: ReturnType<S[K]>, next: ReturnType<S[K]>) => boolean */
  /* @Return Destructor function */
  /* @Description  observe single data */
  observe,

  /* @params 
    key: (K keyof Initiator)[]
    observer: (result: { [K in keyof Initiator]: ReturnType<S[K]> }) => void,
    comparator?: (
      prev: { [K in keyof Initiator]: ReturnType<Initiator[K]> },
      next: { [K in keyof Initiator]: ReturnType<Initiator[K]> }
    ) => boolean */
  /* @Return Destructor function */
  /* @Description  observe all stored data */
  observeAll, 

  /* @params 
    observer: (result: { [K in keyof Initiator]: ReturnType<S[K]> }) => void,
    comparator?: (
      prev: { [K in keyof Initiator]: ReturnType<Initiator[K]> },
      next: { [K in keyof Initiator]: ReturnType<Initiator[K]> }
    ) => boolean */
  /* @Return Destructor function */
  /* @Description  observe multiple data changes */
  observeMultiple, 

  /* @params 
    {
      computation: Computation<R, Initiator>;
      comparator?: Comparator<{
        [K in keyof Initiator]: ReturnType<S[K]>;
      }>;
    } 
    */
  /* @Return Computed instance */
  /* @Description  create a observable computation form stored data */
  withComputation, 
  createDispatch, // create a dispatch function with a Reducer, to handle complex Reactive data management

  /* @params 
    key: (K keyof Initiator) */
  /* @Return Initiator[K] */
  /* @Description  get a non-reactive data, it is mutable, please try to avoid to change it directly */
  getState,

  /* @params 
    key: (K keyof Initiator) */
  /* @Return Initiator[K] */
  /* @Description  get a cloned non-reactive data, by default, it is shallow cloned, you can define a custom clone function when create a NRS instance */
  getClonedState,

  /* @Return Observable<{ [K in keyof Initiator]: ReturnType<Initiator[K]>; }> */
  /* @Description  get a RxJS Observable object containing all stored data, you can add any mid wares into its pipe function */
  getDataSource,

  /* @params 
    key: (K keyof Initiator) */
  /* @Return Observable<ReturnType<Initiator[K]>> */
  /* @Description  get a RxJS Observable object containing one single stored data */
  getSingleSource, 

  /* @params 
    key: (K keyof Initiator) */
  /* 
    @Return 
    {
        success: true;
        immutable: Collection<keyof ReturnType<S[K]>, ReturnType<S[K]>[keyof ReturnType<S[K]>]>;
    } | {
        success: false;
        immutable: ReturnType<S[K]>;
    }
  */  
  /* @Description  try to parse a normal JS object into a Immutable object */
  getImmutableState,

  /* @Return { [K in keyof S]: ReturnType<S[K]>; } */
  /* @Description  get a mutable object containing all stored data, avoid to change it directly */
  getStateAll,

  /* @params 
    keys: (K keyof Partial<Initiator>)[]
  /* @Return { K in (K keyof Partial<Initiator>)[][number]: Initiator[K]} */
  /* @Description  get multiple stored non-reactive data, please try to avoid to change it directly */
  getStates, 

  /* @params 
    key: (K keyof Initiator)
  /* @Return NRS instance */
  /* @Description  reset a stored data to its default value */
  reset,

  /* @params 
    keys: (K keyof Partial<Initiator>)[]
  /* @Return { K in (K keyof Partial<Initiator>)[][number]: Initiator[K]} */
  /* @Description  reset multiple stored data to its default value */
  resetMultiple,

  /* @params 
    keys: (K keyof Initiator)[]
  /* @Return { K in (K keyof Initiator)[][number]: Initiator[K]} */
  /* @Description  reset all stored data to its default value */
  resetAll,

  /* @params 
    key: (K keyof Initiator)
  /* @Return Initiator[K] */
  /* @Description  get default value of a non-reactive data */
  getDefault,

  /* @Return { [K in keyof S]: ReturnType<S[K]>; } */
  /* @Description  get all default values of all non-reactive data, avoid to change it directly */
  getDefaultAll,

  /* @params 
    keys: (K keyof Partial<Initiator>)[]
  /* @Return { K in (K keyof Partial<Initiator>)[][number]: Initiator[K]} */
  /* @Description  get multiple default values of multiple non-reactive data */
  getDefaults,
} = NRS(initiator);

Define stored data

example:

const { observe, observeMultiple, observeAll, getDefault } = NRS({
  complex: () => ({
    uid: "",
    name: "",
  }),
  height: () => 0,
});

Observe stored data

example 1:

const unObserve = observe("complex", (r) => {
  console.log(r);
});

setTimeout(unObserve, 5000); // stop observe after about 5 seconds

example 2 (React):

const [complex, setComplex] = useState(getDefault("complex"));

useEffect(() => {
  const unObserve = observe("complex", (c) => {
    setComplex(c);
  });
  return unObserve; // stop observe on unmount
}, []);

example 3 (observe multiple and all):

const unObserveMultiple = observeMultiple(
  ["height", "complex"],
  ({ height, complex }) => {
    console.log(height, complex);
  }
);

const unObserveAll = observeAll(({ height, complex }) => {
  console.log(height, complex);
});

setTimeout(() => {
  unObserveMultiple();
  unObserveAll();
}, 5000);

Only way to change stored data

You can pass a function or a Object into setState function as argument

example:

const { setState } = NRS({
  complex: () => ({
    uid: "",
    name: "",
  }),
  height: () => 0,
});

setTimeout(() => {
  setState({ height: 42 }); // "height" wil be observed after 5 seconds
  setState((prevState) => {
    if (!prevState.complex) {
      return { complex: { uid: "114514", name: "1g1g1g1g" } }; // the mutation will be observed
    }
    return prevState; // no change will be observed
  });
}, 5000);

Create a dispatch function for stored data createDispatch sometimes we might need to manage complex state by a reducer

arguments: key, reducer

key is the state name defined in store

reducer is the similar function with React userReducer parameter, first arg is previous value, second arg is the action contains type and an optional payload*

the type of this payload is the same as related state marked with "key(first argument)" defined inside store

return a dispatch function, we can use this dispatch function to emit actions

example:

const { observe, createDispatch } = NRS({
  complex: () => ({
    uid: "",
    name: "",
  }),
  height: () => 0,
});

const dispatchHeight = createDispatch<"height", "clear" | "auto">({
    key: "height", // the name of defined data
    reducer: (h, action) => {
        if(action.type === "clear") {
            return 0;
        }

        if(action.type === "auto") {
            return action.payload
        }
        return h;
    }
})

const changeHeight = () => {
    dispatchHeight({
        type:"auto", // type is required
        payload: Math.floor(Math.random() * 10)
    })
}

const clearHeight = () => {
    dispatchHeight({
        type: "clear",
        // payload is optional
    })
}

const setHeightBtn = document.querySelector<HTMLButtonElement>("#height-setter");
setHeightBtn?.addEventListener("click", changeHeight);

const clearHeightBtn = document.querySelector<HTMLButtonElement>("#height-clear");
clearHeightBtn?.addEventListener("click", clearHeight);

const output = document.querySelector<HTMLDivElement>("#height-output");
observe("height", (h) => {
   if(output) {
      output.style.height = `${h}px`; // dynamically change a height of a HTMLDivElement
    }
})

Create a asynchronous dispatch function for stored data createAsyncDispatch: sometimes we might need a asynchronous process happened after dispatching data, we can return a Promise or Observable in defined Reducer

arguments: key, reducer, config

key is the state name defined in store

reducer is the similar function with React userReducer parameter, first arg is previous value, second arg is the action contains type and an optional payload*

the type of this payload is the same as related state marked with "key(first argument)" defined inside store

the third argument is a config object containing: a boolean parameter "lazy", if it is true, reducer will not be invoked until previous async process is not pending.

And Functions:

FunctionArgumentReturnRequiredDescription
startN/AvoidNofire on start
successReturnType<SK>voidNofire on success, carried with resolved value
failunknownvoidNofire on error, carried with an error
fallbackN/AReturnType<SK>Noa callback providing a value when error to update store, the store will not be updated if it is undefined
alwaysN/AvoidNofire on the Observable complete or Promise finalized

return a constant array dispatch, observe

we can dispatch actions mixed with a config object (mentioned above third parameter)

observe returns a destructor, start to listen the dispatch activity until we call the destructor you do not need to try catch the async dispatch function, as the error has been captured inside, use the second argument to handle error

const [dispatchHeight, observeHeightReducer] = createAsyncDispatch<"height", "clear" | "auto">({
  key: "height",
  reducer: (h, action) => {
    if (action.type === "clear") {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(0);
        }, 1000);
      });
    }
  // action.payload is a number
    if (action.type === "auto") {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(action.payload);
        }, 1000);
      });
    }
    return Promise.resolve(h);
  },
},
// optional third argument
);
// we can observe "height" like usual
observe("height", console.log)

// need to start observe the dispatch activity and use reducer as the observer

const unObserve = observeHeightReducer();

// call unObserve when we are not caring the dispatch activity

dispatchHeight(
  {
    type:"auto",
    payload: 100,
    fail: (err) => console.error(err)
  }
)
// dispatch an action with config, the config will overwrite the third argument only in current dispatch activity

Clone and compare sometimes we need some special clone or/and compare function we can define them in the factory function

clone function is for achieving immutability compare function is for reducing unnecessary observation

example

import { clone, cloneDeep } from "lodash";
const { getState, setState } = NRS(
  {
    complex: () => ({
      uid: "",
      name: "",
    }),
    height: () => 0,
    groups: (): Array<{ num: number, score: number, alias: string }> => [
      {
        num: 42,
        score: 0,
        alias: "none",
      },
    ],
  },
  // second argument is optional and all properties are optional
  {
    comparator: (var1, var2) => var1 === var2, // set default comparator,
    comparatorMap: { complex: (c1, c2) => c1.uid === c2.uid }, // set specified comparator for "complex"
    cloneFunction: clone, // use Lodash provided shallow clone
    cloneFunctionMap: {
      groups: cloneDeep, // use Lodash provided deep clone just for "group"
    },
  }
);

const c1 = getState("complex");
// should not equal, memory location different
console.log(c1 === getClonedState("complex"));

const g1 = getState("groups");
// should equal with a default clone function, inner objects are not cloned
// should not equal given a specific deep clone function
console.log(g1[0] === getClonedState("groups")[0]);

setTimeout(() => {
  setState({ complex: { ...getDefault("complex") } });
}, 1000);
setTimeout(() => {
  setState({ complex: { ...getDefault("complex") } });
}, 2000);

// only log one time, even the "complex" object changed, because the compare criterion is the "complex.id, see the compare function definition"
observe("complex", console.log);

Observable computation

sometimes we want a computed value from our defined data in store

example

const { withComputation } = NRS({
  height: () => 0,
});

const compute = withComputation({
  computation: ({ height }) => {
    return height * 2;
  },
});

const unObserve = compute.observe((h) => {
  console.log(h);
  // should log 84 after 1 second
});

setTimeout(() => {
  setState({ height: 42 });
}, 1000);

setTimeout(unObserve, 2000);

Observable asynchronous computation

sometimes the computation might not immediately computed, we can return an Observable object instead.

the argument of "withAsyncComputation" is a configurable object containing

and functions below:

FunctionArgumentReturnRequiredDescription
onStart{ K in keyof S: ReturnType<SK> }voidNofire on start
onErroranyvoidNofire on error, carried with an error
onSuccessresult: RvoidNofire on success, carried with a resolved computed result
onCompleteN/AvoidNofire on the async computation stream complete
comparatorN/AvoidNocustomer comparator to compare upstream values (keys related values), to determine whether should the computation function get called

example

import { map, timer } from "rxjs";

const { withAsyncComputation } = NRS({
  height: () => 0,
});

const compute = withAsyncComputation({
  computation: ({ height }) => {
    return timer(1000).pipe(map(() => height * 2));
  },
  // ...optional functions below
});

compute.observe((h) => {
  console.log(h);
  // should log 84 after 1 second
}, onPending // optional, fire on start async process
);

setState({ height: 42 });

// you can also get a value and state by calling get
// "state" is a enum including: PENDING, ERROR and FULFILLED
console.log(compute.get())
// should log { state: PENDING, value: 0 }

setTimeout(() => {
  console.log(compute.get())
  // should log { state: FULFILLED, value: 84 }
}, 1500)

Schedule and fire on create

schedule mode: sync or async, default to async, if set to async, only the last value of current call stack can be observed

fire on create: the default can be observed if set to true

example:

NRS(
  {
    height: () => 0,
  },
  {
    config: {
      schedule: "async", // you can call setState many times in a sync way, but only last mutation can be observed, normally useful on production, but keeping it "sync" is good for development debugging
      fireOnCreate: false, // the default value cannot be observed
    },
  }
);

Define your own Mid-wares

"getDataSource" method returns a RxJS Observable, which gives you a independent data stream pipeline.

we can add some Mid-wares to achieve certain effects.

example: Report some data change to a server.

import {
  map,
  exhaustMap,
  ajax,
  catchError,
  of,
  distinctUntilChange,
  AjaxResponse,
  AjaxError,
} from "rxjs";
const { getDataSource } = NRS({
  complex: () => ({
    uid: "",
    name: "",
  }),
});
getDataSource()
  .pipe(
    map(({ complex }) => complex.uid),
    distinctUntilChange(), // do not trigger a request if uid not change
    exhaustMap((uid) =>
      ajax({
        // wait until previous request finish, ignore incoming uid during previous requesting
        method: "POST",
        url: "some.url.example",
      }).pipe(
        catchError((err: AjaxError) => of(err)) // catch the request error to keep the data stream alive
      )
    )
  )
  .subscribe((r: AjaxError | AjaxResponse<any>) => {
    // perform some tasks if needed
  });

Use a Immutable Reactive Store (IRS):

Only Immutable data structure or Primitive data type accepted by IRS

Immutable follows Deep-copy-on-write pattern and has its own equals method to compare, so we do not need to provide clone and compare function

example:

import { Map as IMap, List } from "immutable";

const { getStates, getStateAll } = IRS({
  height: () => 0,
  complex: () =>
    IMap(
      new Map([
        ["uid", "" as string],
        ["name", "" as string],
      ] as const)
    ),
  groups: () => List<IMap<"score" | "age", string | number>>([]),
});
// the usage is the same as NRS
// IRS has no methods: getClonedState and getImmutableState
// comparator and comparatorMap, cloneFunction and cloneFunctionMap are no longer be configured, since they are pointless
// fireOnCreate and schedule are still configurable
// getStates and getStateAll returns a Immutable Map rather than a JS object

Common utility functions

some handy functions used in rx-store-core library get exported for common usage or develop related plugins

import { shallowClone, shallowCompare, bound, isPrimitive, isObject } from "rx-store-core";  
FunctionArgumentReturnDescription
shallowCloneanyanya function for shallow cloning majority JS data structure
shallowCompareany, anybooleana function for shallow compare by each key of object
boundFunction, ClassMethodDecoratorContextvoida Typescript Method level Decorator for binding class method to instance
isPrimitiveanybooleana function to judge a value is a primitive type or not
isObjectanybooleana function to judge a value is a reference type or not
2.3.5

22 days ago

2.3.4

4 months ago

2.3.3

8 months ago

2.2.1

11 months ago

2.2.0

11 months ago

2.2.3

10 months ago

2.2.2

10 months ago

2.2.5

10 months ago

2.2.7

10 months ago

2.2.6

10 months ago

2.1.9

11 months ago

2.3.0

10 months ago

2.3.2

8 months ago

2.3.1

10 months ago

2.1.6

11 months ago

2.1.5

11 months ago

2.1.8

11 months ago

2.1.7

11 months ago

2.2.9

10 months ago

2.2.8

10 months ago

2.1.4

1 year ago

2.1.3

1 year ago

2.1.2

1 year ago

2.1.1

1 year ago

2.1.0

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

2.0.3

1 year ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.3.4

1 year ago

1.3.3

1 year ago

1.3.2

1 year ago

1.3.1

1 year ago

1.3.0

1 year ago

1.2.9

1 year ago

1.2.8

1 year ago

1.2.7

1 year ago

1.2.6

1 year ago

1.2.5

1 year ago

1.2.4

1 year ago

1.2.3

1 year ago

1.2.2

1 year ago

1.2.1

1 year ago

1.2.0

1 year ago

1.1.9

1 year ago

1.1.8

1 year ago

1.1.7

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago

1.1.4

1 year ago

1.1.3

1 year ago

1.1.2

1 year ago

1.1.1

1 year ago

1.1.0

1 year ago

1.0.9

1 year ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago