Reading 9 API Server - liz-kavalski-401-advanced-javascript/seattle-javascript-401n13 GitHub Wiki

Express Router.param() Middleware

  • `router.param(name,callback) syntax.
    • name is a parameter and technically optional
    • the callback is a callback function that takes req, res, next. It also take the value of name
  • dose not take an array as a parameter.
  • Param callback functions are local to the router on which they are defined.
    • Not inherited by mounted apps or routers.
    • Defined on router will be triggered only by route parameters defined on router routes.
  • Called only once in a request-response cycle
  • Can be altered entirely by passing only a function to router.param().
    • First parameter of this function is the name of the URL parameter that should be captured.
    • Second parameter can be any JavaScript object which might be used for returning the middleware implementation.
  • The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.

Mongoose middleware

  • Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions.
  • Mongoose has 4 types of middleware:
    • Document middleware,
    • Model middleware,
    • Aggregate middleware,
    • Query middleware.
  • Middleware are useful for:
    • Complex validation
    • Removing dependent documents (removing a user removes all his blogposts)
    • Asynchronous defaults
    • Asynchronous tasks that a certain action triggers.
  • Mongoose will pass an error to the callback and/or reject the returned promise if their a pre hook error.
  • Post middleware are executed after the hooked method and all of its pre middleware have completed.
  • The second parameter is a next() function that you will call to trigger the next middleware in the sequence.
  • Has a pre-save and validation built-in.
  • The query and document has hooks for remove().
  • Query middleware differs from document middleware in a subtle but important way: in document middleware, this refers to the document being updated.
  • In query middleware, mongoose doesn't necessarily have a reference to the document being updated.
  • Post middleware called "error handling middleware" that executes specifically when an error occurs.
    • Takes one extra parameter: the 'error' that occurred as the first parameter to the function.
  • In aggregation middleware functions, this refers to the Mongoose Aggregate object. *What dose this means?
  • Currently, only init hooks are synchronous, because the init() function is synchronous.