Skip to content
Open
Show file tree
Hide file tree
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
21 changes: 8 additions & 13 deletions DataStore2/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -182,26 +182,21 @@ end
function DataStore:SetValidator(validator)
assert(
type(validator) == "function",
"function expected, got " .. type(validator)
"function expected, got " .. typeof(validator)
)
self.validator = validator
end

local function AssertValidatorWithDefaultError(validator, input, defaultError)
local success, err = pcall(validator, input)

-- if success but result is false
if success and err ~= true then
error(defaultError)
-- if not success and there is an error message
elseif not success and err ~= nil then
error(err)
end
local function assertValidatorWithDefaultError(validator, input, defaultError)
local isValid = validator(input)
if not isValid then
error(defaultError)
end
end

function DataStore:Set(value, _dontCallOnUpdate)
if self.validator then
AssertValidatorWithDefaultError(
assertValidatorWithDefaultError(
self.validator,
value,
"Invalid data"
Expand All @@ -214,7 +209,7 @@ end
function DataStore:Update(updateFunc)
local updateFuncReturn = updateFunc(self.value)
if self.validator then
AssertValidatorWithDefaultError(
assertValidatorWithDefaultError(
self.validator,
updateFuncReturn,
"Invalid data"
Expand Down
14 changes: 14 additions & 0 deletions Tests/tests/DataStore2.spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,20 @@ return function()
expect(DataStore2(nonNilKey, fakePlayer):Get("badDefault")).to.equal("abc")
end)

it("should validate the data", function()
local dataStore = DataStore2(UUID(), fakePlayer)
local function testValidator(dataToValidate)
if dataToValidate == "yepp" then
return true
end
return false
end
dataStore:SetValidator(testValidator)
expect(dataStore.validator).to.be.a("function")
expect(dataStore:Set("nope")).to.throw()
expect(dataStore:Set("yepp")).to.equal(true)
end)

it("should set", function()
local dataStore = DataStore2(UUID(), fakePlayer)
dataStore:Set(1)
Expand Down