TheHeckingDeveloper

DSInterface

Apr 26th, 2021
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.67 KB | None | 0 0
  1. -- Services
  2. local dataStoreService = game:GetService("DataStoreService")
  3.  
  4. -- Formatstrings
  5. local keyValue = "%s : %s"
  6. local requestError = "Unable to %s data for DataStore: %s"
  7.  
  8. -- Private functions
  9. local function throwError(message)
  10.     warn("From DSInterface: " .. message)
  11. end
  12.  
  13. -- Tables
  14. local dataStoreInterface = {}
  15.  
  16. dataStoreInterface.__index = dataStoreInterface
  17.  
  18. -- Public object functions
  19. function dataStoreInterface:UnsafelyRequest(requestType, key, value)
  20.     local dataStore = self.DataStore
  21.    
  22.     if requestType == "Set" then
  23.         print("Setting, with ")
  24.         print(key, value)
  25.        
  26.         dataStore:SetAsync(key, value)
  27.     else
  28.         return dataStore:GetAsync(key)
  29.     end
  30. end
  31.  
  32. function dataStoreInterface:SafelyRequest(requestType, key, value)
  33.     local dataStore = self.DataStore
  34.  
  35.     local success, returnedValue = pcall(self.UnsafelyRequest, self, requestType, key, value)
  36.    
  37.     if not success then
  38.         -- The get/set errored
  39.        
  40.         throwError(requestError:format(requestType, dataStore.Name))
  41.         throwError(returnedValue)
  42.         throwError(keyValue:format(key, value or ""))
  43.        
  44.         return false
  45.     end
  46.    
  47.     -- In the case of Set, returnedValue will be nil at this point
  48.     -- In the case of Get, returnedValue will be, well, the returned value.
  49.    
  50.     return returnedValue
  51.     -- If there is a returnedValue, return that. If there isn't, return "success"
  52. end
  53.  
  54. function dataStoreInterface:Set(...)
  55.     return self:SafelyRequest("Set", ...)
  56. end
  57.  
  58. function dataStoreInterface:Get(...)
  59.     return self:SafelyRequest("Get", ...)
  60. end
  61.  
  62. return {
  63.     new = function(dataStore)
  64.         return setmetatable(
  65.             {
  66.                 DataStore = dataStoreService:GetDataStore(dataStore)
  67.             },
  68.            
  69.             dataStoreInterface
  70.         )
  71.     end,
  72. }
Advertisement
Add Comment
Please, Sign In to add comment