Yesterday I got stuck on a segment of code that confused me from the local library express tutorial. Today after reading through the docs it all makes sense and Express seems that much more robust to me. So, yesterday I was going through the section for the ‘Create Genre form’ when the callback used was not a function but rather was an array. This brought on the question of how express
handles arrays as the second parameter in a route instead of a regular callback function. I learned after reading through the Routes section of the express docs that multiple middleware functions can be included in an array (const arr = [md1, md2]
) and provided as the second parameter of the route method like get('/', arr)
.
In the tutorial the express-validator
packages uses middleware functions for validating data sent by users. So in my route handling POST
requests the validation middleware and the actual controller functions were included as the callback for the route.post()
method. I will include the code below.
It was a cool experience to read and find my solution. This is not anything new but I could not find my answer on Stack Overflow because I thought the express-validator
functions were not middleware. Once I figured that out it all made sense. The Express docs were pretty nice though so that also helped.
TLDR;
Okay, so here are the highlights of what I did:
- Portfolio -> Continued updating my projects for the projects hosting site. This site is meant to provide a stable location online for all of my demo projects linked to my portfolio. That way my portfolio won’t point to dead links. I add my weather app project. Trying to update the Git repos while I keep going through this process. I just recently had a serious Git awakening so I am trying to improve on my old repos. One day things will look so clean you could perfectly fork off each of my repos.
- Practice -> Continued working through the practice ‘Local Library’ project in the MDN ExpressJS guide. Continued my work on part 6 of the tutorial. Read up on the Express docs to help overcome the confusion I had with a section of the provided code for the
POST
request handler.
Code snippets I did not understand and the Notes from docs page
Segment from the genre controller:
// Handle Genre create on POST.
exports.genre_create_post = [
body('name', 'Genre name required').trim().isLength({min: 1}).escape(), // Validate and sanitize the name field
(req, res, next) => {
const errors = validationResult(req) // Extract the validation errors from a request
const genre = New Genre({name: req.body.name}) // Construct Genre object with escaped and trimmed name
if (!errors.isEmpty()){
res.render('genre_form', {title: 'Create Genre', genre: genre, errors: errors.array()})
return
}
Genre.findOne({'name': req.body.name}) // Data from form is valid. Check if Genre with same name already exists.
.exec((err, found_genre) => {
if (err) return next(err)
if (found_genre)
res.redirect(found_genre.url) // Genre exists, redirect to its detail page.
else
genre.save((err) => {
if (err) return next(err)
res.redirect(genre.url) // Genre saved. Redirect to genre detail page.
});
})
},
]
Usage in Genre section of catalog router:
//POST request for creating Genre.
router.post('/genre/create', genre_controller.genre_create_post);
Notes on Using an Array of Callback Functions
An array of callback functions can handle a route. For example:
const cb0 = function (req, res, next) {
console.log('CB0')
next()
}
const cb1 = function (req, res, next) {
console.log('CB1')
next()
}
const cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])
A combination of independent functions and arrays of functions can handle a route. For example:
const cb0 = function (req, res, next) {
console.log('CB0')
next()
}
const cb1 = function (req, res, next) {
console.log('CB1')
next()
}
app.get('/example/d', [cb0, cb1], (req, res, next) => {
console.log('the response will be sent by the next function ...')
next()
}, (req, res) => {
res.send('Hello from D!')
})
Goal For Round 8 of the #100DaysofCode Challenge
This is my eighth round of the “#100daysofcode” challenge. I will be continuing my work from round five, six, and seven into round eight. I was working through the book “Cracking the Coding Interview” by Gayle Laakmann McDowell. My goal was to become more familiar with algorithms and data structures. This goal was derived from my goal to better understand operating systems and key programs that I use in the terminal regularly e.g. Git. This goal was in turn derived from my desire to better understand the fundamental tools used for coding outside of popular GUIs. This in turn was derived from my desire to be a better back-end developer.
I am currently putting a pause on the algorithm work to build some backend/full stack projects. I primarily want to improve my skills with the back-end from an implementation perspective. I have improved tremendously in terminal and CLI skills but I lost focus due to how abstract the algorithm concepts got. I wanted to work on things that were more tangible until I can get to a position where I could directly benefit from improving my algorithm skills and theoretical knowledge. So that’s the focus right now. Build my backend skills and prove my full stack capabilities by building some dope projects.
Again, I still have no idea if my path is correct but I am walking down this road anyways. Worst case scenario I learn a whole bunch of stuff that will help me out on my own personal projects. Best case scenario I actually become one of those unicorn developers that go on to start a billion dollar company… You never know LOL.