Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexjamesbrown/6e1a94d308c642fb23575f47adbe735e to your computer and use it in GitHub Desktop.
Save alexjamesbrown/6e1a94d308c642fb23575f47adbe735e to your computer and use it in GitHub Desktop.
DeleteCache function for MattMarshEvents API
public static class DeleteCache
{
private static readonly HttpClient HttpClient = new HttpClient();
[FunctionName("DeleteEventsCache")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "events/cache")] HttpRequest req,
ILogger log)
{
var zoneId = Environment.GetEnvironmentVariable("CloudflareZoneId");
var authEmail = Environment.GetEnvironmentVariable("CloudflareAuthEmail");
var authKey = Environment.GetEnvironmentVariable("CloudflareAuthKey"); //this is in KeyVault
var cachedUrls = new[]{
"https://api.mattmarshevents.co.uk/events",
"https://api.mattmarshevents.co.uk/events/",
};
var url = $"https://api.cloudflare.com/client/v4/zones/{zoneId}/purge_cache";
using (var request = new HttpRequestMessage(new HttpMethod("POST"), url))
{
request.Headers.TryAddWithoutValidation("X-Auth-Email", authEmail);
request.Headers.TryAddWithoutValidation("X-Auth-Key", authKey);
var payload = new
{
files = cachedUrls
};
var json = JsonConvert.SerializeObject(payload);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await HttpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
log.LogInformation("Successfully cleared cache.");
return new OkResult();
}
var error = await response.Content.ReadAsStringAsync();
log.LogError(error);
throw new Exception("Error clearing cache: " + error);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment