DDD:将分页信息从我的仓库返回给 NodeJS 中的 API 响应



我有一个 API 而不是返回用户列表/api/user :

[{
id: 1,
firstname: 'toto',
lastname: 'titi'
},
{
...
}]

现在我想从我的用户存储库中添加分页信息

{
result: [{
id: 1,
firstname: 'toto',
lastname: 'titi'
},
{
...
}],
pagination: {
totalPages: 75,
page: 2,
limit: 25
}
}

我的控制器(接口层(

...
router.get('/users', ctx => {
getUsersUseCase
.execute(ctx.state.limit, ctx.state.offset)
.then(data => {
ctx.response.status = Status.OK;
ctx.response.body = data;
})
.catch(error => {
ctx.response.status = Status.INTERNAL_SERVER_ERROR;
ctx.response.body = error;
});
});
...

在我的应用层中,我有一个getUsers用例:

// app/getUsers.js
module.exports = () => {
const execute = (limit, offset) => {
const userListPaginated = userRepository.find(limit, offset);
return userListPaginated; // before it returned just a User Array
};
return {
execute,
};
};

我的域 用户模型:

// domain/User.js
module.exports = {
id: Integer,
username: String,
email: String,
firstName: String,
lastName: String
}

我的域用户列表分页模型:

// domain/UserListPaginated.js
module.exports = {
result: [], // User list
pagination: {}, // pagination informations
}

在我的用户存储库中(我使用 https://github.com/aravindnc/mongoose-paginate-v2 作为分页信息(:


class UserRepository {
constructor({ model }) {
this.userModel = model; // mongoose model
}
async find(limit, offset) {
var userListPaginated;
this.userModel.paginate({}, { offset, limit }).then(function(result) {
userListPaginated = { 
result: result.docs,
pagination: {
totalPages: result.totalPages
limit: result.limit - 10
offset: result.offset
}
});
return userListPaginated; // before returned just a array of user model
}

我认为,我的问题是分页信息与域无关(在UserListPaginated.js中(。 它只是在这里返回到 API 控制器。但是我需要从存储库返回此信息并跨域层。

什么是好的DDD蔬菜?

谢谢

最好完全绕过查询的域模型 (CQRS(。让域模型专注于写入/命令,并在其他地方处理读取/查询。例如,您可以在application层中有一个IUserQueryService接口,该接口在infrastructure层中实现(甚至可以由同一存储库类实现(。

不过,务实很重要。如果您习惯在查询结果中直接使用域实体,那么用查询问题(如分页状态(污染存储库的界面可能是可以接受的。这始终是一个权衡的问题,当它不切实际时,你不应该追求纯洁。

感谢您的回答。目前,我不在我的干净体系结构中使用 CQRS。

在我的用户控制器中,如果我调用两个用例,您认为这是一个更好的主意吗?getUserCountUseCase这是一个非常好的用例?

router.get('/users', ctx => {
const usersPromise = getUsersUseCase // Old use case (just a users array)
.execute(ctx.state.limit, ctx.state.offset)
const userCountPromise = getUserCountUseCase
.execute(ctx.state.limit, ctx.state.offset)
Promise.all([userCountPromise, usersPromise])
.then((values) => {
const [count, users] = values;
const userListPaginated = {
result:  users,
pagination: {
totalPages: count,
page: Math.ceil((offset + 1) / limit),
limit: ctx.state.limit
}
}
ctx.response.status = Status.OK;
ctx.response.body = userListPaginated;
})
});

最新更新