Is it possible to detect if a request is real vs injected?
purplepenguin42 opened this issue · 2 comments
💬 Question here
Is it possible to detect within a hook or handler whether or not the request is a "real" request vs being generated from fastify.inject()
?
import { isInjection } from 'light-my-request';
// ...
fastify.get('/test', async (req, res) => {
console.log(isInjection(req)); // always prints: false
return { ok: 'hello world' };
});
fastify.get('/inject', async (req, res) => {
const r = await fastify.inject({ method: 'get', path: '/test' });
return r.json();
});
I do see some internals/properties that are unique to the injected request, but I'm hesitant to hook into any internals when it doesn't seem to be documented anyway (not sure if they're stable/safe, etc.). I'm looking for an official way to do this if it's possible.
For a little context, although not very important, I have a handful of routes in my app, but one of them simply does an "internal redirect" to the other handler. I realize I could separate things out into functions and call them outside the scope of a handler, but it's quite messy, and I want all the hooks to run, etc. Is there a better way to do an internal redirect and essentially pass control to another route handler?
EDIT: An alternative would be having a way to possibly pass an object or flag along when calling inject, but that doesn't seem supported either. Basically, I need a way to set some flag, value, config, etc. that can be read from the handler, but that cannot be set on a normal request.
Thanks.
fastify
wrap the original request with it's own one.
Instead of checking the fastify
request, check the raw request.
import Fastify from 'fastify'
import { isInjection } from 'light-my-request'
const fastify = Fastify({})
fastify.get('/', function (request) {
console.log(isInjection(request.raw))
return ''
})
await fastify.inject({ method: 'GET', path: '/' })
Wowzers, I'm dumb, lol. I knew Fastify wrapped it, but I was thinking req.raw
was one step lower than even light-my-request
, so never thought to even try that, but it works. Appreciate the help!