2017-08-13 51 views
1

我有一個名爲handleImageBannerUpload的方法。在這個方法中,我有一個switch語句。有3個開關的情況和每個人都應該返回不同的ResponseEntity:如何在交換機中使用ResponseEntity?

switch(type){ 
    case "localEvent": 
      try { 
      LocalEvent localEvent = localEventRepository.findOne(id); 
      storageService.store(file, localEvent); 
      String path = localEvent.getBannerPath(); 
      log("FileUploadController: " + path); 
      result = ResponseEntity 
       .ok() 
       .header(HttpHeaders.CONTENT_TYPE, "application/json;") 
       .body(path); 
     } 
     catch (StorageException e) { 
      result = ResponseEntity 
       .status(HttpStatus.INTERNAL_SERVER_ERROR)    
       .header(HttpHeaders.CONTENT_TYPE, "application/json;") 
       .body("\"" + e.getMessage() + "\""); 
     } 

    case "session": 
     try { 
      Session session = sessionRepository.findOne(id); 
      storageService.store(file, session); 
      String path = session.getSessionDescriptionImagePath(); 
      log("FileUploadController: " + path); 
      result = ResponseEntity 
       .ok() 
       .header(HttpHeaders.CONTENT_TYPE, "application/json;") 
       .body(path); 
     } 
     catch (StorageException e) { 
      result = ResponseEntity 
       .status(HttpStatus.INTERNAL_SERVER_ERROR)    
       .header(HttpHeaders.CONTENT_TYPE, "application/json;") 
       .body("\"" + e.getMessage() + "\""); 
     } 
    case "theme": 
     try{ 
      Theme theme = themeRepository.findOne(id); 
      storageService.store(file, theme); 
      String path = theme.getThemeImagePath(); 
      log("FileUploadController: " + path); 
      result = ResponseEntity 
       .ok() 
       .header(HttpHeaders.CONTENT_TYPE, "application/json;") 
       .body(path); 
     } 
     catch (StorageException e) { 
      result = ResponseEntity 
       .status(HttpStatus.INTERNAL_SERVER_ERROR)    
       .header(HttpHeaders.CONTENT_TYPE, "application/json;") 
       .body("\"" + e.getMessage() + "\""); 
     } 
} 

return result; 

如何創建一個適當的result變量,可以在switch語句返回ResponseEntity?

回答

0

你的設計氣味已經滲入你的代碼。您犧牲了清晰度,可讀性和可測試性以支持交換機。

,你需要的是3個簡潔端點:

POST /banner/event 
POST /banner/theme 
POST /banner/template 

從那裏,你應該堅持單一職責原則,使每一個相應的控制器方法是短而簡潔。