-
-
Save joelwurtz/2017abbb881e214c37dbeae3f0aabc0c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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