create-translatable.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { Type } from 'shared/shared-types';
  2. import { Connection } from 'typeorm';
  3. import { Translatable, TranslatedInput, Translation } from '../../common/types/locale-types';
  4. /**
  5. * Returns a "save" function which uses the provided connection and dto to
  6. * save a translatable entity and its translations to the DB.
  7. */
  8. export function createTranslatable<T extends Translatable>(
  9. entityType: Type<T>,
  10. translationType: Type<Translation<T>>,
  11. beforeSave?: (newEntity: T) => void,
  12. ) {
  13. return async function saveTranslatable(
  14. connection: Connection,
  15. input: TranslatedInput<T>,
  16. data?: any,
  17. ): Promise<T> {
  18. const entity = new entityType(input);
  19. const translations: Array<Translation<T>> = [];
  20. if (input.translations) {
  21. for (const translationInput of input.translations) {
  22. const translation = new translationType(translationInput);
  23. translations.push(translation);
  24. await connection.manager.save(translation);
  25. }
  26. }
  27. entity.translations = translations;
  28. if (typeof beforeSave === 'function') {
  29. await beforeSave(entity);
  30. }
  31. return await connection.manager.save(entity, { data });
  32. };
  33. }