头图

Commands and queries provide a powerful and simplified way to handle state (in other words, load and cache) and perform actions against backend systems. This is similar to how libraries like React Query and SWR handle state issues from APIs in single-page applications. A large portion of front-end application state comes from the back-end. The Redux architecture, which is often used for state management, was not created with this type of state in mind, and requires a lot of boilerplate to support it. Different types of state require different solutions, and commands and queries are designed to handle state from the API in Spartacus. Commands and queries will replace the default Spartacus library's NgRx in many cases, and make most implementations simpler, with better, more consistent error handling, while also leveraging the Spartacus event framework.

what is command

Commands represent actions that can change the state of the system, usually by making REST calls to the backend. Commands can return results and can be executed while taking into account the execution strategy. Each command execution returns an observable, which is emitted (with an optional success result) and then either completes when the command completes, or throws an error if the command execution results in an error.

Subscribing to the resulting observable does not determine the execution of the command, so it is optional. ,

command definition

Commands can be defined as properties of a class by storing the result of the CommandService.create factory method call.

The command has the following parameters:

  • A function to dispatch a command (usually a call to a connector)
  • an options object (usually used to specify policies)

Below is an example:

  protected updateCommand: Command<{ details: User }> = this.command.create(
    (payload) =>
      this.userIdService.takeUserId(true).pipe(
        switchMap((uid) =>
          this.userProfileConnector.update(uid, payload.details)
      ),
    {
      strategy: CommandStrategy.Queue,
    }
  );
  • Parallel executes all commands in parallel.
  • Queue queues commands and executes them sequentially (this is the default policy).
  • CancelPrevious starts a new command execution and cancels the previous execution if it has not completed (the result stream of the previous execution will complete without emitting).
  • ErrorPrevious starts a new command execution, or raises an error for the previous command if it has not completed (the result stream of the previous execution will raise an error).

Exposing Commands in Facade Services

Commands are intended to be exposed as calls to methods that can be executed on the command class and return observable results. As mentioned earlier, a call can simply call a method to execute a command. Subscribing to results is optional. Below is an example:

  update(details: User): Observable<unknown> {
    return this.updateCommand.execute({ details });
  }

注销
1k 声望1.6k 粉丝

invalid