Skip to content

Instantly share code, notes, and snippets.

@kokeiro001
Created May 30, 2019 15:43
Show Gist options
  • Save kokeiro001/eb12a9c4b112c24e99d8c3e2338eba18 to your computer and use it in GitHub Desktop.
Save kokeiro001/eb12a9c4b112c24e99d8c3e2338eba18 to your computer and use it in GitHub Desktop.
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