0

Imagine this sample Express app straight from the documentation:

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(3000)

What is the idiomatic way to invoke the '/' endpoint programmatically from a different point in the same application code? Assume that I already removed the last line app.listen(3000).

The reason for this is that I want to take something like express-pouchdb and write an adapter for a different wire protocol, but leveraging the extensive routes already defined. I want to invoke these routes directly from js code without going over the network.

The application has dozens of routes already defined so changing each one to direct function calls as suggested in the first comment is not an option.

UPDATE:

I tried calling app.route.dispatch() but nothing comes back on the rsp object.

Alex R
  • 11,364
  • 15
  • 100
  • 180
  • _an idea_ - Instead of using a lambda, map the request to an external method, then you can call the method at will. – Matt Clark Oct 31 '22 at 04:52
  • @MattClark the code defining the routes using lambdas is pre-existing, so I updated the question a bit to make that more clear. The routes are already defined in an existing open-source project which I would rather not rewrite. – Alex R Oct 31 '22 at 04:53
  • As long as you have acces to the router, [This may answer your question](https://stackoverflow.com/questions/33090091/is-it-possible-to-call-express-router-directly-from-code-with-a-fake-request) – LeoDog896 Nov 02 '22 at 21:06
  • @LeoDog896 yes! Please post as an answer to get the bounty. I can’t close as duplicate. – Alex R Nov 04 '22 at 00:04

1 Answers1

1

Your question is a duplicate of this answer: Is it possible to call Express Router directly from code with a "fake" request?

You can use run-middleware module exactly for that. You create an express app a usual, and then you can call the app using your parameters

LeoDog896
  • 3,472
  • 1
  • 15
  • 40