Search code examples
javascriptnode.jspostgresqlexpresspg-promise

How are these three JavaScript function arguments use?


I've looked up JavaScript functions and arguments but couldn't find anything to help me understand a function like the one below. You can reference the original tutorial.

createPuppy has three arguments: req, res and next.

function createPuppy(req, res, next) {
  req.body.age = parseInt(req.body.age);
  db.none('insert into pups(name, breed, age, sex)' +
      'values(${name}, ${breed}, ${age}, ${sex})',
    req.body)
    .then(function () {
      res.status(200)
        .json({
          status: 'success',
          message: 'Inserted one puppy'
        });
    })
    .catch(function (err) {
      return next(err);
    });
}

That function is being called by a router:

var express = require('express');
var router = express.Router();

var db = require('../queries');

router.get('/api/puppies', db.getAllPuppies);
router.get('/api/puppies/:id', db.getSinglePuppy);
router.post('/api/puppies', db.createPuppy);
router.put('/api/puppies/:id', db.updatePuppy);
router.delete('/api/puppies/:id', db.removePuppy);
module.exports = router;

When db.createPuppy is called, there wasn't any arguments passed.

How do those three arguments fit into this function?

Update: I'm new to Node, JavaScript, pg-promise and express. So it was a bit overwhelming to narrow down where to dig. I came here to get leads on where to narrow my focus in. Thank you!


Solution

  • I believe that (req, res, next) are default arguments in Express.

    When you write router.post('/api/puppies', db.createPuppy);, the function createPuppy is not actually called yet. This just establishes what function to call when that method/endpoint is hit.

    Express takes care of calling the function and passing in the required arguments to it when you hit the /api/puppies endpoint with a POST.

    Hope that helps!