Interceptor
An Interceptor wraps around your route handler, giving you control before the request reaches the handler and after the handler returns a response. This makes interceptors perfect for logging, timing execution speed, and transforming outgoing response payloads.
Interceptors execute right before your route handler:
Guard ➔ Validator ➔ Interceptor ➔ Route HandlerApplying an Interceptor (--@Interceptor)
To attach an interceptor to an endpoint, add the --@Interceptor(...) attribute comment directly above your route handler function:
local common = require("common")
local response = common.response
local Home = {}
--@Interceptor(Transform)
function Home.Get(req: IRequest)
return response.json({ message = "Hello from Mayari!" })
end
return HomeYou can also apply multiple interceptor rules in sequence:
--@Interceptor(Logger, Transform)
function Home.Get(req: IRequest)
return response.json({ message = "Hello from Mayari!" })
endExecution Sequence: Multiple interceptors run in order from left to right.
Writing Interceptor Rules (src/interceptors/)
Interceptor rule files must be placed inside src/interceptors/ (e.g., --@Interceptor(Logger) resolves to src/interceptors/Logger.luau).
Each rule file exports a single function that receives req and next:
-- src/interceptors/Logger.luau
local function Logger(req: IRequest, next: INext)
local start = os.clock()
-- Pass control down to the next interceptor or route handler
next()
local elapsed = (os.clock() - start) * 1000
print(`[{req.method}] {req.path} - Completed in {elapsed} ms`)
end
return LoggerThe Onion Pattern & Response Transformation
Because Interceptors follow the Onion Pattern, calling next() executes the rest of the pipeline and returns the handler's outgoing response.
You can inspect, mutate, or completely replace the response object before it gets sent back to the client:
-- src/interceptors/Transform.luau
local common = require("common")
local response = common.response
local function Transform(req: IRequest, next: INext)
local res = next()
-- Mutate response or wrap payload in a standardized format
return response.json({
success = true,
data = res.body,
timestamp = os.time()
}, res.config)
end
return TransformCheat Sheet
| Feature | Usage / Detail |
|---|---|
| Attribute Syntax | --@Interceptor(RuleName) |
| Rule Path | Must live in src/interceptors/RuleName.luau |
| Signature | function Rule(req: IRequest, next: INext) |
Calling next() | Required to continue down the chain to the route handler |
| Response Override | Return a new response payload to modify what the client receives |