From 5568f44d4348846330602936c9796d6e3d49860b Mon Sep 17 00:00:00 2001
From: "maksi.ageev" <maksi.ageev@x5.ru>
Date: Thu, 14 Jul 2022 12:54:24 +0400
Subject: [PATCH] fix registration

---
 src/artist/artist.service.ts     | 12 ++++++---
 src/auth/auth.service.ts         |  4 ++-
 src/painting/painting.service.ts | 43 ++++++++++++++++++++++++--------
 3 files changed, 44 insertions(+), 15 deletions(-)

diff --git a/src/artist/artist.service.ts b/src/artist/artist.service.ts
index ce71544..1c1b204 100644
--- a/src/artist/artist.service.ts
+++ b/src/artist/artist.service.ts
@@ -17,10 +17,10 @@ import { BadRequestException, Injectable, NotFoundException } from '@nestjs/comm
 import { InjectModel } from '@nestjs/mongoose';
 import omit from 'lodash.omit';
 import { LeanDocument, Model, Types } from 'mongoose';
+import { PaintingService } from 'src/painting/painting.service';
 import { GenreService } from '../genre/genre.service';
 import { Genre } from '../genre/schemas/genre.schema';
 import { ImageService } from '../image/image.service';
-import { PaintingService } from '../painting/painting.service';
 import { Painting } from '../painting/schemas/painting.schema';
 import { User } from '../user/schemas/user.schema';
 import { UserService } from '../user/user.service';
@@ -29,6 +29,7 @@ import { Artist } from './schemas/artist.schema';
 @Injectable()
 export class ArtistService {
   constructor(
+    private readonly paintingService: PaintingService,
     private readonly userService: UserService,
     private readonly imageService: ImageService,
     private readonly genreService: GenreService,
@@ -95,7 +96,7 @@ export class ArtistService {
     ];
 
     if (sortBy && ['asc', 'desc'].includes(orderBy)) {
-      const order = orderBy === 'asc' ? 1 : -1
+      const order = orderBy === 'asc' ? 1 : -1;
       aggregateQuery.push({ $sort: { [sortBy]: order } });
     }
     if (pagination.perPage && pagination.pageNumber)
@@ -198,15 +199,20 @@ export class ArtistService {
     artistCredentials: Omit<LeanDocument<Artist>, 'user'>,
   ): Promise<void | never> {
     const artistId = Types.ObjectId();
+    const { paintings, ...demoArtist } = artistCredentials;
 
     const docArtist = {
-      ...artistCredentials,
+      ...demoArtist,
       _id: artistId,
       user: user._id,
     } as LeanDocument<Artist> & { _id: Types.ObjectId };
 
     const artist = new this.ArtistModel(docArtist);
     await artist.save();
+
+    paintings.forEach((painting) => {
+      this.paintingService.registrationCreate(artist._id, painting);
+    });
   }
 
   async update(
diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts
index 6121276..5795ccf 100644
--- a/src/auth/auth.service.ts
+++ b/src/auth/auth.service.ts
@@ -37,7 +37,9 @@ export class AuthService {
     const artists = await this.ArtistModel.find(
       { user: demoUser._id },
       { _id: false, user: false, __v: false },
-    ).exec();
+    )
+      .populate('paintings')
+      .exec();
 
     artists.forEach((artist) => {
       this.artistService.registrationCreate(user, artist.toObject());
diff --git a/src/painting/painting.service.ts b/src/painting/painting.service.ts
index bda549a..21565ed 100644
--- a/src/painting/painting.service.ts
+++ b/src/painting/painting.service.ts
@@ -6,9 +6,9 @@ import type { IPainting } from './painting.interface';
 import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
 import { InjectModel } from '@nestjs/mongoose';
 import omit from 'lodash.omit';
-import { Model, Types } from 'mongoose';
-import { ArtistService } from '../artist/artist.service';
+import { LeanDocument, Model, Types } from 'mongoose';
 import { Artist } from '../artist/schemas/artist.schema';
+import { IImage } from '../image/image.interface';
 import { ImageService } from '../image/image.service';
 import { Painting } from './schemas/painting.schema';
 
@@ -42,16 +42,25 @@ export class PaintingService {
 
     await painting.save();
 
-    const artist = await this.ArtistModel.findOne({ _id: artistId }).exec();
+    await this.bindPaintingToArtist(artistId, painting);
 
-    if (!artist.paintings.length) {
-      artist.mainPainting = painting;
-    }
+    return omit(painting.toObject(), 'artist');
+  }
 
-    await this.ArtistModel.updateOne({ _id: artistId }, { $push: { paintings: painting } });
-    await artist.save();
+  async registrationCreate(
+    artistId: string,
+    { name, yearOfCreation, image }: LeanDocument<Painting>,
+  ): Promise<void | never> {
+    const painting = new this.PaintingModel({
+      name,
+      yearOfCreation,
+      artist: Types.ObjectId(artistId),
+      image,
+    });
 
-    return omit(painting.toObject(), 'artist');
+    await painting.save();
+
+    await this.bindPaintingToArtist(artistId, painting);
   }
 
   async findAll(artistId: string): Promise<IPainting[]> {
@@ -60,7 +69,7 @@ export class PaintingService {
     return this.PaintingModel.find({ artist }, { artist: false }).populate('image').exec();
   }
 
-  async findOne(_id: string): Promise<IPainting | never> {
+  async findOne(_id: string): Promise<(IPainting & { image: IImage }) | never> {
     const painting = await this.PaintingModel.findOne({ _id }, { artist: false })
       .populate('image')
       .exec();
@@ -106,7 +115,8 @@ export class PaintingService {
       },
     );
 
-    if (matchedCount === 0) ArtistService.throwNotFoundException();
+    // TODO: нужно разобраться с круговой зависимостью импортов
+    // if (matchedCount === 0) ArtistService.throwNotFoundException();
 
     if (!painting) PaintingService.throwNotFoundException();
 
@@ -115,6 +125,17 @@ export class PaintingService {
     return Types.ObjectId(_id);
   }
 
+  private async bindPaintingToArtist(artistId: string, painting: Painting) {
+    const artist = await this.ArtistModel.findOne({ _id: artistId }).exec();
+
+    if (!artist.paintings.length) {
+      artist.mainPainting = painting;
+    }
+
+    await this.ArtistModel.updateOne({ _id: artistId }, { $push: { paintings: painting } });
+    await artist.save();
+  }
+
   private async findPaintingByName(artistId: string, name: string) {
     const { _id: artist } = await this.ArtistModel.findOne({ _id: artistId }).exec();
     return await this.PaintingModel.findOne({ artist, name }).exec();
-- 
GitLab