Advertisement
Guest User

Untitled

a guest
May 21st, 2023
44
0
7 min
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Service to interact with the diary database
  3.  */
  4. @Injectable()
  5. export class LogDiaryService {
  6.   private diary: MongoRepository<Diary>;
  7.  
  8.   private user: Repository<User>;
  9.  
  10.   public constructor(
  11.     @InjectRepository(Diary, DATA_SOURCE_MONGO) diary: MongoRepository<Diary>,
  12.     @InjectRepository(User, DATA_SOURCE_DEFAULT) user: Repository<User>
  13.   ) {
  14.     this.diary = diary;
  15.     this.user = user;
  16.   }
  17.   /**
  18.    * Retrive a diary by mongo ID
  19.    */
  20.   public async getById(id: string): Promise<DiaryResponse> {
  21.     const diary = await this.diary.findOneByOrFail({
  22.       _id: ObjectId.createFromHexString(id),
  23.     });
  24.     const [response] = await this.reformat([diary]);
  25.     return response;
  26.   }
  27.  
  28.   /**
  29.    * Get all diaries in mongo
  30.    */
  31.   public async getAll(): Promise<DiaryResponse[]> {
  32.     const diaries = await this.diary.find({});
  33.     return this.reformat(diaries);
  34.   }
  35.  
  36.   /**
  37.    * Reformat log diaries to resolve all users both the owner AND reviewers
  38.    */
  39.   private async reformat (diaries: Diary[] = []): Promise<DiaryResponse[]> {
  40.     const userIds = [...new Set(
  41.       ...diaries.map(({ userId, reviews, markers }) => [
  42.         userId,
  43.         ...reviews.map(({ userId }) => userId),
  44.         ...markers.map((userId) => userId),
  45.       ])
  46.     )];
  47.  
  48.     const users = await this.user.findBy({
  49.       id: In(userIds),
  50.     });
  51.  
  52.     return diaries.map(({ userId, ...diary }) => ({
  53.       ...diary,
  54.       id: diary.id.toString(),
  55.       user: users.find(({ id }) => id === userId),
  56.       markers: diary.markers.map((marker) => users.find(({ id }) => id === marker)),
  57.       reviews: diary.reviews.map(({ userId: uId, ...review }) => ({
  58.         ...review,
  59.         user: users.find(({ id }) => uId === id),
  60.       })),
  61.     }));
  62.   }
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement