Tips to improve my storage module?

Hey fellow programmers.

I made this code it’s been taking me a very long time and I’m planning to use it. It is a storage module for Roblox games that I’m planning to use for my future projects.

local StorageService = {}
StorageService.__index = StorageService

-- Services
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")

-- Configuration
local DATASTORE_NAME = "PlayerData"
local BACKUP_DATASTORE_NAME = "PlayerDataBackup"
local AUTO_SAVE_INTERVAL = 60 -- seconds
local MAX_RETRIES = 3
local RETRY_DELAY = 1 -- seconds

-- Default player data template
local DEFAULT_DATA = {
    coins = 0,
    gems = 0,
    level = 1,
    experience = 0,
    inventory = {},
    achievements = {},
    lastLogin = os.time(),
    playTime = 0,
    settings = {
        musicVolume = 0.5,
        sfxVolume = 0.5,
        graphicsQuality = "Medium"
    }
}

-- Cache for active player data
local playerDataCache = {}
local autoSaveConnections = {}

-- Private functions
local function deepCopy(t)
    if type(t) ~= "table" then return t end
    local copy = {}
    for k, v in pairs(t) do
        copy[k] = deepCopy(v)
    end
    return copy
end

local function mergeData(default, saved)
    local merged = deepCopy(default)
    
    for key, value in pairs(saved or {}) do
        if merged[key] ~= nil then
            if type(merged[key]) == "table" and type(value) == "table" then
                merged[key] = mergeData(merged[key], value)
            else
                merged[key] = value
            end
        else
            merged[key] = value
        end
    end
    
    return merged
end

local function safeGetDataStore(name)
    local success, datastore = pcall(function()
        return DataStoreService:GetDataStore(name)
    end)
    
    if success then
        return datastore
    else
        warn("Failed to get DataStore:", name, datastore)
        return nil
    end
end

local function retryOperation(operation, ...)
    local retries = 0
    local success, result
    
    while retries < MAX_RETRIES do
        success, result = pcall(operation, ...)
        
        if success then
            return result
        else
            retries += 1
            warn(string.format("Operation failed (attempt %d/%d): %s", 
                 retries, MAX_RETRIES, result))
            
            if retries < MAX_RETRIES then
                wait(RETRY_DELAY)
            end
        end
    end
    
    return nil, result
end

-- Public methods
function StorageService:GetData(player)
    local userId = tostring(player.UserId)
    
    -- Return cached data if available
    if playerDataCache[userId] then
        return playerDataCache[userId]
    end
    
    local mainStore = safeGetDataStore(DATASTORE_NAME)
    if not mainStore then return nil end
    
    local data
    local success, savedData = retryOperation(function()
        return mainStore:GetAsync(userId)
    end)
    
    if success and savedData then
        data = mergeData(DEFAULT_DATA, savedData)
    else
        -- Try backup store if main fails
        local backupStore = safeGetDataStore(BACKUP_DATASTORE_NAME)
        if backupStore then
            success, savedData = retryOperation(function()
                return backupStore:GetAsync(userId)
            end)
            
            if success and savedData then
                data = mergeData(DEFAULT_DATA, savedData)
                warn("Restored data from backup for player:", player.Name)
            end
        end
        
        -- If still no data, use default
        if not data then
            data = deepCopy(DEFAULT_DATA)
            warn("Using default data for new player:", player.Name)
        end
    end
    
    -- Update last login time
    data.lastLogin = os.time()
    
    -- Cache the data
    playerDataCache[userId] = data
    
    -- Set up auto-save
    self:SetupAutoSave(player)
    
    return data
end

function StorageService:SaveData(player)
    local userId = tostring(player.UserId)
    local data = playerDataCache[userId]
    
    if not data then
        warn("No data to save for player:", player.Name)
        return false
    end
    
    -- Update play time
    if data.lastLogin then
        data.playTime = data.playTime + (os.time() - data.lastLogin)
        data.lastLogin = os.time()
    end
    
    local mainStore = safeGetDataStore(DATASTORE_NAME)
    if not mainStore then return false end
    
    local success, errorMessage = retryOperation(function()
        mainStore:SetAsync(userId, data)
    end)
    
    if success then
        -- Save to backup as well
        local backupStore = safeGetDataStore(BACKUP_DATASTORE_NAME)
        if backupStore then
            pcall(function()
                backupStore:SetAsync(userId, data)
            end)
        end
        
        print("Successfully saved data for player:", player.Name)
        return true
    else
        warn("Failed to save data for player:", player.Name, errorMessage)
        return false
    end
end

function StorageService:SetupAutoSave(player)
    local userId = tostring(player.UserId)
    
    -- Remove existing auto-save connection
    if autoSaveConnections[userId] then
        autoSaveConnections[userId]:Disconnect()
        autoSaveConnections[userId] = nil
    end
    
    -- Set up new auto-save
    autoSaveConnections[userId] = game:GetService("RunService").Heartbeat:Connect(function()
        if not playerDataCache[userId] then return end
        
        -- Check if it's time to auto-save
        if playerDataCache[userId]._lastSave and 
           os.time() - playerDataCache[userId]._lastSave < AUTO_SAVE_INTERVAL then
            return
        end
        
        self:SaveData(player)
        playerDataCache[userId]._lastSave = os.time()
    end)
end

function StorageService:PlayerLeaving(player)
    local userId = tostring(player.UserId)
    
    -- Save data
    self:SaveData(player)
    
    -- Clean up
    if autoSaveConnections[userId] then
        autoSaveConnections[userId]:Disconnect()
        autoSaveConnections[userId] = nil
    end
    
    playerDataCache[userId] = nil
end

function StorageService:UpdateData(player, updateFunction)
    local userId = tostring(player.UserId)
    local data = playerDataCache[userId]
    
    if not data then
        warn("No data found for player:", player.Name)
        return false
    end
    
    local success, result = pcall(updateFunction, data)
    
    if success then
        return true
    else
        warn("Failed to update data for player:", player.Name, result)
        return false
    end
end

function StorageService:GetAllPlayersData()
    return playerDataCache
end

-- Initialize
game.Players.PlayerAdded:Connect(function(player)
    player:SetAttribute("DataLoaded", false)
    
    local data = StorageService:GetData(player)
    if data then
        player:SetAttribute("DataLoaded", true)
        print("Data loaded for player:", player.Name)
    end
end)

game.Players.PlayerRemoving:Connect(function(player)
    StorageService:PlayerLeaving(player)
end)

-- Auto-save all players periodically
spawn(function()
    while true do
        wait(AUTO_SAVE_INTERVAL)
        
        for userId, data in pairs(playerDataCache) do
            local player = game.Players:GetPlayerByUserId(tonumber(userId))
            if player then
                StorageService:SaveData(player)
            end
        end
    end
end)



return StorageService 









Lemme know if you got any tips to improve this really wanna use this for my project but I want it to be even better.

Have a great day!
2 Likes

Put ``` before and after the script to make it much more readable

1 Like