Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions Withings.Example/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Withings.NET.Client;
using Withings.NET.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddMemoryCache();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
Expand Down Expand Up @@ -84,18 +86,23 @@
return Results.Json(activity);
});

app.MapGet("/api/withings/dailyactivity", async (HttpContext context, WithingsClient client) =>
app.MapGet("/api/withings/dailyactivity", async (HttpContext context, WithingsClient client, IMemoryCache cache) =>
{
var userId = context.Session.GetString("UserId");
var accessToken = context.Session.GetString("AccessToken");

if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(accessToken))
return Results.Unauthorized();

var activity = await client.GetActivityMeasures(
DateTime.Today.AddDays(-30),
userId,
accessToken);
var cacheKey = $"dailyactivity_{userId}_{DateTime.Today:yyyyMMdd}";
var activity = await cache.GetOrCreateAsync(cacheKey, async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
return await client.GetActivityMeasures(
DateTime.Today.AddDays(-30),
userId,
accessToken);
});
return Results.Json(activity);
});

Expand Down