我正在发展双方。 API位于Angular中的nest.js和前端。双方都使用打字稿,我面临共享接口的问题,应该是相同的。例如ILoginRequest和ILoginResponse。我想将这两个项目都放在单独的GIT存储库中。我应该使用GIT子模块与第三个共享GIT仓库或以某种方式创建共享的npm包或是否有一些很好的工具来自动生成类(从swagger定义)到前端或其他任何东西?
遇到了同样的问题,并考虑了一些替代方案。这是我考虑的和我选择的:
最后,看看这些评论,我看不出GraphQL如何帮助你,因为你没有尝试利用现有的界面 - 希望听到某人的意见:)
注意:我最近偶然发现typeorm-entitysharer“可用于创建基于相同TypeORM实体的客户端/服务器类,允许您共享它们。”它让您可以更好地控制您想要分享的内容,您可以查看他们的示例。我没有选择使用它,因为我觉得这对我来说有点过分。但是,这就是我构建上一个项目的方式:
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
。
让我们说我在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'
被映射到虚拟包。