Issue found: functions within pipe operation in fp-ts are being skipped

I've recently started delving into function programming and encountered some unexpected behavior. I'm facing an issue where a function containing a tryCatch isn't being called within a pipe function for fp-ts. Despite reaching the next line past the function with breakpoints, it seems like the tryCatch function or any subsequent chain or fold functions are not executed.

Moreover, when I isolate this function and log it to the console using validateRegistrationForm(user), instead of getting a return value, it displays a function. From what I've gathered online, it seems that tryCatch should return a TaskEither and not a function.

Could someone point out any syntax errors causing this problem and suggest how to resolve it?

Here is an excerpt of the function in the pipe where the tryCatch appears to be skipped:

const validateRegistrationForm = (user: User): TaskEither<Error, User> => tryCatch(
    async () => {
        const schema = Joi.object().keys({
            userName: Joi.string().min(4).max(255).required(),
            firstName: Joi.string().pattern(new RegExp(/^[a-z\d\-_\s]+$/i)).min(1).max(50).required(),
            lastName: Joi.string().pattern(new RegExp(/^[a-z\d\-_\s]+$/i)).min(1).max(50).required(),
            emailAddress: Joi.string().email().required(),
            password: Joi.alternatives().try(Joi.string(), Joi.number()).required(),
            confirmPassword: Joi.alternatives().try(Joi.string(), Joi.number()).disallow(Joi.ref('password')).required()
        });

        let {error} = await schema.validateAsync(user);

        if (error && error.length > 0)
            throw new ValidationError(error.message);

        return user;
    },
    (reason: any) => reason instanceof Error ? reason : new Error(reason.message)
);

Below is the function consisting of the pipe and chain:

const createUser = (user: User): TaskEither<Error, User> => {
    return pipe(
        user,    
        validateRegistrationForm, 
        chain((validContent: User) => {
            const user: User = {
                confirmPassword: validContent.confirmPassword,
                firstName: validContent.firstName,
                lastName: validContent.lastName,
                emailAddress: validContent.emailAddress,
                password: validContent.password,
                userName: validContent.userName
            };

            return repository.saveUser(user);
        })
    );
};

Lastly, here's the code snippet calling the function with the pipe:

postUser: (req, res) => {
        pipe(
            req.body,
            interactor.createUser,
            fold(
                (error) => async () => {
                    console.error(error);
                    res.status(500).send({ error: 'Failed to retrieve user' });
                },
                (user) => async () => {
                    if (user) {
                        res.status(200).send(user);
                    } else {
                        res.status(404).send({ error: 'User not found' });
                    }
                }
            )
        );
    }

Answer №1

When you use tryCatch, it creates a new function that is then returned by your own function. You have the option to either eliminate the outer function or execute it directly.

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

When passing a property name via generic, it is not possible to have multiple properties

I recently came across a coding example that I found interesting: export type TimeStamped<TContent, TContentName extends string> = { [P in TContentName]: TContent } type Food = 'apple' | 'banana' | 'pear' type TimeS ...

Encountering a Node-gyp rebuild issue while integrating NGRX into an Angular application on Mac OS

I am currently working on integrating ngrx/store into my Angular application. Johns-MBP:Frontend johnbell$ npm install @ngrx/store <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac9cbc4dccbd9ea9b849c849b99">[email pr ...

Typically used to describe an item with a variable amount of string attributes

I have a TypeScript generic for an object with an unspecified number of string parameters like this: type Params<T extends string[]> = Record<T[number], string>; However, every time I want to use it, I need to define it with an array like so: ...

Utilizing Typescript to Inject Generics and Retrieve the Name of an ES6 Module

I am currently working on developing a versatile repository using: Typescript ES6 Angular 1.x However, I am facing challenges in determining the correct way to inject the Entity and retrieve its module name. The main reason for needing the name: I adh ...

Properly implement the indexById function

I have a task to create a function called indexById that will accept an Array of objects. Each object in the array will contain a unique id property and may also have different value properties. The desired outcome is to get an object where the keys are t ...

Building AngularJS directives using CSS classes

My current approach is as follows: class AService { $http: any; $state: any; static $inject = ['$http', '$state']; constructor($http, $state) { this.$http = $http; this.$state = $state; }; Dealing w ...

What could be causing the "Failed to compile" error to occur following the execution of npm

Exploring react with typescript, I created this simple and basic component. import React, { useEffect, useState } from "react"; import "./App.css"; type AuthUser = { name: string; email: string; }; function App() { const [user, setUser] = useState& ...

Accessing the personal data fields of a MongoDB object

My current environment setup includes: NodeJS: 5.7.1 Mongo DB: 3.2.3 MongoDB (NodeJS Driver): 2.1.18 TypeScript: 1.8 I have defined an Object using Typescript as: class User { private _name:string; private _email:string; public get name():strin ...

Exploring Angular2: The Router Event NavigationCancel occurring prior to the resolution of the Route Guard

My application has routes protected by an AuthGuard that implements CanActivate. This guard first checks if the user is logged in and then verifies if certain configuration variables are set before allowing access to the route. If the user is authenticated ...

Capturing the request headers when making an HTTP call with AngularJS

Hey! I need some help with displaying the content of headers. Is there a simple way to do this? Here's my code snippet: this.http.post(this.url, '{"username":"user","password":"123456"}') .subscribe((res) => { var payload = res.json(); ...

Leveraging Renderer in Angular 4

Understanding the importance of using a renderer instead of directly manipulating the DOM in Angular2 projects, I have gone through multiple uninstallations, cache clearings, and re-installations of Node, Typescript, and Angular-CLI. Despite these efforts, ...

Guide: Making a custom icon for a status bar in your vscode extension

Looking for assistance, I am trying to create a custom icon status bar button for my vscode extension. Despite my efforts in researching and analyzing code examples, I have yet to find a solution that works. Here is the current code snippet. import * as vs ...

Can you dynamically create screens within the React Navigation Tab Navigator using code?

My goal is to dynamically generate tabs in React-Navigation based on the values retrieved from an array, and pass the data from each array value to the corresponding screen. For instance, if there are 2 accounts, I expect 2 tabs with unique screens for eac ...

How can we eliminate a declaration?

The declaration file index.d.ts of a library I am using contains the following: declare namespace browser.runtime { ... function sendMessage(message: any, options?: _SendMessageOptions): Promise<any>; function sendMessage(extensionId: str ...

Error TS2349: The function cannot be called as it does not have a defined call signature. The type 'typeof renderIf' does not have any compatible call signatures

Based on the starter template found at https://github.com/react-native-training/reactxp-starter, I am just starting out with TypeScript! The issue seems to be related to the type in the renderIf function. I'm unsure where exactly the type should be s ...

Exploring Ngu-Carousel in Angular 7: Importing JSON data for a dynamic display

After attempting to import data from JSON and display it using ngu-carousel, I encountered an error. The error shows "length of undefined" Subsequently, when I try to click on the previous/next button, another error appears. This error states "innerHTML ...

Tips for using map on an array to create and return an object with the help of tslint and its syntactic sugar

This is a straightforward question about code style. How do I use the map function to iterate over an array and return a new object without triggering TSLint warnings? TSLint suggests simplifying the arrow function by removing curly braces, 'retur ...

Support for dark mode in Svelte with Typescript and TailwindCSS is now available

I'm currently working on a Svelte3 project and I'm struggling to enable DarkMode support with TailwindCSS. According to the documentation, it should be working locally? The project is pretty standard at the moment, with Tailwind, Typescript, and ...

Attempting to retrieve backend data through an API to be displayed on the frontend

After successfully sending form data from my React front end to the server using fetch, I am struggling to make this data accessible from the front end again. Despite being able to access and utilize the data within my API function on the server side, I&ap ...

Trigger a new GET request in Angular whenever a selection is made

I have a dilemma with my two select options. The first select allows you to choose different car brands, while the second select dynamically populates specific models based on the selected brand using a GET request. component.html <mat-form-field app ...