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 2 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
24 changes: 19 additions & 5 deletions DataStore2/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -182,15 +182,28 @@ end
function DataStore:SetValidator(validator)
assert(
type(validator) == "function",
"function expected, got "..type(validator)
"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
assert(
self.validator(value),
AssertValidatorWithDefaultError(
self.validator,
value,
"Invalid data"
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
)
end
Expand All @@ -201,8 +214,9 @@ end
function DataStore:Update(updateFunc)
local updateFuncReturn = updateFunc(self.value)
if self.validator then
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
assert(
self.validator(updateFuncReturn),
AssertValidatorWithDefaultError(
self.validator,
updateFuncReturn,
"Invalid data"
Masken8 marked this conversation as resolved.
Show resolved Hide resolved
)
end
Expand Down