I'm building an NPM module that needs to make an HTTP request to itself (the running web server). For example:
var url = "http://127.0.0.1:" + (process.env.PORT || 3000) + path; request(url, function(error, response, body){    ... });   Is there a way to process a request through the NodeJS pipeline without actually doing an HTTP request?
Or is there a better way to form the URL? I'm nervous that 127.0.0.1 isn't the most robust way to handle this for production sites.
In a self consuming JSON API, you define some functionality in some standalone controller functions and then wire the functionality up to express after the fact. Let's use a library application as an example:
module.exports = {   browse: function () {       return Book.findAll()   },   read: function (options) {       return Book.findById(options.book)   },   processLateFees: function () {       // Do a bunch of things to process late fees   } }   In this file we build a function that converts a controller function to an HTTP route. We take the query params and pass that to our controller as options:
module.exports = function toHTTP (func) {     return function (req, res) {          func(req.params).then(function (data) {              res.send(data)          })     } }   And then we connect up our controller to our http router
var express = require('express') var books = require('./books') var toHTTP = require('./to-http')  var app = express() app.get('/books', toHTTP(books.browse)) app.get('/books/:book', toHTTP(books.read)) app.get('/batch-jobs/process-late-fees', toHTTP(books.processLateFees))   So we now have an express application connected up to controller functionality. And the wonderful thing is that we can call these controller functions manually too.
var books = require('./books') books.processLateFees().then(function () {     // late fees have been processed })   If you need a more in depth example of this, the Ghost blog codebase is built around this pattern. It is a very informative read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With