Pet Counter System

I have been working on this for a while now. I am using a module I made called SafeDataStore. It wraps datastore calls inside a promise that waits for the datastore budget. I am using a memory store to quickly update the copies, and then I am updating the copies, when possible, inside of a datastore. Any suggestions?

local PlushiesUpdated = Instance.new("BindableEvent")
local function updatePlushieCopyCount()
	local plushiesUpdated = 0
	local dataStore = DataStoreService:GetDataStore("PlushieCopies")
	for plushieType, pendingCopies in pairs(pendingPlushieCopies) do
		SafeDataStore:pull(dataStore, plushieType):andThen(function(savedCopies, keyInfo)
			savedCopies = savedCopies or 0
			
			print(string.format("Pulled copies for plushie type %s. Last saved amount: %d", plushieType, savedCopies))
			
			local success, updatedCopies = pcall(function()
				return memoryStore:UpdateAsync(plushieType, function(cachedCopies)
					if not cachedCopies then
						
						print(string.format("Copy count was not for plushie type %d."
							.. " Using the backup from most recent save in the data store.", plushieType))
						
						cachedCopies = savedCopies
					end
					return cachedCopies + pendingCopies
				end, 432000)
			end)
			
			if not success then
				warn(string.format("Plushie type %d copies failed to update.", plushieType))
				return nil
			end
			
			plushieCopyCountReplica:SetValue({plushieType}, updatedCopies)
			pendingPlushieCopies[plushieType] = nil -- Remove the pending copies.
			
			return SafeDataStore:pushUpdate(dataStore, plushieType, function(savedCopies, keyInfo)
				keyInfo = keyInfo or { UpdatedTime = 0 }
				local secondsSinceUpdate = os.time() - keyInfo.UpdatedTime / 1000
				if secondsSinceUpdate <= 10 then
					print(string.format("Plushie type %d was updated %s ago. Update was ignored.", plushieType, EasyUtil:toTime(secondsSinceUpdate)))
					return nil
				end
				
				print(string.format("Plushie type %d was successfully updated.", plushieType))
				return updatedCopies
			end):catch(function(errorMessage)
				warn(string.format("Failed to update the saved copies for plushie type %d.", plushieType))
			end)
		end):catch(function()
			warn(string.format("Failed to retrieve the saved copies for plushie type %d.", plushieType))
		end):finally(function()
			plushiesUpdated += 1
			if plushiesUpdated == #Plushies then
				PlushiesUpdated:Fire()
			end
		end)
	end
	
	PlushiesUpdated.Event:Wait()
	print("Plushie copies updated.")
end
1 Like