Сохранение многих для многих в Nestjs - PullRequest
0 голосов
/ 19 февраля 2020

У меня есть ресурс сущности со связями «многие ко многим» с местоположением

@Entity("resource")
export class Resource extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 500, nullable: true })
  name: string;

  @ManyToMany(
    type => Location,
    location => location.resources,
    { cascade: true }
  )
  @JoinTable({
    name: "resource_location",
  })
  locations: Location[];
}
@Entity("location")
export class Location extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 500, nullable: true })
  name: string;

  @ManyToMany(
    type => Resource,
    resource => resource.locations
  )
  resources: Resource[];

}

И я использую плагин nest js crud для контроллера

@Crud({
  model: {
    type: Resource
  }
})
@Controller("resource")
export class ResourceController {
  constructor(public service: ResourceService) {}
}

Я хочу иметь возможность передавать и возражать подобным образом, и он создаст все записи отношений

POST /resource
{
  name: 'resourceName',
  locations: [1,2] // provided these locations are in the locations table
}

этот формат выглядит как стандарт в других средах, таких как django, но не работает из коробки в гнезде с сырой / типорм. Также пытаться реализовать функциональные швы тоже немного сложно, если бы я попытался переопределить метод следующим образом:

export class ResourceController {
  constructor(
    public service: ResourceService,
    private readonly locationService: LocationService
  ) {}

  get base(): CrudController<Resource> {
    return this;
  }

  @Override("createOneBase")
  async createOne(
    @ParsedRequest() req: CrudRequest,
    @ParsedBody() dto: Resource
  ) {
    let locations;
    if (dto.locations) {
      locations = dto.locations.map(
        async v => await this.locationService.findOne(v)
      );
    }
    dto.locations = locations;

    return this.base.createOneBase(req, dto);
  }
}

Я просто получаю сообщение об ошибке:

Nest] 18527   - 02/18/2020, 4:31:50 PM   [ExceptionsHandler] Cannot read property 'constructor' of undefined +1602ms
TypeError: Cannot read property 'constructor' of undefined
    at Object.encrypt (/Users/natedeazy/projects/MedOneScheduling/scheduling-backend/node_modules/typeorm-encrypted/lib/transformers/index.js:14:83)
    at AutoEncryptSubscriber.beforeInsert (/Users/natedeazy/projects/MedOneScheduling/scheduling-backend/node_modules/typeorm-encrypted/lib/subscribers/AutoEncryptSubscriber.js:18:24)
    at /Users/natedeazy/projects/MedOneScheduling/scheduling-backend/node_modules/typeorm/subscriber/Broadcaster.js:39:54
    at Array.forEach (<anonymous>)
    at Broadcaster.broadcastBeforeInsertEvent (/Users/natedeazy/projects/MedOneScheduling/scheduling-backend/node_modules/typeorm/subscriber/Broadcaster.js:37:53)
    at /Users/natedeazy/projects/MedOneScheduling/scheduling-backend/node_modules/typeorm/persistence/SubjectExecutor.js:162:99
    at Array.forEach (<anonymous>)
    at SubjectExecutor.broadcastBeforeEventsForAll (/Users/natedeazy/projects/MedOneScheduling/scheduling-backend/node_modules/typeorm/persistence/SubjectExecutor.js:162:33)
    at SubjectExecutor.<anonymous> (/Users/natedeazy/projects/MedOneScheduling/scheduling-backend/node_modules/typeorm/persistence/SubjectExecutor.js:68:50)
    at step (/Users/natedeazy/projects/MedOneScheduling/scheduling-backend/node_modules/tslib/tslib.js:136:27)
...