How to handle with Ordered data store properly?

Sorry for my poor English :smiling_face_with_tear:
I’ve been using Profile service for a while, and when I wanted to make leaderboards I came up with Profile service at once, but it seems that Profile service dose not use APIs like “GetOrderedDataStore”, so I am trying to code a simple practicable module.


local RankListModule = {}

---- services ----
local DataStoreService = game:GetService("DataStoreService")

---- variables ----
local nameTable = {
	rankList1 = "rankList1",
	rankList2 = "rankList2",
	rankList3 = "rankList3",
	rankList4 = "rankList4",
}
local storeTable = {}
local cookieTable = {
	rankList1 = {},
	rankList2 = {},
	rankList3 = {},
	rankList4 = {}
}
local AUTOSAVE_INTERVAL = 60

---- functions ----

-- get sorted data from data store
function GetRemoteRankList(rankListName, ascending, pageSize)
	ascending = ascending or false
	pageSize = pageSize or 10
	return storeTable[rankListName]:GetSortedAsync(ascending, pageSize):GetCurrentPage()
end

-- autoSave TODO  set too frequently
function AutoSave()
	while task.wait(AUTOSAVE_INTERVAL) do
		for _, name in pairs(nameTable) do
			for _, playerValue in ipairs(cookieTable[name]) do
				storeTable[name]:SetAsync(playerValue.key, playerValue.value)
			end
		end
	end
end

---- init ----
for key,value in pairs(nameTable) do
	storeTable[key] = DataStoreService:GetOrderedDataStore(value)
	cookieTable[key] = GetRemoteRankList(nameTable[key])
end

---- APIs ----
function RankListModule:SetPlayerRank(rankListName, player:Player, value)
	local exists = false
	for _, v in ipairs(cookieTable[rankListName]) do
		if v.key == player.UserId then
			exists = true
			v.value = value
		end
	end

	if not exists then
		table.insert(cookieTable[rankListName], {key = player.UserId, value = value})
	end

end

function RankListModule:GetRankListCookie(rankListName)
	return cookieTable[rankListName]
end

-------------
task.spawn(AutoSave)

return RankListModule

I set the cookieTable for the same reason as using a normal data store, to avoid too frequent use of GetAsync or SetAsync, but I could not find a proper solution to upload all cookie data via SetAsync. ​As you can see, my AutoSave function will request more than 40 times when it’s called.

function AutoSave()
	while task.wait(AUTOSAVE_INTERVAL) do
		for _, name in pairs(nameTable) do
			for _, playerValue in ipairs(cookieTable[name]) do
				storeTable[name]:SetAsync(playerValue.key, playerValue.value)
			end
		end
	end
end

so, is there a proper solution to save ordered data?

Sorry for my poor English again

1 Like