How to improve filters with promises

I had been programming a filters setup for the node API of a MEAN stack app.

Having this ´User´ model:

{[ .=old-user.model.js= | 1.hilite(=javascript=) ]}

It allowed a ´User´ controller like this:

{[ .=old-user.controller.js=| 1.hilite(=javascript=) ]}

The meaning should be straightforward: copy the ´name´ field as is and make the ´admin´ field a proper boolean. That was made possible by this:

{[ .=old-CRUD.controller.js=| 1.hilite(=javascript=) ]}

Then I wanted to add a ´password´ field to the ´User´ model. For storing it I decided to go with Strong Password Hashing with Node.js Standard Library. Properly translated to JavaScript and slightly tweaked I got this:

{[ .=hash.js= | 1.hilite(=javascript=) ]}

So my ´User´ model became this:

{[ .=user.model.js= | 1.hilite(=javascript=) ]}

Have you noticed that the ´Hash´ function relies on the asynchronous´crypto.pbkdf2´ function? That’s just standard, so I wasn’t going to use the synchronous version on a second thought.

Then my problem was:

How do I make these filters work with deferred values?

Ta-da! Promises:

{[ .=user.controller.js= | 1.hilite(=javascript=) ]}

To make that work I had to change a bit the ´CRUD´ controller.

The first change was to separate the filtering from the assignment, so that I could later use the ´Promise.all´ method which allows to synchronize promises and values as well. That implied to pass from a ´CopyFields´ function which filters and assigns each value in turn to a ´FilterFields´ function which filters all values at once, thus making the assignments directly in the ´Create´ function.

{[ .=middle-CRUD.controller.js= | 1.hilite(=javascript=) ]}

The second change was to add a needed special treatment for my promises. You may have noticed that, in the ´case ‘function’:´ above, ´result.value´ can be a promise BUT that won’t make ´result´ a promise itself!! So the code above wouldn’t work yet, because it would complete ´Promise.all´ before getting the hashed password. Finally, I got this:

{[ .=CRUD.controller.js= | 1.hilite(=javascript=) ]}

The added lines make ´result´ a promise if ´result.value´ is one: ´result´ will eventually resolve to the expected result. BTW, the ´stuff.isPromise´ method is the classical ´object.then && typeof object.then == ‘function’´.

2 Replies to “How to improve filters with promises”

  1. The decision to buy
    steroids online or elsewhere requires research on steroid forums and other
    places. Taking too much can cause significant steroid shot side effects; taking
    too little may not produce the beneficial effects of steroids
    very quickly and professionally… They were helpful, professional, and most
    importantly, effective at https://www.esteroides24.com.

Leave a Reply

Your email address will not be published. Required fields are marked *