Datastore Code Review

Hi everyone! Hope your having a great day. I recently released a game with some other people which I had to immediately take down due to data issues. I recently just rewrote the datastore code and was wondering whether this would be secure for it to work.

--// DATASTORES
local DataStoreService = game:GetService("DataStoreService")
local Storage = DataStoreService:GetDataStore("-BetaDataCameraSimulator")

 -- When The Player Joins
game.Players.PlayerAdded:Connect(function(plr)
	local key = plr.UserId
	
	local data 
	local success, errormessage = pcall(function()
		data = Storage:GetAsync(key)
	end)
	
	if success then
		plr.leaderstats.Coins.Value = data.Coins
		plr.leaderstats.Rebirths.Value = data.Rebirths
		plr.leaderstats["Total Photos"].Value = data.TotalPhotos
		plr.Stats.CurrentPhotos.Value = data.CurrentPhotos
		plr.Stats.Gems.Value = data.Gems
		plr.Stats.EquippedPet.Value = data.EquippedPet
		plr.Stats.EquippedCamera.Value = data.EquippedCamera
	else
		print("Error loading data for " .. plr.Name)
		warn(errormessage)
	end

end)

 -- PlayerLeaving
game.Players.PlayerRemoving:Connect(function(plr)
	local key = plr.UserId
	
	local data = {}
	data.Coins = plr.leaderstats.Coins.Value
	data.Rebirths = plr.leaderstats.Rebirths.Value
	data.TotalPhotos = plr.leaderstats["Total Photos"].Value
	data.CurrentPhotos = plr.Stats.CurrentPhotos.Value
	data.Gems = plr.Stats.Gems.Value
	data.EquippedPet = plr.Stats.EquippedPet.Value
	data.EquippedCamera = plr.Stats.EquippedCamera.Value
	
	local success, errormessage = pcall(function()
		Storage:SetAsync(key, data)
	end)
	
	if success then
		print("saved data successfully for "..plr.Name)
	else
		print("error saving data for "..plr.Name)
		warn(errormessage)
	end
end)

Instead of using GetAsync, you should use UpdateAsync since it takes into account the previous data

2 Likes

The thing that immediately stands out with this is that you are using SetAsync when the player leaves without checking whether their data successfully loaded. If success is false when the player joins, you should not be trying to save when they leave.

3 Likes

UpdateAsync is used to increment data based on it’s old data. This datastore doesnt care what the old datastore was, it’s just setting it to what it’s supposed to be. Also the UpdateAsync datastore limit is lower than SetAsync

1 Like

This is an error, I think you meant SetAsync.