taglius
taglius

Reputation: 1247

ServiceStack- cache object sometimes based on state

Not sure the best way to implement this pattern - say our service returns the results of a sporting event. We want to put the object in the cache only if the event is over. If the event is still being played, then we want to keep it out of the cache (because it is changing frequently).

It didn’t seem correct to use the regular .ToOptimizedResultUsingCache and then delete from the cache right after.

Upvotes: 1

Views: 63

Answers (1)

mythz
mythz

Reputation: 143284

My approach would be to check if the event is in the Cache, if it isn't create it, then return it immediately if you don't want it cached, otherwise use ToOptimizedResultUsingCache to cache and return the most optimal response the client accepts, e.g:

public object Get(GetEvent request)
{
    var cacheKey = $"{nameof(EventResponse)}:{event.Id}";

    var eventResponse = Cache.Get<EventResponse>(cacheKey)
         ?? GetEvent(request.Id);

    if (eventResponse.Result.ExpiredDate == null)
        return eventResponse;

    // Cache and return optimal result for Request
    return base.Request.ToOptimizedResultUsingCache(Cache, cacheKey, () =>
       eventResponse;
}

Upvotes: 1

Related Questions