Posts

Showing posts from November 6, 2021

Adapting Express.js

Image
  Now, it actually is possible to recreate some of this behavior with Express.js using a set of middleware. The  express - async - handler  npm module provides a wrapper function that can interpose and allow a  async  controller function to interact nicely with the Express.js  app . use  API. Unfortunately, this requires the developer to manually wrap each controller function: const asyncHandler = require ( 'express-async-handler' ) app . post ( '/user' , asyncHandler ( async ( req , res , next ) => { const bar = await foo . findAll (); res . send ( bar ); })) The response tuple unwrapping can also be handled by middleware. Such a middleware would need to run after the controller code has run and would replace the array with a representation Express.js is expecting. The ability to promise the request body stream parsing can also be built in a generic manner: app . use ( ( req , res , next ) => { req . bodyToJson = requ...

Forget Express.js — opt for these alternatives instead

Image
Node.js  offers some powerful primitives when it comes to building HTTP servers. By default, you get a function that runs every time an HTTP request has been received by the server. The proverbial server example that parses an incoming POST request containing a JSON body looks a bit like this: const http = require ( 'http' ); const server = http . createServer ( ( req , res ) => { // This function is called once the headers have been received res . setHeader ( 'Content-Type' , 'application/json' ); if ( req . method !== 'POST' || req . url !== '/user' ) { res . statusCode = 405 ; res . end ( '{"error":"METHOD_NOT_ALLOWED"}' ); return ; } let body = '' ; req . on ( 'data' , ( data ) => { // This function is called as chunks of body are received body += data ; }); req . on ( 'end' , () => { // This ...

Followers