Magic Hat
I've always wanted an easier way of writing express middleware.
Take the standard hello world
example.
app
With Magic Hat this becomes:
app
The Req variable
The thing that makes middleware pretty hard to work with is that it's all asynchronous, which makes managing control flow difficult. The req
variable is used in many pieces of middleware to store custom data as well as information about the current request.
This example serves the value of ?user=reggi
, we know it's stored in req.query.user
.
app
How can we do something like this with Magic Hat? Surely we can't do this, because we don't have access to req
.
// this will not workapp
I created a Req
object that accesses the scoped property of req
from outside the callback. To use it do something like this:
app
The concept of the Req
variable is where Magic Hat gets it's name, because it's like pulling a rabbit out of a hat.
Perhaps you can start to see the power of this, or not. Magic Hat is loaded with other features that attempt at allowing you to write smaller functions which you can surround with control flow goodness.
Conditionals
One major use case for Magic Hat is conditionals. Take the case where we'd like to serve a string specifically if the user query is github
.
app
Or serve an error:
app)
Writing Real Functions
With Magic Hat you can write normal functions and pass them around with Magic Hat using .exe()
. This way you can strip the real functionality out of your middleware flow.
{ return 'Hello ' + user + '!'}app ))
Chain Middleware
Because express middleware can be passed as an array of middleware or just one function Magic Hat works the same way.
Each piece as argument.
app
Pass in as array.
app
Or chain each call together and call .assemble()
at the end.
app
api
magicHatReq// conditionalsmagicHatifmagicHatifNotmagicHatifEqualmagicHatifNotEqualmagicHatifInstanceOfmagicHatifNotInstanceOfmagicHatifTypeOfmagicHatifNotTypeOf// basic responsemagicHatrendermagicHatredirectmagicHatsendmagicHatjson// handelingmagicHatthrowmagicHatnextmagicHatnextRoute// nesting middlewaremagicHatnestmagicHatnestParam// root conditionalmagicHatifExe// modifiersmagicHatsetmagicHatexemagicHatexeCatch// debuggingmagicHatlog
Example
var util = var model = var express = var Promise = var fs = Promisevar csv = Promisevar _ = var magicHat = var Req = magicHatReqvar multipartMiddleware = { var router = express router router router routerall'/api/redirects-csv/:redirectsCsv.json' magicHat routerall'/api/shopify-redirects/:shopifyRedirects.json' magicHat routerall'/api/redirects-csv/:redirectsCsv/shopify-redirects/:shopifyRedirects/report.json' main routerall'/api/shopify-redirects/:shopifyRedirects/redirects-csv/:redirectsCsv/report.json' main return router} main { return magicHat} main { return magicHat} main { return } moduleexports = main