factory.ts 732 B

12345678910111213141516171819202122232425262728
  1. import Attribute, { AttributeConstructor } from './attributes/base';
  2. interface AttributeMapType {
  3. [key: string]: any;
  4. }
  5. // 所有的 attribute map
  6. const ATTRIBUTE_MAP: AttributeMapType = {};
  7. /**
  8. * 通过类型获得 Attribute 类
  9. * @param type
  10. */
  11. const getAttribute = (type: string) => {
  12. return ATTRIBUTE_MAP[type.toLowerCase()];
  13. };
  14. const registerAttribute = (type: string, ctor: AttributeConstructor) => {
  15. // 注册的时候,需要校验 type 重名,不区分大小写
  16. if (getAttribute(type)) {
  17. throw new Error(`Attribute type '${type}' existed.`);
  18. }
  19. // 存储到 map 中
  20. ATTRIBUTE_MAP[type.toLowerCase()] = ctor;
  21. };
  22. export { getAttribute, registerAttribute, Attribute };
  23. export * from './interface';