message: Unlink deleted files
diff: @@ -9,6 +9,7 @@ import {Lecture} from '../models/Lecture';
  import {Unit} from '../models/units/Unit';
  import {IUnit} from '../../../shared/models/units/IUnit';
  import {IVideoUnitModel, VideoUnit} from '../models/units/VideoUnit';
  +import {IFileUnitModel, FileUnit} from '../models/units/FileUnit';
  import {IVideoUnit} from '../../../shared/models/units/IVideoUnit';
  const uploadOptions = {dest: 'uploads/' };
  @@ -34,7 +35,35 @@ export class UnitController {
  @Put('/:id')
  updateUnit(@Param('id') id: string, @Body() unit: IUnit) {
  - return Unit.findByIdAndUpdate(id, unit, {'new': true})
  + return Unit.findById(id).then((oldUnit) => {
  + if (!oldUnit) {
  + throw new NotFoundError();
  + }
  + // pre update: delete removed files
  + if (oldUnit instanceof VideoUnit) {
  + (<IVideoUnitModel>oldUnit).files.forEach((file: any) => {
  + // if not present in new: delete
  + if (!(<IVideoUnitModel>unit).files.some((newFile) => newFile.name === file.name)) {
  + try {
  + fs.unlinkSync(file.path);
  + } catch (e) {} // silently discard file not found errors
  + }
  + });
  + return VideoUnit;
  + }
  + if (oldUnit instanceof FileUnit) {
  + (<IFileUnitModel>oldUnit).files.forEach((file: any) => {
  + // if not present in new: delete
  + if (!(<IFileUnitModel>unit).files.some((newFile) => newFile.name === file.name)) {
  + try {
  + fs.unlinkSync(file.path);
  + } catch (e) {} // silently discard file not found errors
  + }
  + });
  + return FileUnit;
  + }
  + return Unit;
  + }).then((model) => model.findByIdAndUpdate(id, unit, {'new': true}))
  .then((u) => u.toObject());
  }
  @@ -45,9 +74,22 @@ export class UnitController {
  throw new NotFoundError();
  }
  - if (unit instanceof VideoUnit && (<IVideoUnitModel>unit).filePath) {
  - fs.unlinkSync((<IVideoUnitModel>unit).filePath);
  + if (unit instanceof VideoUnit) {
  + (<IVideoUnitModel>unit).files.forEach((file: any) => {
  + try {
  + fs.unlinkSync(file.path);
  + } catch (e) {} // silently discard file not found errors
  + });
  + }
  +
  + if (unit instanceof FileUnit) {
  + (<IFileUnitModel>unit).files.forEach((file: any) => {
  + try {
  + fs.unlinkSync(file.path);
  + } catch (e) {} // silently discard file not found errors
  + });
  }
  +
  return Lecture.update({}, {$pull: {units: id}});
  })
  .then(() => Unit.findByIdAndRemove(id))
  