custom-fields-validation-subscriber.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { Injectable } from '@nestjs/common';
  2. import { EntitySubscriberInterface, InsertEvent, UpdateEvent } from 'typeorm';
  3. import { ConfigService } from '../config/config.service';
  4. import { CustomFields, HasCustomFields } from '../config/custom-field/custom-field-types';
  5. import { Logger } from '../config/logger/vendure-logger';
  6. import { TransactionalConnection } from './transactional-connection';
  7. @Injectable()
  8. export class CustomFieldsValidationSubscriber implements EntitySubscriberInterface {
  9. constructor(
  10. private connection: TransactionalConnection,
  11. private configService: ConfigService,
  12. ) {
  13. connection.rawConnection.subscribers.push(this);
  14. }
  15. validateCustomFields(entityName: string, entity: Partial<HasCustomFields>) {
  16. const cf: any = (entity as any).customFields;
  17. if (cf === null || cf === undefined || typeof cf !== 'object') {
  18. return;
  19. }
  20. const config = this.resolveCustomFieldsConfig(entityName);
  21. if (!config || config.length === 0) {
  22. return;
  23. }
  24. const validFieldNames = new Set(config.map(field => field.name));
  25. for (const key of Object.keys(cf)) {
  26. if (!validFieldNames.has(key)) {
  27. Logger.warn(`Custom field ${key} not found for entity ${entityName}`);
  28. }
  29. }
  30. }
  31. private resolveCustomFieldsConfig(entityName: string) {
  32. let cfg = this.configService.customFields[entityName as keyof CustomFields];
  33. if (!cfg && entityName.endsWith('Translation')) {
  34. const base = entityName.slice(0, -'Translation'.length);
  35. cfg = this.configService.customFields[base as keyof CustomFields];
  36. }
  37. return cfg;
  38. }
  39. beforeInsert(event: InsertEvent<any>) {
  40. if (event.entity === undefined) {
  41. return;
  42. }
  43. const entityName = event.entity.constructor.name;
  44. this.validateCustomFields(entityName, event.entity);
  45. }
  46. beforeUpdate(event: UpdateEvent<any>) {
  47. if (event.entity === undefined) {
  48. return;
  49. }
  50. const entityName = event.entity.constructor.name;
  51. this.validateCustomFields(entityName, event.entity);
  52. }
  53. }