cache.gd 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. class_name _ModLoaderCache
  2. extends RefCounted
  3. # This Class provides methods for caching data.
  4. const CACHE_FILE_PATH = "user://mod_loader_cache.json"
  5. const LOG_NAME = "ModLoader:Cache"
  6. # ModLoaderStore is passed as parameter so the cache data can be loaded on ModLoaderStore._init()
  7. static func init_cache(_ModLoaderStore) -> void:
  8. if not _ModLoaderFile.file_exists(CACHE_FILE_PATH):
  9. _init_cache_file()
  10. return
  11. _load_file(_ModLoaderStore)
  12. # Adds data to the cache
  13. static func add_data(key: String, data: Dictionary) -> Dictionary:
  14. if ModLoaderStore.cache.has(key):
  15. ModLoaderLog.error("key: \"%s\" already exists in \"ModLoaderStore.cache\"" % key, LOG_NAME)
  16. return {}
  17. ModLoaderStore.cache[key] = data
  18. return ModLoaderStore.cache[key]
  19. # Get data from a specific key
  20. static func get_data(key: String) -> Dictionary:
  21. if not ModLoaderStore.cache.has(key):
  22. ModLoaderLog.info("key: \"%s\" not found in \"ModLoaderStore.cache\"" % key, LOG_NAME)
  23. return {}
  24. return ModLoaderStore.cache[key]
  25. # Get the entire cache dictionary
  26. static func get_cache() -> Dictionary:
  27. return ModLoaderStore.cache
  28. static func has_key(key: String) -> bool:
  29. return ModLoaderStore.cache.has(key)
  30. # Updates or adds data to the cache
  31. static func update_data(key: String, data: Dictionary) -> Dictionary:
  32. # If the key exists
  33. if has_key(key):
  34. # Update the data
  35. ModLoaderStore.cache[key].merge(data, true)
  36. else:
  37. ModLoaderLog.info("key: \"%s\" not found in \"ModLoaderStore.cache\" added as new data instead." % key, LOG_NAME, true)
  38. # Else add new data
  39. add_data(key, data)
  40. return ModLoaderStore.cache[key]
  41. # Remove data from the cache
  42. static func remove_data(key: String) -> void:
  43. if not ModLoaderStore.cache.has(key):
  44. ModLoaderLog.error("key: \"%s\" not found in \"ModLoaderStore.cache\"" % key, LOG_NAME)
  45. return
  46. ModLoaderStore.cache.erase(key)
  47. # Save the cache to the cache file
  48. static func save_to_file() -> void:
  49. _ModLoaderFile.save_dictionary_to_json_file(ModLoaderStore.cache, CACHE_FILE_PATH)
  50. # Load the cache file data and store it in ModLoaderStore
  51. # ModLoaderStore is passed as parameter so the cache data can be loaded on ModLoaderStore._init()
  52. static func _load_file(_ModLoaderStore = ModLoaderStore) -> void:
  53. _ModLoaderStore.cache = _ModLoaderFile.get_json_as_dict(CACHE_FILE_PATH)
  54. # Create an empty cache file
  55. static func _init_cache_file() -> void:
  56. _ModLoaderFile.save_dictionary_to_json_file({}, CACHE_FILE_PATH)