如何验证从以下URL或类似内容给出的路径变量(storeId,customerId,accountId)?/store/{storeId}/customers/{customerId}/accounts/{accountId}
如果用户开始写random storeIds/customerIds
,并尝试创建类似
URL中的POST /store/478489/customers/56423/accounts
(假设478489和56423没有指向有效的资源)。
我想返回正确的错误代码,例如HttpStatus.NOT_FOUND, HttpStatus.BAD_REQUEST
。
我在Spring Boot中使用Java。
以下问题更详细地解释了我的问题,但是并没有太多答复。
Validating path to nested resource
最佳答案
在提供的URL /store/{storeId}/customers/{customerId}/accounts/{accountId}
中,
显然store has customers
和那些customers have accounts
。
后续方法包括额外的数据库调用,用于按ID验证商店和按ID验证顾客,但这将是适当的方法,因为如果我们在STORE和CUSTOMER表上使用带有联接的查询,那么您可能无法确切知道给定的storeId或customerId是否为错误/不在数据库中。
如果您逐步进行操作,则可以显示相应的错误消息,
如果storeId不正确-There exists no store with given storeId: XYZ
如果customerId不正确-There exists no customer with customerID: XYZ
由于您提到您正在使用Spring Boot,因此您的代码应该看起来像这样:
@RequestMapping(value = "/store/{storeId}/customers/{customerId}/accounts",
method = RequestMethod.POST)
public ResponseEntity<Account> persistAccount(@RequestBody Account account, @PathVariable("storeId") Integer storeId,
@PathVariable("customerId") Integer customerId) {
// Assuming you have some service class @Autowired that will query store by ID.
// Assuming you have classes like Store, Customer, Account defined
Store store = service.getStoreById(storeId);
if(store==null){
//Throw your exception / Use some Exception handling mechanism like @ExceptionHandler etc.
//Along with proper Http Status code.
//Message will be something like: *There exists no store with given storeId: XYZ*
}
Customer customer = service.getAccountById(storeId, customerId);
if(customer==null){
//Throw your exception with proper message.
//Message will be something like: *There exists no store with given customerID: XYZ*
}
// Assuming you already have some code to save account info in database.
// for convenience I am naming it as saveAccountAgainstStoreAndCustomer
Account account = service.saveAccountAgainstStoreAndCustomer(storeId, customerId, account);
ResponseEntity<Account> responseEntity = new ResponseEntity<Account>(account, HttpStatus.CREATED);
}
上面的代码片段只是代码外观的骨架,通过遵循一些良好的编码习惯,可以使结构比上面给出的更好。
希望对您有所帮助。