一个有点人为的但却很重要的例子。JSON补丁和“聚合”DTO
假设UserDetails
是由RESTful Web服务使用的聚合DTO(不清楚正确的术语,请教育我,但基本上是来自不同商店/服务的收集信息的模型)。它不一定具有与其收集在一起的对象相同的属性名称。
public class UserDetails
{
public int UserId { get;set; }
public string GivenName { get; set; }
public string Surname { get; set; }
public int? UserGroupId { get;set; } // FK in a different database
}
让我们的店坚持以下型号:
public class User
{
public int Id { get; set; }
public string GivenName { get; set; }
public string Surname { get; set; }
}
public class UserGroup
{
public int UserId { get; set; }
public int GroupId { get; set; }
}
让的UserDetails对象正是如此填充:
User user = _userService.GetUser(userId) ?? throw new Exception();
UserGroup userGroup = _userGroupService.GetUserGroup(user.Id);
UserDetails userDetails = new UserDetails {
UserId = user.Id,
GivenName = user.GivenName,
Surname = user.Surname,
UserGroupId = userGroup?.GroupId
};
也就是说,设置FirstName
或Surname
应该委托给UserService
,和UserGroupId
到GroupService
。
此UserDetails
对象用于GET和PUT,这里的逻辑非常简单,但是此对象的JSON Patch文档是针对PATCH请求发送的。这显然要复杂得多。
我们该如何去改变用户的组?最好的(“最好”的使用非常松散),我想出了是这样的:
int userId;
JsonPatchDocument<UserDetails> patch;
// This likely works fine, because the properties in `UserDetails`
// are named the same as those in `User`
IEnumerable<string> userPaths = new List<string> {"/givenName", "/surname"};
if (patch.Operations.Any(x => userPaths.Contains(x.path))) {
User user = _userService.GetUserByUserId(userId);
patch.ApplyTo(user);
_userService.SetUser(userId, user);
}
// Do specialised stuff for UserGroup
// Can't do ApplyTo() because `UserDetails.UserGroupId` is not named the same as `UserGroup.GroupId`
IEnumerable<Operation<UserDetails>> groupOps = patch.Operations.Where(x => x.path == "/userGroupId");
foreach (Operation<UserDetails> op in groupOps)
{
switch (op.OperationType)
{
case OperationType.Add:
case OperationType.Replace:
_groupService.SetOrUpdateUserGroup(userId, (int?)(op.value));
break;
case OperationType.Remove:
_groupService.RemoveUserGroup(userId);
break;
}
}
,这是相当可怕的华丽地。这是很多样板,并依靠一个魔术字符串。
,而无需请求Microsoft.AspNetCore.JsonPatch
API的变化,像
JsonPatchDocument<UserDetails> tmpPatch = new JsonPatchDocument<UserDetails>();
tmpPatch.Add(x => x.GivenName, String.Empty);
tmpPatch.Add(x => x.Surname, String.Empty);
IEnumerable<string> userPaths = tmpPatch.Operations.Select(x => x.path);
东西至少会干掉魔术字符串,但,IMO,这只是感觉错了!
JsonPatch在这方面似乎非常有限,似乎更适合于DAO(实体)和DTO(模型)之间存在1:1映射的系统。
任何人有任何好主意?不能很难打败我想出来的肚子!