我试图在HasMany
中定义相关模型,例如@types/loopback definitions关系我已经为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)
Role模型具有以下内置关系(如loopback模块中所定义):
"relations": {
"principals": {
"type": "hasMany",
"model": "RoleMapping",
"foreignKey": "roleId"
}
}
在Typescript中,此函数将按如下方式使用:
await createdRole.principals.create({
principalType: loopback.RoleMapping.USER,
principalId: createdUser.id
});
(注意:loopback.RoleMapping.USER是即将到来的PR中的一个常量我将提交给DT)
所以现在,我需要将此接口附加到Role模型,并让它引用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 :(得分:0)
好的,对于遇到此问题的其他人来说,关键是:
在界面中,将其设为与此<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
})