Skip to content

Instantly share code, notes, and snippets.

@joelwurtz
Created August 2, 2017 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelwurtz/2017abbb881e214c37dbeae3f0aabc0c to your computer and use it in GitHub Desktop.
Save joelwurtz/2017abbb881e214c37dbeae3f0aabc0c to your computer and use it in GitHub Desktop.
MyAddEventHandler = Middleware.Builder(Middleware.Logger, Middleware.Identifier, Middleware.Sourcer, Middleware.Register)
-- This event will be log in console and automatically register if not existing
MyAddEventHandler('eventName', function (context, param1)
print(context.source) -- Source
print(context.identifier) -- Steam id (or ip)
-- Your code
end)
Middleware = {}
local EventRegistry = {}
---
-- Handler that automatically register
-- @param eventName
-- @param next
--
function Middleware.Register(eventName, next)
local hasEvent = false
for _, event in ipairs(EventRegistry) do
if eventName == event then
hasEvent = true
end
end
if not hasEvent then
EventRegistry[#EventRegistry] = eventName
RegisterServerEvent(eventName)
end
return next;
end
function Middleware.Logger(eventName, next)
return function (...)
print('Begin calling event "' .. eventName .. "' with " .. TableToString({...}))
next(...)
print('End calling event "' .. eventName .. '"')
end
end
function Middleware.Sourcer(eventName, next)
return function (context, ...)
context.source = source
next(context, ...)
end
end
--- Need to have the source as the first argument of the next
function Middleware.Identifier(eventName, next)
return function (context, ...)
if context.source then
context.identifier = GetPlayerIdentifiers(context.source)[1]
end
next(context, ...)
end
end
function Middleware.Builder(...)
local middlewareList = {...}
return function (eventName, callback)
local callbackChain = function(...)
local context = {}
callback(context, ...)
end
for _, middleware in ipairs(middlewareList) do
callbackChain = middleware(eventName, callbackChain)
end
AddEventHandler(eventName, callbackChain)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment