对象建模和 JSON 响应

Object modeling and JSON responses

我正在尝试使用允许您同时实现 API 和用户界面 (NextJS) 的框架来实现 Web 应用程序。而且我不确定建模和 Json 响应的最佳实践是什么。

注意事项

问题
如果我想归档这个模式,我不得不声明两个接口:一个带有简单的浅引用(外键),另一个允许嵌入对象。

示例: 假设我有一个博客 Post 模型:Post:

interface Post {
    id: string;
    creatorId: string;
}

还有另一个用户模型:User

interface User {
    id: string;
    name: string;
}

因此,为了从数据库中进行解析,我使用了 Post 接口,它准确地表示了它在数据库中的存储方式。
但是如果我想 return 到嵌套对象的前端,我应该依赖类似于以下的模型:

interface PostWithNested {
    id: string;
    creator : User;
}

这个界面的JSON是这样的:

{
    "id": "X",
    "creator": {
        "id" : "Y",
        "name": "Z";
    },
}

API 的示例,其中必须使用接口从数据库进行解析:

...
const postsRepository = getRepository(Post); // has shallow reference
const singlePost : Post = await postsRepository.findById(X);
// Adding nested object
const postWithNested : PostWithNested = {
    id : singlePost.id,
    user : userInstance,
}

res.status(200).json({post : postWithNested }

那么是否有一种解决方法可以不声明两个本质上相同但在对其相关对象的引用上不同的接口?

您可以使用可选 creator 创建接口 Post。例如

interface User {
    id: string;
    name: string;
}
interface Post {
    id: string;
    creatorId: string;
    creator?: User; //it will be not populated, if it has no data
}

每当您从 API 收到 creator 数据时,它就会自动填充。否则,它将始终在您的 Post 数据中取消设置。您可以验证日志 here.

以下是我们如何将其集成到您的代码中

const postsRepository = getRepository(Post);
const singlePost : Post = await postsRepository.findById(X);

res.status(200).json({post : singlePost })

同样,如果你们有one-many关系。比如1用户有很多帖子,你就会有这样的界面结构

interface User {
    id: string;
    name: string;
    posts?: Post[]; //can keep many posts belong to this user
}
interface Post {
    id: string;
    creatorId: string;
    creator?: User; 
}