Leveraging the power of RXJS and typescript for executing work conditionally between Server and Client Code



I am in need of a function that will assess various conditions to determine if an object is eligible for editing.
These conditions may exist on both the server and client sides.
Certain conditions should halt further validation and return a value.

I will attempt to clarify this process using pseudocode.
There may be an established pattern for executing such tasks already.

isEditable(): Observable<boolean> {
  return serverSideCondition.pipe(
    switchMap(editable => {
      if (editable)
      {
        return clientSideCondition;
      }

      return of(false); // Should abort further conditions ...
    }),
    switchMap(editable => {
      if (editable)
      {
        return clientSideAskTheUser;
      }

      return of(false); // Should abort further conditions ...
    })
  );
}

Thanks

Answer №1

If you prefer not to pass a false value through all operators, an alternative approach is to throw an error and catch it later.

isEditable(): Observable<boolean> {
  return serverSideCondition.pipe(
    throwIfFalsy(),
    switchMap(editable => clientSideCondition.pipe(throwIfFalsy())),   
    switchMap(editable => clientSideAskTheUser.pipe(throwIfFalsy())),
    // other operators ...
    catchError(error => of(error))
  );
}

throwIfFalsy() {
  return tap(value => {
    if (!value) {
      throw value
    }
  })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

pressing the button again will yield a new outcome

I am looking to disable a button (material ui) when it is clicked for the second time by setting disabled={true}. Unfortunately, I have not been able to find any examples related to this specific scenario on StackOverflow. <Button onClick={this.s ...

Type error TS2322: You can't assign type 'undefined' to type 'string'

I am currently in the process of creating a chatbot for an upcoming exhibition and encountered the following error: src/app/chat/chat.component.ts:32:9 - error TS2322: Type 'undefined' is not assignable to type 'string'. 32 th ...

Having trouble adding @angular/fire to my Angular project

Having trouble adding Firebase authentication to my Angular project, specifically when running npm install @angular/fire. I keep encountering the following error: > npm ERR! code ERESOLVE > npm ERR! ERESOLVE unable to resolve dependency tree > ...

Is the 'case' in a switch statement not treated as a typeguard by Typescript?

Here is a simplified version of the code I am working with: type Todo = { id: string; text: string; }; type Action = | { type: 'DELETE'; payload: string } | { type: 'CREATE'; payload: Todo } function reducer(state: Todo[], ...

Keeping track of the authentication state in AngularFire2 on page reload to verify if the user is logged

I am facing a challenge in my angular4 app that uses angularfire2. I need to determine if a user is logged in when the page loads. Logging in and out works fine, and I have set up a guard on the router to handle unauthorized access. In one example I came ...

In Node.js, retrieve all users from the database and display only the users' name, id, and image, excluding

I'm trying to fetch the names, profile pictures, and IDs of all users using the User.find() method. However, this method is returning all data including sensitive information like passwords and addresses. My goal is to only retrieve the name, ID, and ...

Dealing with an `err_connection_refused` HTTP error in Angular 7: What's the best approach?

Whenever my application encounters an err_connection_refused error during an HTTP request, I need to display a message to the user. This error typically occurs when the server is disconnected. http.get().subscribe( (response) => { }, err ...

The TN-Models-FP error message states that it is not allowed to use the `create` model without an associated `entity` model

Utilizing the TN-models-fp library to construct a basic api inspired by the provided examples, here is my implementation in api.ts: import { axios } from '../axios-instance' import { createApi } from '@thinknimble/tn-models-fp' import { ...

The side menu fails to appear when pressed

When using the push method, I am unable to see the side menu. However, it works fine with the setRoot navigation. How can I resolve this issue and display the side menu when using the push method? dashboard.html <ion-col col-9> <ion-searchbar ...

Having trouble with sending values to Angular 7 components' HTML pages

Struggling with a simple task and encountering an error: Code snippet below: app.component.html <div class="col-md-{{myvalue}}">stuff here</div> app.component.ts myvalue: string; ngOnInit() { this.myvalue('6'); } Seeing th ...

Troubden array filtration in Angular is malfunctioning

I recently developed an angular "filter component" intended to filter an array and display its contents. The keyword used to filter the array, value, is obtained from another component through a service. While the HTML displays both the value and the entir ...

What are the TypeScript type definitions for the "package.json" configuration file?

What is the most efficient method for typing the content of the "package.json" file in TypeScript? import { promises as fs } from 'fs'; export function loadManifest(): Promise<any> { const manifestPath = `${PROJECT_DIR}/package.json`; ...

explore and view all images within a directory

Hello, I am new to NextJS and encountering some issues. I have a folder in my public directory containing 30 images that I want to import all at once in the simplest way possible, without having to import each image individually by name. Here is the curren ...

Exporting Types in an NPM Package: Best Practices

Struggling to create a private NPM package for internal use within my company's Nodejs applications using Typescript. Currently, I have a basic proof of concept with some constants, but I'm having trouble structuring it in a way that is importabl ...

Utilizing a TypeScript definition file (.d.ts) for typings in JavaScript code does not provide alerts for errors regarding primitive types

In my JavaScript component, I have a simple exporting statement: ./component/index.js : export const t = 'string value'; This component also has a TypeScript definition file: ./component/index.d.ts : export const t: number; A very basic Typ ...

Utilizing shared components across a Next.js application within a monorepo

Utilizing a monorepo to share types, DTOs, and other isomorphic app components from backend services (Nest.js) within the same mono repo has presented some challenges for me. In my setup, both the next.js app and nest.js app (which itself is a nest.js mono ...

Can someone guide me on creating a slideshow using Ionic?

Having trouble integrating a javascript/css slideshow into Ionic. Ionic does not support the use of ".style" in elements. Need assistance, below is the code: <head> <title>Slideshow</title> <style> .slides {display:none;} </styl ...

When using Angular's `createComponent()` method, an error may be thrown with the message "ERROR TypeError: Cannot add

I am currently working on a project where I am dynamically creating components. The component's class is being passed via an ngrx action and the process involves: loadComponent(componentType: Type<any>): void { const viewContainerRef = this.co ...

What is the best way to display HTML in this particular situation?

This is the function I am working on: public static monthDay(month: number): string { let day = new Date().getDay(); let year = new Date().getFullYear(); return day + ", " + year; } I am trying to add <span></span> tags around ...

Angular Material - truncating selected text in a list

I'm having trouble implementing the Angular Material list with checkboxes, where the text needs to be truncated instead of word-wrapped due to limited UI space. I have modified an example on the Angular Material site to demonstrate the issue. The text ...