2017-09-18 41 views
0

我試圖定義相關的模型,如內@types/loopback definitions打字稿/環路相關型號

HasMany關係我已經定義的hasMany的接口,因爲它是實現:

interface IHasMany { 
     /** 
     * Create a target model instance 
     * @param {Object} targetModelData The target model data 
     * @param {Function} callback The callback function 
     */ 
     // HasMany.prototype.create = function(targetModelData, options, cb) 
     create<T = any>(targetModelData: any, callback?: (err: Error, instance: T) => void): Promise<T> | void; 

(snip ... other functions findById, exists, updateById, destroyById omitted for bevity) 

榜樣具有以下內置關係(如在回送模塊中定義的):

"relations": { 
    "principals": { 
     "type": "hasMany", 
     "model": "RoleMapping", 
     "foreignKey": "roleId" 
    } 
} 

在Typescript中,此函數將用作f ollows:

await createdRole.principals.create({ 
    principalType: loopback.RoleMapping.USER, 
    principalId: createdUser.id 
}); 

(注:loopback.RoleMapping.USER是在即將到來的PR我要提交至DT常數)

所以,現在,我需要這個接口連接到示範作用,並讓它引用RoleMapping模型。

class Role extends PersistedModel { 
     static OWNER: string; 
     static RELATED: string; 
     static AUTHENTICATED: string; 
     static UNAUTHENTICATED: string; 
     static EVERYONE: string; 

     /** HasMany RoleMappings */ 
     static async principals = ???? 

任何下一步的指導?好像我需要延長IHasMany是RoleMapping特定的(如IHaveManyRoleMappings) - 可能使用this post,然後讓校長是這樣的:

static async principals = class RoleMappings implements IHasManyRoleMappings {}; 

回答

0

OK,其他任何人碰到這個問題來了,這裏的關鍵:

在接口方面,使其與此<T>通用接口:

interface HasMany<T> { 
     /** 
     * Find a related item by foreign key 
     * @param {*} id The foreign key 
     * @param {Object} [options] Options 
     * @param {instanceCallback} callback 
     */ 
     // HasMany.prototype.findById = function(fkId, options, cb) 
     findById<T = any>(id: any, options?: any, callback?: (err: Error, instance: T) => void): Promise<T> | void; 
(snip ... other functions findById, exists, updateById, destroyById omitted for bevity) 

接下來,只需簡單的在這你的接口/類,如下所示:

class Role extends PersistedModel { 
     static OWNER: string; 
     static RELATED: string; 
     static AUTHENTICATED: string; 
     static UNAUTHENTICATED: string; 
     static EVERYONE: string; 

     /** HasMany RoleMappings */ 
     // createdRole.principals.create({principalType: loopback.RoleMapping.USER, principalId: createdUser.id}); 
     principals: HasMany<RoleMapping>; 

現在很容易使用,如下所示:

await createdRole.principals.create({ 
    principalType: loopback.RoleMapping.USER, 
    principalId: createdUser.id 
})