Unraveling functions from a JavaScript promise in a web application using ExpressJS and NeDB

I have successfully implemented code that retrieves all users from my neDB-promisses:

const fetchAllUsers = (res) => {
    db.find({})
        .sort({ name: 1 })
        .exec()
        .then(
            (content) => {
                res.status(200).json(content);
            },
            (err) => {
                res.status(400).json(err);
            }
        );
};

Now, I am aiming to optimize this code to prevent future redundancy in CRUD functions. I envision something like the following:

...
.then(successFunctionCall, failureFunctionCall)
...

I considered designing a separate module named successFunctionCall/failureFunctionCall, but I am faced with the challenge of needing to invoke res within it to define the response JSON and status code. Is there a more efficient approach to accomplishing this?

Thank you.

Answer №1

If you want to make use of functional programming concepts like currying, you can apply it to your functions. By passing the res parameter as a handler, you create a new function that will be ready to receive either the content or err:

const successFunctionCall = res => content => 
  res.status(200).json(content);

const failureFunctionCall = res => err => 
  res.status(400).json(err);

const getUsers = (res) => {
  db.find({})
      .sort({ name: 1 })
      .exec()
      .then(
        successFunctionCall(res),
        failureFunctionCall(res)
      );
};

Answer №2

To prevent redundancies in CRUD operations, one possible solution is to organize your concerns differently. Here's a basic outline of what I mean.

const usersDb = {} // instance of your user database here

const findAllSortedBy = db => (...args) => db.find({}).sort(...args).exec()

const findAllUsersSortedBy = findAllSortedBy(usersDb)

const success = res => content => res.status(200).json(content)

const failure = res => err => res.status(400).json(err)

const getUsers = res => {
  findAllUsersSortedBy({ name: 1 })
    .then(success(res))
    .catch(failure(res))
}

Below demonstrates the getUsers function as part of an express route handler.

const getUsers = (req, res) => {
  findAllUsersSortedBy({ name: 1 })
    .then(success(res))
    .catch(failure(res))
}

router.get('/users', getUsers)

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

Is the JSON parsing issue being caused by Bodyparser?

I am encountering an issue with parsing JSON on my server using the body-parser NPM module and Express. The JSON data is not appearing correctly on the server for some reason. Here is a snippet of my server code: ... app.use(bodyParser.json()); app.use(bo ...

Sorry, but we couldn't complete your request: User verification unsuccessful: email must be provided

Every time I attempt to save a user's credentials to the mongo database, an error pops up saying: "User validation failed: email: Path email is required." I am clueless as to why this issue keeps happening. It only started occurring when I added the v ...

ESLint is parsing through alternative configurations

My .eslintrc file is very simple: { "extends": [ "twilio" ] } However, when I run eslint, I encounter this error message: The config "standard" was referenced from the config file in "/Users/MyAccount/Projects/my-sample-app/node_modules/cipher ...

Acquire Category Permissions when making a channel in discord.js v14

I am in the process of setting up a channel that will grant specific roles access while automatically blocking out @everyone. I also want this setup to be compatible with categories, allowing for other roles to have permissions within them. let customPermi ...

Creating packing features specifically designed for resolution within a reusable module

I've decided to revamp my Angular application based on John Papa's style guide (well, mostly) and my main focus is on improving modularity. The stumbling block I've encountered is with route resolves. So far, I've been using a global ap ...

"Kindly complete all mandatory fields" - The undisclosed field is preventing me from submitting

I am facing an issue with my WordPress page that has Buddyboss installed along with Elementor pro as the Pagebuilder. The Buddyboss plugin provides Facebook-like functions on the website. While it is easy to comment on posts within the Buddy Boss system, I ...

Creating a Custom Error Object in Feathersjs: A Step-by-Step Guide

If I were to throw a GeneralError when calling a service, how can I create an error object with the following structure: { "status": "Failed", "code": "500_1", "detail": "Something is wrong with your API" } I have attempted to add this in the error hook: ...

Verifying the presence of a value in an array of nested objects prior to updating in Mongoose

This is the model for my shopping cart: const cartSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "userSchema", }, cart: [ { product: { type: mongoose.Schema.Types. ...

Tips for updating a section of a webpage without the need to redirect to a different page: use technologies such as Express, Nodejs, and M

In the midst of developing a two-player game where one player must guess a word within 10 tries, I find myself facing a challenge. I need to display the player's guesses and scores in a table without refreshing the entire page. Unfortunately, my exper ...

`Achieving object placement on top of another object in ThreeJS`

Being new to ThreeJS, I am seeking help with a basic question. I have loaded multiple GLTF files into my scene and I need to position one object on top of another (but the position should be adjustable later on) For instance: https://i.sstatic.net/oJq1BIi ...

React Warning: Every child component within a list must contain a distinct key property

Can you spot the issue in the following code snippet: <List> {sections.map(section => ( <> {section.header && <ListSubheader key={section.header}>{section.header}</ListSubheader>} {section.items ...

Error encountered in Three.js when using multiple canvases and loading JSON geometry

I have been working on creating multiple views and came across an example code here which worked flawlessly when I tried it. However, when I replaced the geometries with ones I created in Blender, I encountered an error: Cannot read property 'length ...

Caution: It is not possible to make changes to a component (`App`) during the rendering of another component (`History

I am currently in the process of creating a tic tac toe game, but I'm encountering an error that is preventing me from updating the history. Despite following a tutorial on skillshare.com and mirroring the steps exactly, the error persists. I must men ...

Submit the form and additional information in a single AJAX request in Django

Seeking assistance with a straightforward task. The objective is to utilize AJAX POST to move data from a form along with additional information. The challenge lies in extracting this data from the form later on, as it constitutes an entire line. $(func ...

What steps should be taken to avoid an event from occurring when an error message is encountered?

I have a dropdown list of cars where an error message is displayed if any of them becomes inactive. When the error message is shown, clicking on the Route Car button should prevent any event from occurring, i.e., no modal popup should be displayed. How ca ...

Having issues passing parameters with Ajax, Python Bottle, Jquery, and JSON collaboration

Every time I make an AJAX request POST, the newUser() function seems to be ignoring any arguments being passed even though I have filled out both userInput and passInput fields. Here's the JS/JQ/AJAX code snippet: var userInput = document ...

What are the available choices for constructing HTML based on an ajax response?

Are there any alternatives or libraries available for constructing html from an ajax response? Currently, I am taking the json data received, creating the html as a string, and using a jQuery function to insert it into the DOM. However, I believe there mu ...

I'm looking for the best method to submit an authentication form using isomorphic-fetch

I've encountered an issue while trying to send an ajax request from a react/redux app to an express POST endpoint. Despite testing the server-side endpoint with Postman and confirming its correct operation, I keep receiving {message: "Missing credenti ...

How can I turn off autocomplete in MUI textfields?

Currently, I am working with the latest version of mui. Within my user contact info form, there is a zip code field that I do not want to be auto completed if the value is null. However, despite my efforts, it continues to autocomplete with the email saved ...

What are the best practices for integrating QML with Java?

How can QML be interfaced with Java when developing the GUI and API for a linux based device? ...