反对循环依赖和打字稿定义

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

我们的数据模型中有两个对象相互引用,在数据库级别,每个“客户端”都拥有一些“范围”(

HasManyRelation
)。并且每个“范围”都有许多允许访问的“客户端”(
ManyToManyRelation
)。异议模型看起来有点像:

import {Model, ModelObject} from "objection";
import {OauthClientUriModel} from "./OauthClientUriModel";
import {OauthScopeModel} from "./OauthScopeModel";

export class OauthClientModel extends Model {

    id!: number;
    static get useLimitInFirst(): boolean {
        return true;
    }
    static get tableName(): string {
        return "oauth_client"
    }

    static get idColumn(): string {
        return "id";
    }


    name!: string;
    static get NameColumn(): string {
        return "name";
    }

    _scopes!: ModelObject<OauthScopeModel>[]|null;
    static get relationMappings() {
        return {
            _scopes: {
                relation: Model.HasManyRelation,
                modelClass: OauthScopeModel,
                join: {
                    from: 'oauth_client.id',
                    to: 'oauth_scope.owner',
                }
            }
        }
    }
}

_scopes!: ModelObject<OauthScopeModel>[]|null;
行用于在返回的查询中提供打字稿信息。 现在在范围对象中,我们需要能够访问所有允许访问它的客户端。

export class OauthScopeModel extends Model {

    id!: number;
    static get useLimitInFirst(): boolean {
        return true;
    }
    static get tableName(): string {
        return "oauth_scope"
    }

    static get idColumn(): string {
        return "id";
    }
  
    name!: string;
    static get nameColumn(): string {
        return "name";
    }

    owner!: number;
    static get ownerColumn(): string {
        return "owner";
    }

    _allowed_clients!: ModelObject<OauthClientModel>|null;
    static get relationMappings() {
        return {
            _allowed_clients: {
                relation: Model.ManyToManyRelation,
                modelClass: OauthClientModel,
                join: {
                    from: 'oauth_scope.id',
                    through: {
                        from: 'oauth_scope_client.scope',
                        to: 'oauth_scope_client.client'
                    },
                    to: 'oauth_client.id',
                }
            },
        }
    }
}

然而,这会导致循环导入错误:

_allowed_clients is referenced directly or indirectly in its own type annotation at the _allowed_clients!: ModelObject<OauthClientModel>[]|null;

如何在保持强类型安全的同时防止这种循环导入? (所以不要让其中一个数组具有

any
类型)。

typescript circular-dependency objection.js
© www.soinside.com 2019 - 2024. All rights reserved.