Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented optional data validation #118

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion DataStore2/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,48 @@ function DataStore:GetTableAsync(default, ...)
end)
end

function DataStore:SetValidator(validator)
assert(
type(validator) == "function",
"function expected, got " .. type(validator)
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
)
self.validator = validator
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
end

local function AssertValidatorWithDefaultError(validator, input, defaultError)
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
local success, err = pcall(validator, input)
Masken8 marked this conversation as resolved.
Show resolved Hide resolved

-- if success but result is false
if success and err ~= true then
error(defaultError)
-- if not success and there is an error message
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
elseif not success and err ~= nil then
error(err)
end
end

function DataStore:Set(value, _dontCallOnUpdate)
if self.validator then
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
AssertValidatorWithDefaultError(
self.validator,
value,
"Invalid data"
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
)
end
self.value = clone(value)
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
self:_Update(_dontCallOnUpdate)
end

function DataStore:Update(updateFunc)
self.value = updateFunc(self.value)
local updateFuncReturn = updateFunc(self.value)
if self.validator then
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
AssertValidatorWithDefaultError(
self.validator,
updateFuncReturn,
"Invalid data"
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
)
end
self.value = updateFuncReturn
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
self:_Update()
end

Expand Down