共享API和前端之间的接口

问题描述 投票:0回答:1

我正在发展双方。 API位于Angular中的nest.js和前端。双方都使用打字稿,我面临共享接口的问题,应该是相同的。例如ILoginRequest和ILoginResponse。我想将这两个项目都放在单独的GIT存储库中。我应该使用GIT子模块与第三个共享GIT仓库或以某种方式创建共享的npm包或是否有一些很好的工具来自动生成类(从swagger定义)到前端或其他任何东西?

angular git typescript nestjs
1个回答
1
投票

遇到了同样的问题,并考虑了一些替代方案。这是我考虑的和我选择的:

  1. 将实体定义分离为单独的代码库 - 可能在不同的git仓库中。问题是Nest使用Angular不理解的装饰器。这意味着我必须将Nest作为依赖项包含在内,这似乎是一个坏主意或创建存根装饰器 - 浪费时间。被拒绝
  2. 创建节点包 - 与#1相同的问题。被拒绝
  3. 复制粘贴。后端和前端项目都有一个实体文件夹。后端的实体是用TypeORM装饰器(对我来说)装饰的类。我将它们复制到前端的实体目录并将它们转换为接口,因为你从httpclient库中获取了什么(应该符合接口的对象 - 而不是类实例)。采用

最后,看看这些评论,我看不出GraphQL如何帮助你,因为你没有尝试利用现有的界面 - 希望听到某人的意见:)


1
投票

注意:我最近偶然发现typeorm-entitysharer“可用于创建基于相同TypeORM实体的客户端/服务器类,允许您共享它们。”它让您可以更好地控制您想要分享的内容,您可以查看他们的示例。我没有选择使用它,因为我觉得这对我来说有点过分。但是,这就是我构建上一个项目的方式:


I have my frontend and backend in one repository, but I guess you could have them separate, but you would still need to keep them next to each other somehow. The file structure would be something like this:
workspace
  ├─backend        <- repo #1
  │   ├─src
  │   │   ├─shared <- shared code goes here
  │   │   └─proxy.ts
  │   └─tsconfig.json
  └─frontend       <- repo #2
      ├─src
      │   └─proxy.ts
      └─tsconfig.json

然后在backend/tsconfig.json你介绍

{
    ...
    "paths": {
        "@shared/*": [ "src/shared/*" ],
    }
}

frontend/tsconfig.json你介绍

{
    ...
    "paths": {
        "@shared/*": [ "../backend/src/shared/*" ],

        // if you're using TypeORM, this package has dummy decorators
        "typeorm": [ "node_modules/typeorm/typeorm-model-shim.js" ]
        // you can do the same for other packages, point them to dummy paths

        // altirnatively you can route the shared imports through the proxy.ts
        // and replace them in frontend/src/proxy.ts with dummy ones
    }
}

也不要忘记在你的前端npm i typeorm

Example

让我们说我在backend/src/shared/user.entity.ts有这个

import { PrimaryGeneratedColumn, Column } from 'typeorm';

export class UserEntity
{
    @PrimaryGeneratedColumn() id: number;
    @Column() name: string;
    @Column() password: string;
}

现在,我可以在任何地方使用它:

import { UserEntity } from '@shared/model/user.entity';

在后端,很明显,在前端,@shared/model/user.entity被映射到../backend/src/shared/model/user.entity,实体内部的import from 'typeorm'被映射到虚拟包。

© www.soinside.com 2019 - 2024. All rights reserved.