0

I created a REST API with Spring Data Rest that forks fine. It must be possible to clone Projects via the API, so I added a custom @RestController to implement that via POST /projects/{id}/clone.

@RestController
@RequestMapping(value = "/projects", produces = "application/hal+json")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ProjectCloneController {

    private final ProjectRepo projectRepo;

    @PostMapping("/{id}/clone")
    public EntityModel<Project> clone(@PathVariable String id) {
        Optional<Project> origOpt = projectRepo.findById(id);
        Project original = origOpt.get();
        Project clone = createClone(original);

        EntityModel<Project> result = EntityModel.of(clone);
        result.add(linkTo(ProjectRepo.class).slash(clone.getId()).withSelfRel());
        
        return result;
    }

I am stuck at the point where I need to add a Link to the EntityModel that points to an endpoint provided by Spring Data Rest. It will need to support a different base path, and act correctly to X headers as well.

Unfortunately, the line above (linkTo and slash) just generates http://localhost:8080/636f4aaac9143f1da03bac0e which misses the name of the resource.

user3235738
  • 335
  • 4
  • 22

2 Answers2

0

Check org.springframework.data.rest.webmvc.support.RepositoryEntityLinks.linkFor

Ion Ionets
  • 105
  • 1
  • 8
0

You can use org.springframework.data.rest.webmvc.support.RepositoryEntityLinks from Spring Data Rest:

@RestController
@RequestMapping(value = "/projects", produces = "application/hal+json")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ProjectCloneController {
    private final ProjectRepo projectRepo;
    private final RepositoryEntityLinks repositoryEntityLinks;

    @PostMapping("/{id}/clone")
    public EntityModel<Project> clone(@PathVariable String id) {
        Optional<Project> origOpt = projectRepo.findById(id);
        Project original = origOpt.get();
        Project clone = createClone(original);

        EntityModel<Project> result = EntityModel.of(clone);
        result.add(repositoryEntityLinks.linkToItemResource(Project.class, clone.getId()).withSelfRel());
        
        return result;
    }

linkToItemResource take the class of Entity as the first argument.