如何在使用Flow的同时实现多重继承

时间:2018-12-30 22:57:02

标签: javascript node.js multiple-inheritance flowtype

我正在开发JS应用程序,我想在前端和后端之间共享包括我的数据类的代码。我正在使用业务逻辑创建基类,然后使用后端的数据库连接版本和前端的AJAX连接版本对其进行扩展。我有一个接受基类并返回具有标准DB功能的子类的函数,然后可以将该类与另一个类进行扩展,以使用其他特定方法。基本上是class DBUser extends DBWrapper(DBUserModel, BaseUser) {}

此代码均有效。现在,我正在尝试在我的代码库中实现Flow,并且抱怨我的子类无法实现该接口。静态代码检查器的动态组成可能过多。

我正在将Sequelize用于数据库。序列化行实例包含该行的所有属性,但是部分问题是现有的Flow类型似乎不知道这一点。因此,我应该能够通过DBUserModel对象来代替UserData,但是Flow不允许这样做。

这是Node.js后端代码的简化MCVE:

/* @flow */

type BaseData = {
  id?: ?number
};

class BaseClass<TData: BaseData = BaseData> {
  id: ?number;

  constructor(data?: TData) {
    this._initFromData(data);
  }
  _initFromData(data?: TData) {
    if (!data) {
      this.id = null;
      return;
    }
    this.id = data.id;
  }
}

type UserData = {
  id?: ?number,
  name: string,
};

export interface IUser {
  id: ?number;
  name: string;

  _initFromData(data: UserData): void;

  save(): Promise<?IUser>;
  reload(): Promise<?IUser>;
}

class BaseUser extends BaseClass<UserData> implements IUser {
  id: ?number;
  name: string;

  _initFromData(data?: UserData={}) {
    if (!data.name) {
      throw new Error('User needs a name');
    }
    this.id = data.id;
    this.name = data.name;
  }

  // these methods will be overridden in a child class
  async save() {}
  async reload() {}

  static async getById(id: number) {} // eslint-disable-line no-unused-vars
}

interface DBConnectedClass<TModel, TData> {
  _dbData: ?TModel;

  _initFromData(data: TModel & TData): void;

  save(): Promise<DBConnectedClass<TModel, TData>>;
  reload(): Promise<DBConnectedClass<TModel, TData>>;
}

// actually using Sequelize but mocking it here for a MCVE
class Model {
  update(data) {}
  reload() {}
  get(attr) {}
  static async create(data): Promise<Model> {return new this}
  static async findByPk(id): Promise<Model> {return new this}
}

function dbConnected<TModel: Model, TData: BaseData> (dbClass: Class<TModel>, baseClass: Class<BaseClass<TData>>) {
  return class extends baseClass implements DBConnectedClass<TModel, TData> {
    _dbData: ?TModel;

    constructor(data?: TData & TModel) {
      super(data);
      if (data instanceof dbClass) {
        this._dbData = data;
      }
    }
    _initFromData(data?: TData | TModel) {
      if (data instanceof dbClass) {
        super._initFromData(data.get({plain: true}));
      } else {
        super._initFromData(data);
      }
    }

    async save() {
      if (this._dbData) {
        await this._dbData.update(this);
      }
      if (this.id) {
        let data = (await dbClass.findByPk(this.id): TModel);
        this._dbData = data;
        if (this._dbData) {
          await this._dbData.update(this);
        }
      } else {
        let data: TModel = await dbClass.create(this);
        this._dbData = data;
        this.id = data.get({plain: true}).id;
      }
      return this;
    }

    async reload() {
      if (!this.id) {
        return this;
      }
      if (this._dbData) {
        await this._dbData.reload();
      }
      if (this.id) {
        let data = await dbClass.findByPk(this.id);
        this._dbData = data;
      }
      if (this._dbData) {
        this._initFromData(this._dbData);
      }
      return this;
    }

    static async getById(id: number) {
      const obj: ?TModel = await dbClass.findByPk(id);
      if (!obj) {
        throw new Error('not found');
      }
      return new this(obj);
    }
  }
}

const DBUserModel = Model; // actually it would be a subtype/subclass
class ConnectedUser extends dbConnected<DBUserModel, BaseUser>(DBUserModel, BaseUser) implements IUser, DBConnectedClass<DBUserModel, UserData> {
  // any user-specific DB code goes here
}

这是Flow错误:

Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ flow-test.js:138:1

Cannot implement IUser [1] with ConnectedUser because:
 • empty [2] is incompatible with UserData [3] in the first argument of property _initFromData.
 • property name is missing in <<anonymous class>> [4] but exists in IUser [5] in type argument R [6] of the return
   value of property reload.
 • property name is missing in <<anonymous class>> [4] but exists in IUser [7] in type argument R [6] of the return
   value of property save of type argument R [6] of the return value of property reload.
 • in the first argument of property _initFromData:
    • Either UserData [3] is incompatible with TData [8].
    • Or UserData [3] is incompatible with Model [9].
 • property name is missing in ConnectedUser [10] but exists in IUser [1].

           flow-test.js
       [3]  31│   _initFromData(data: UserData): void;
            32│
       [7]  33│   save(): Promise<?IUser>;
       [5]  34│   reload(): Promise<?IUser>;
              :
       [4]  75│   return class extends baseClass implements DBConnectedClass<TModel, TData> {
            76│     _dbData: ?TModel;
            77│
            78│     constructor(data?: TData & TModel) {
            79│       super(data);
            80│       if (data instanceof dbClass) {
            81│         this._dbData = data;
            82│       }
            83│     }
 [2][8][9]  84│     _initFromData(data?: TData | TModel) {
            85│       if (data instanceof dbClass) {
            86│         super._initFromData(data.get({plain: true}));
            87│       } else {
            88│         super._initFromData(data);
            89│       }
              :
           120│       }
           121│       if (this._dbData) {
           122│         this._initFromData(this._dbData);
           123│       }
           124│       return this;
           125│     }
           126│
           127│     static async getById(id: number) {
           128│       const obj: ?TModel = await dbClass.findByPk(id);
           129│       if (!obj) {
           130│         throw new Error('not found');
           131│       }
           132│       return new this(obj);
           133│     }
           134│   }
           135│ }
           136│
           137│ const DBUserModel = Model; // actually it would be a subtype/subclass
   [10][1] 138│ class ConnectedUser extends dbConnected<DBUserModel, BaseUser>(DBUserModel, BaseUser) implements IUser, DBConnectedClass<DBUserModel, UserData> {
           139│   // any user-specific DB code goes here
           140│ }
           141│

           /tmp/flow/flowlib_3f3cb1a7/core.js
       [6] 612│ declare class Promise<+R> {


Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ flow-test.js:138:1

Cannot implement DBConnectedClass [1] with ConnectedUser because:
 • TModel [2] is incompatible with Model [3] in property _dbData.
 • TModel [4] is incompatible with Model [3] in type argument TModel [5] of type argument R [6] of the return value of
   property reload.
 • TData [7] is incompatible with UserData [8] in type argument TData [9] of type argument R [6] of the return value
   of property reload.
 • property name is missing in BaseData [7] but exists in UserData [8] in type argument TData [9] of type argument
   R [6] of the return value of property reload.
 • in the first argument of property _initFromData:
    • Either Model [3] is incompatible with TData [10].
    • Or UserData [8] is incompatible with TData [10].
    • Or Model [3] is incompatible with TModel [11].
    • Or UserData [8] is incompatible with TModel [11].

           flow-test.js
    [5][9]  56│ interface DBConnectedClass<TModel, TData> {
              :
    [4][7]  75│   return class extends baseClass implements DBConnectedClass<TModel, TData> {
       [2]  76│     _dbData: ?TModel;
              :
  [10][11]  84│     _initFromData(data?: TData | TModel) {
              :
           135│ }
           136│
           137│ const DBUserModel = Model; // actually it would be a subtype/subclass
 [1][3][8] 138│ class ConnectedUser extends dbConnected<DBUserModel, BaseUser>(DBUserModel, BaseUser) implements IUser, DBConnectedClass<DBUserModel, UserData> {
           139│   // any user-specific DB code goes here
           140│ }
           141│

           /tmp/flow/flowlib_3f3cb1a7/core.js
       [6] 612│ declare class Promise<+R> {


Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ flow-test.js:138:77

Cannot call dbConnected with BaseUser bound to baseClass because UserData [1] is incompatible with BaseUser [2] in type
argument TData [3].

 [3]   7│ class BaseClass<TData: BaseData = BaseData> {
        :
 [1]  37│ class BaseUser extends BaseClass<UserData> implements IUser {
        :
     135│ }
     136│
     137│ const DBUserModel = Model; // actually it would be a subtype/subclass
 [2] 138│ class ConnectedUser extends dbConnected<DBUserModel, BaseUser>(DBUserModel, BaseUser) implements IUser, DBConnectedClass<DBUserModel, UserData> {
     139│   // any user-specific DB code goes here
     140│ }
     141│

我该如何教导Flow我的代码在做什么,或者稍微重构代码以更好地处理静态检查?

1 个答案:

答案 0 :(得分:0)

我最终通过更改数据库连接方式解决了这个问题。我不是从基类派生,而是使用mixin模式直接修改子类。 class DBUser extends User {}; dbMixin(DBUserModel, DBUser);

我遇到了Flow的问题,不允许我覆盖原型上的方法,但是我能够通过先转换为any,然后在内部修复this的类型转换来解决它功能。有点棘手,但必须做到。

/* @flow */

type BaseData = {
  id?: ?number
};

class BaseClass<TData: BaseData = BaseData> {
  id: ?number;

  constructor(data?: TData) {
    this._initFromData(data);
  }
  _initFromData(data?: TData) {
    if (!data) {
      this.id = null;
      return;
    }
    this.id = data.id;
  }

  static async getById(id) {}
}

type UserData = BaseData & {
  name: string,
};

export interface IUser {
  id: ?number;
  name: string;

  _initFromData(data: UserData): void;

  save(): Promise<?IUser>;
  reload(): Promise<?IUser>;
}

class BaseUser extends BaseClass<UserData> implements IUser {
  id: ?number;
  name: string;

  _initFromData(data?: UserData={}) {
    if (!data.name) {
      throw new Error('User needs a name');
    }
    this.id = data.id;
    this.name = data.name;
  }

  // these methods will be overridden in a child class
  async save() {}
  async reload() {}

  static async getById(id: number) {} // eslint-disable-line no-unused-vars
}

interface DBConnectedClass<TModel, TData> {
  id?: ?number;
  _dbData: ?TModel;

  constructor(data: TModel | TData): void;

  _initFromData(data: TModel | TData): void;

  save(): Promise<void>;
  reload(): Promise<void>;
}

// actually using Sequelize but mocking it here for a MCVE
class Model {
  id: ?number;
  name: string;

  update(data) {}
  reload() {}
  get(attr) {}
  static async create(data): Promise<Model> {return new this}
  static async findByPk(id): Promise<Model> {return new this}
}

function dbConnectedMixin<TModel: Model, TData: BaseData> (dbClass: Class<TModel>, baseClass: Class<DBConnectedClass<TModel, TData>>) {
  const _initFromData = baseClass.prototype._initFromData;
  (baseClass: any).prototype._initFromData = function(data?: TData | TModel) {
    const self = (this: DBConnectedClass<TModel, TData>);
    if (data instanceof dbClass) {
      self._dbData = data;
    }
    _initFromData.call(self, data);
  };

  // const save = baseClass.prototype.save;
  (baseClass: any).prototype.save = async function() {
    const self = (this: DBConnectedClass<TModel, TData>);
    if (self._dbData) {
      await self._dbData.update(self);
    }
    if (self.id) {
      let data = (await dbClass.findByPk(self.id): TModel);
      self._dbData = data;
      if (self._dbData) {
        await self._dbData.update(self);
      }
    } else {
      let data: TModel = await dbClass.create(self);
      self._dbData = data;
      self.id = data.get({plain: true}).id;
    }
  };

  // const reload = baseClass.prototype.reload;
  (baseClass: any).prototype.reload = async function() {
    const self = (this: DBConnectedClass<TModel, TData>);
    if (!self.id) {
      return;
    }
    if (self._dbData) {
      await self._dbData.reload();
    }
    if (self.id) {
      let data = await dbClass.findByPk(self.id);
      self._dbData = data;
    }
    if (self._dbData) {
      self._initFromData(self._dbData);
    }
  };

  (baseClass: any).getById = async function(id: number) {
    const self = (this: Class<DBConnectedClass<TModel, TData>>);
    const obj: ?TModel = await dbClass.findByPk(id);
    if (!obj) {
      throw new Error('not found');
    }
    return new self(obj);
  };
}

const DBUserModel = Model; // actually it would be a subtype/subclass
class ConnectedUser extends BaseUser implements IUser, DBConnectedClass<DBUserModel, UserData> {
  _dbData: ?DBUserModel;

  // any user-specific DB code goes here
}
dbConnectedMixin<DBUserModel, UserData>(DBUserModel, ConnectedUser);