Created
May 30, 2019 15:43
-
-
Save kokeiro001/eb12a9c4b112c24e99d8c3e2338eba18 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using System; | |
using System.IO; | |
using System.Threading.Tasks; | |
namespace Kokeiro | |
{ | |
public static class Util | |
{ | |
private static readonly string CacheDirectoryName = "Cache"; | |
public static T Cache<T>(Func<T> dataFecher, string key) | |
{ | |
var currentDirectory = Directory.GetCurrentDirectory(); | |
var cacheDirectory = Path.Combine(currentDirectory, CacheDirectoryName); | |
if (!Directory.Exists(cacheDirectory)) | |
{ | |
Directory.CreateDirectory(cacheDirectory); | |
} | |
var filePath = Path.Combine(cacheDirectory, $"{key}.json"); | |
if (File.Exists(filePath)) | |
{ | |
var json = File.ReadAllText(filePath); | |
return JsonConvert.DeserializeObject<T>(json); | |
} | |
else | |
{ | |
var data = dataFecher(); | |
var json = JsonConvert.SerializeObject(data); | |
File.WriteAllText(filePath, json); | |
return data; | |
} | |
} | |
public static async Task<T> Cache<T>(Func<Task<T>> dataFecher, string key) | |
{ | |
var currentDirectory = Directory.GetCurrentDirectory(); | |
var cacheDirectory = Path.Combine(currentDirectory, CacheDirectoryName); | |
if (!Directory.Exists(cacheDirectory)) | |
{ | |
Directory.CreateDirectory(cacheDirectory); | |
} | |
var filePath = Path.Combine(cacheDirectory, $"{key}.json"); | |
if (File.Exists(filePath)) | |
{ | |
var json = File.ReadAllText(filePath); | |
return JsonConvert.DeserializeObject<T>(json); | |
} | |
else | |
{ | |
var data = await dataFecher(); | |
var json = JsonConvert.SerializeObject(data); | |
File.WriteAllText(filePath, json); | |
return data; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment