Chaining based on conditions in JavaScript and TypeScript

How can I conditionally add a function to a chain in JavaScript?

For instance, if modifier is true, I want myKey to be required using Joi.string().required(). If it is false, then just use Joi.string():

function customJoi(modifier) {
  return Joi.object({
    myKey: Joi.string() //#If(modifier) .required() #EndIf
  });
}

I am aware that I could achieve this without conditional statements by breaking it down into multiple steps. However, I'm interested in finding an elegant way to handle this for large objects.

Answer №1

Consider using the optional option if it is not mandatory.

myKey: Joi.string()[modifier ? 'required' : 'optional']()

Answer №2

If you're looking to accomplish this task, consider using a ternary operator in JavaScript.

function customValidator(update) {
    return Validator.object({
        myItem: update ? Validator.string().required() : Validator.string()
    });
}

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

What is the best way to continuously call a URL using jQuery until the desired result is obtained?

I have a jQuery script that interacts with a Jenkins web server to initiate a build process. The duration of this build process is unknown, and one way to determine if the build is completed is by checking the JSON API for the status key "building." If thi ...

How to Send Data with NodeJS by Utilizing the Finish Event

Is there a way to retrieve the JSON data sent during the nodejs finish event? This is how I send the JSON data: oResponse.json({ version: "1.0.0", author: "Someone", contributors: "also Someone" }); I would like ...

How can I obtain the download link for an image that has been resized using Node.js in Google Cloud Functions?

I have recently started exploring node js and google cloud functions. Successfully, I can resize an image to create a thumbnail. However, I am stuck at finding the download URL for the newly generated thumbnail. Below is the code snippet: exports.gener ...

Inquired about the installation of Typescript in the Docker image building process despite it already being installed

I am in the process of creating a docker image for a Next.js/React application that utilizes Typescript. Typescript is installed and I can successfully generate a local build without docker. However, during the docker image creation, I encounter the foll ...

Place a vertical slider adjacent to an HTML element on either the left or right side

I'm struggling to bind a range slider to the left or right side of a canvas that displays video. Despite my efforts, CSS seems to be putting up a strong fight. I can handle issues like stretching and slider values, but attaching it to the canvas is pr ...

Using Vue.js for redirecting with a post method

Is there a way to redirect from Vue.js to a Laravel controller using the POST method without using AJAX? I would like to be able to use var_dump or dd inside the controller. //Vue.js axios.post('/add-hotel-listing', this.finish).then((respons ...

MongoDB facing difficulties in updating the database

Seeking help with my MongoDB setup as I am still new to it. I have a database where card data is stored and need to update counts when users like cards, resulting in a total likes number. I'm facing an issue where I keep getting a 400 error response ...

Tips for Sending Emails from an Ionic Application without Utilizing the Email Composer Plugin

I am attempting to send an email from my Ionic app by making an Ajax call to my PHP code that is hosted on my server. Below is the code for the Ajax call: $scope.forget = function(){ $http({ method: 'POST', url: 's ...

What is the best way to attach a function to an href attribute for creating a dynamic link?

I've been struggling to pass a function to the href attribute in my link tag, but no matter what I try, it just doesn't seem to work. It either redirects to a 404 page or is completely unclickable. What could be causing this issue? This link app ...

Retrieve the value from a classic ASP page using an if statement and pass it to

Currently, I am attempting to assign a JavaScript value through ASP. foo('RequestMode', '<%=Request.Querystring("Mode")%>') My goal is to achieve something along the lines of: foo('RequestMode', '<%=if (Reques ...

Using Angular, we can assign an array iteration as the value for a dropdown option in

Following the controller logic: $scope.form_data = { day: 'Day' }; $scope.days = [ 'Day',1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31 ]; In the html section: <select n ...

The jQuery autocomplete feature is malfunctioning, as it is unable to display any search

Creating a country list within an ajax call involves working with an array of objects: $.ajax({ url: '//maps.googleapis.com/maps/api/geocode/json?address=' + zipCode + '&region=AT', type: 'GET', dataType: &apo ...

Encountering a JavaScript toJSON custom method causing a StackOverflow error

Unique Scenario Upon discovering this answer, a new idea struck me - creating an object from a JSON literal. This led me to believe I could do the opposite using the handy JSON method: JSON.stringify(myObject). Curious, I proceeded as follows: function ...

Exploring Grunt (node): Ways to Display Available Tasks

While I am accustomed to using Rakefile, Cakefile, and Jakefile, each of them offered a convenient method for listing the tasks available. For example: jake -T jake db:dump # Dump the database jake db:load # Populate the database ...and so ...

Adding External JS Files to a Node.js Project

I recently discovered how to incorporate a JS file into Node JS. However, I am facing an issue with two JS files in particular - hashing.js and encoding.js. Within encoding.js, I have the following code: exports = exports || {}; exports.encoding = encodi ...

Failed installation of Semantic-ui through npm encountered

Encountering an error while attempting to install semantic-ui through npm for a new project. Here are the version details: $ node -v v16.14.0 $ npm -v 8.10.0 $ npm i semantic-ui npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Losing POST data when sending HTTP status codes in Express 3.4.8

I have implemented a route handler in Express 3.4.8 to check for privileges on all my routes. In case the credentials sent with each request are invalid, I want to respond with a status of 403. app.all('*',function(req,res,next){ //req.body c ...

What is the process for setting a cookie in Next.js from a different backend server?

I have encountered an issue with my Node.js API built using Express.js. The cookie I set works perfectly fine on Postman, but for some reason, it is not functioning properly in Next.js. I set the cookie when a user logs in, but it is not appearing in the b ...

Error encountered in Listings#index with ExecJS RuntimeError

Upon launching my localhost, I encountered an ExecJS error message that has left me puzzled. Any assistance would be greatly appreciated. A Glimpse into My Localhost The issue originates from /.../conektec/app/views/layouts/application.html.erb, specific ...

How to dismiss a jQueryMobile dialog without triggering a page refresh

I've encountered a question similar to this before, but there wasn't any solution provided. The issue I'm facing is that I have a form and when a user clicks on a checkbox, I want to open a popup/dialog for them to enter some data. However, ...