首页 > 解决方案 > DateTime 的通用端点还是三个不同的端点?

问题描述

我有一个问题,因为我以前遇到过这种情况,我想知道最佳实践。

假设您想要这三个端点。

host:port/api/movies/published/2012从 '2012' 返回所有,按发布日期(M13,M1) host:port/api/movies/published/2012/8排序 返回所有来自 '2012-08',按发布日期(M1)排序 host:port/api/movies/published/2012/8/15返回所有来自 '2012-08-15',按发布日期(M1)排序

您是否会完成这样的通用端点,或者在这些情况下最佳实践是什么?你会怎么解决?

[HttpGet("published/{year:int}/{month:int?}/{day:int?}/")]
public void GetMoviesSortedByPublishedDateAsync(int year, int month = 0, int day = 0)
{

    if (month == 0)
    {
        var date = new DateTime(year, 1, 1);
        await _cosmosDbService.GetMoviesByYear(date.Year);
    }
    else if(day == 0)
    {
        var date = new DateTime(year, month, 1);
        await _cosmosDbService.GetMoviesByYearAndMonth(date.Year, date.Month);
    }
    else
    {
        var date = new DateTime(year, month, day);
        await _cosmosDbService.GetMoviesByPublishedDate(date);
    }
}

标签: c#asp.net-coreazure-cosmosdb

解决方案


您所拥有的可能会起作用,但它确实有一些可能的缺点,包括将参数构建到 URL 路径中最终会创建无限数量的可能路径这一事实。如果您想分析或过滤您的流量日志或以其他方式进行额外的请求处理,解析这些路径组合可能会导致一些痛苦。

将日期作为查询字符串中的参数似乎是一种更好的做法,这对于 REST URL来说更惯用。它可以是ISO 8601 格式的日期前缀,它自然是可排序的。然后,您的查询可以利用 Cosmos DB 中的本机STARTSWITH来有效地过滤和排序publishedDate属性。

它可能看起来像这样:

[HttpGet("{published}")]
public void GetMoviesSortedByPublishedDateAsync(string published)
{
    if(!string.IsNullOrEmpty(published) // Validate better than this :)
    {
        // Queries container where published date STARTSWITH specified value
        await _cosmosDbService.GetMoviesByPublishPrefix(published);
    }
}

可能的值可以是任何有效的日期前缀,可选的 2 位数日/月:

2020 => GET https://app.com/movies?published=2020
2020-03 => GET https://app.com/movies?published=2020-03
2020-03-13 => GET https://app.com/movies?published=2020-03-01

推荐阅读