6.3.1 调整资源路径和关系名称

实际上,Spring Data REST 提供了处理 tacos 的端点。但是,尽管 Spring Data REST 非常智能,但它在暴露 tacos 端点方面的表现却稍微逊色一些。

在为 Spring Data 存储库创建端点时,Spring Data REST 尝试使关联多元化的实体类。对于 Ingredient 实体,端点是 /ingredients。对于 Order 和 User 实体,它是 /orders/users。到目前为止,一切顺利。

但有时,比如 “taco”,它会在一个字母上出错,这样复数形式就不太正确了。事实证明,Spring Data REST 将复数形式 “taco” 表示为 “tacoes”,因此,要想对 tacos 发出请求,你必须请求 /api/tacoes

% curl localhost:8080/api/tacoes
{
    "_embedded" : {
        "tacoes" : [ {
            "name" : "Carnivore",
            "createdAt" : "2018-02-11T17:01:32.999+0000",
            "_links" : {
                "self" : {
                    "href" : "http://localhost:8080/api/tacoes/2"
                },
                "taco" : {
                    "href" : "http://localhost:8080/api/tacoes/2"
                },
                "ingredients" : {
                    "href" : "http://localhost:8080/api/tacoes/2/ingredients"
                }
            }
        }]
    },
    "page" : {
        "size" : 20,
        "totalElements" : 3,
        "totalPages" : 1,
        "number" : 0
    }
}

你可能想知道我怎么知道 “taco” 会被误拼成 “tacoes”。事实证明,Spring Data REST 还公开了一个 home 资源,其中包含所有公开端点的链接。只需向 API 基础路径发出 GET 请求即可获得:

$ curl localhost:8080/api
{
    "_links" : {
        "orders" : {
            "href" : "http://localhost:8080/api/orders"
        },
        "ingredients" : {
            "href" : "http://localhost:8080/api/ingredients"
        },
        "tacoes" : {
            "href" : "http://localhost:8080/api/tacoes{?page,size,sort}",
            "templated" : true
        },
        "users" : {
            "href" : "http://localhost:8080/api/users"
        },
        "profile" : {
            "href" : "http://localhost:8080/api/profile"
        }
    }
}

可以看到,home 资源显示了所有实体的链接。除了 tacoes 链接之外,一切看起来都很好,其中关系名称和 URL 都有 “taco” 的单数复数形式。

好消息是,不必接受 Spring Data REST 的这个小怪癖。通过向 Taco 类添加一个简单的注解,可以调整关系名称和路径:

@Data
@Entity
@RestResource(rel="tacos", path="tacos")
public class Taco {
    ...
}

@RestResource 注解让你可以给定任何你想要的的名称和路径的关系,在这个例子中,把它们都设定为了 “tacos”。现在当请求 home 资源的时候,将会看到 tacos 链接正确的复数形式:

"tacos": {
    "href": "http://localhost:8080/api/tacos{?page,size,sort}",
    "templeted": true
}

这还可以对端点的路径进行排序,这样就可以针对 /api/tacos 接口发起请求来使用 taco 资源了。

说到排序,让我们看看如何对 Spring Data REST 端点的结果进行排序。

results matching ""

    No results matching ""