entity-ref.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { ClassDeclaration, Node, SyntaxKind, Type } from 'ts-morph';
  2. export class EntityRef {
  3. constructor(public classDeclaration: ClassDeclaration) {}
  4. get name(): string {
  5. return this.classDeclaration.getName() as string;
  6. }
  7. get nameCamelCase(): string {
  8. return this.name.charAt(0).toLowerCase() + this.name.slice(1);
  9. }
  10. isTranslatable() {
  11. return this.classDeclaration.getImplements().some(i => i.getText() === 'Translatable');
  12. }
  13. isTranslation() {
  14. return this.classDeclaration.getImplements().some(i => i.getText().includes('Translation<'));
  15. }
  16. hasCustomFields() {
  17. return this.classDeclaration.getImplements().some(i => i.getText() === 'HasCustomFields');
  18. }
  19. getProps(): Array<{ name: string; type: Type; nullable: boolean }> {
  20. return this.classDeclaration.getProperties().map(prop => {
  21. const propType = prop.getType();
  22. const name = prop.getName();
  23. return { name, type: propType.getNonNullableType(), nullable: propType.isNullable() };
  24. });
  25. }
  26. getTranslationClass(): ClassDeclaration | undefined {
  27. if (!this.isTranslatable()) {
  28. return;
  29. }
  30. const translationsDecoratorArgs = this.classDeclaration
  31. .getProperty('translations')
  32. ?.getDecorator('OneToMany')
  33. ?.getArguments();
  34. if (translationsDecoratorArgs) {
  35. const typeFn = translationsDecoratorArgs[0];
  36. if (Node.isArrowFunction(typeFn)) {
  37. const translationClass = typeFn.getReturnType().getSymbolOrThrow().getDeclarations()[0];
  38. return translationClass as ClassDeclaration;
  39. }
  40. }
  41. }
  42. }