在REST API中实现子资源

时间:2019-03-19 21:58:27

标签: java rest design-patterns

我需要在REST API中实现子资源

URL将类似于:
https://localhost:8080/v1/student/ {id}?include =地址,资格,登录

因此,地址,资格和登录名是三个子资源,如果我们将其添加为查询参数,则将包括这些子资源。子资源可以是数据库调用或其他服务的REST调用

问题发生在实现方面,我已将@RequestParam List包括在内

所以目前我正在服务类中这样写

 public Student getStudentDetail(Integer id ,List<String> include){
    Student student = new Student();
    // setting student details
    for(String itr: include){
    if(itr=="address"){
    student.setAddress(repo.getAddress(id));
    }
    if(itr=="qualification"){
    student.setQualication(repo.getQualification(id));
    }
    if(itr=="login"){
    student.setLogin(client.getLogin(id));// here client in Rest Call for 
    }


   }
    return student;
    }

学生班:

@Data
public Class Student{
private String id;

private List<Address> address;

private List<Qualification> qualification;

private Login login; 
}

所以在这里,我需要为每个子资源添加条件,请问您可以建议采用哪种更好的方法或任何设计原则。

还有另一种使用反射API在运行时获取存储库方法名称的方法,但这会增加调用的额外开销。

另一种方法可以是:

我可以使用策略设计模式

Abstract Class 

public Abstract class Subresource{
public Student getSubresouce(Integer id,Student student){}
}

public class Address extends Subresource{
@Autowired
Databaserepo repo;

public Student getSubresource(Integer id , Student student){
  return student.setAddress(repo.getAddress(id));
}
}

public class Login extends Subresource{
@Autowired
RestClient client;

public Student getSubresource(Integer id, Student student){
 return student.setLogin(client.getLogin(id));
}
}

但是用这种方法,我无法在服务中编写逻辑

  public Student getStudentDetail(Integer id ,List<String> include){
        Student student = new Student();
        // setting student details
        for(String itr: include){
       // Need to fill logic
// Help me here to define logic to use strategy oattern
       }
        return student;
        }

1 个答案:

答案 0 :(得分:1)

您正在寻找的是投影。从这个link

  

投影是客户仅请求特定字段的一种方式   从一个对象而不是整个对象。何时使用投影   您只需要一个对象的几个字段,这是一个很好的方法   自记录您的代码,减少响应的负载,甚至允许   服务器放宽原本耗时的计算或IO   操作。

如果您使用的是Spring here,请参见一些示例。

相关问题