gpt4 book ai didi

java - 使用 Spring Reactive Router 保存后返回 201 和位置

转载 作者:行者123 更新时间:2023-12-02 11:05:35 25 4
gpt4 key购买 nike

我正在使用 Spring Reactive 和 MongoDB 来创建 Rest API。仍在熟悉函数范式,所以我正在努力让事情顺利进行。这是一个关于行星的 API。

我需要的是 POST 方法将行星持久化到 Mongo 并将生成的 ID 添加到 201 响应位置。

在一篇博客文章中,作者创建了一个随机 UUID 并将其设置为要持久化的对象,但我认为这不是一种适合生产的方法。

这是我到目前为止所拥有的,它运行良好,但没有这个必要条件。

    public Mono<ServerResponse> addPlanet(ServerRequest serverRequest) {
Mono<PlanetDTO> planetDTO = serverRequest.bodyToMono(PlanetDTO.class);
return created(UriComponentsBuilder.fromPath("planet/").build().toUri())
.contentType(MediaType.APPLICATION_JSON)
.body(fromPublisher(
planetDTO.map(p -> new Planet(p))
.flatMap(planetService::addPlanet), Planet.class));

然后是服务代码:

    public Mono<Planet> addPlanet(Planet planet) {
return planetRepository.save(planet);
}

有人有办法实现它的功能吗?提前致谢!

最佳答案

明白了!我将为其他需要它的人回答这个问题,因为关于这个框架的 Material 还不是很多。

    public Mono<ServerResponse> addPlanet(ServerRequest serverRequest) {
Mono<PlanetDTO> planetDTO = serverRequest.bodyToMono(PlanetDTO.class);

return planetDTO.map(p -> new Planet(p))
.flatMap(planetService::addPlanet)
.flatMap(p ->
created(UriComponentsBuilder.fromPath("planet/" + p.getId()).build().toUri())
.contentType(MediaType.APPLICATION_JSON)
.body(fromObject(new SWMessageDTO("Planet has been created!", 201)
))
);

关于java - 使用 Spring Reactive Router 保存后返回 201 和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50996634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com