Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Service to interact with the diary database
- */
- @Injectable()
- export class LogDiaryService {
- private diary: MongoRepository<Diary>;
- private user: Repository<User>;
- public constructor(
- @InjectRepository(Diary, DATA_SOURCE_MONGO) diary: MongoRepository<Diary>,
- @InjectRepository(User, DATA_SOURCE_DEFAULT) user: Repository<User>
- ) {
- this.diary = diary;
- this.user = user;
- }
- /**
- * Retrive a diary by mongo ID
- */
- public async getById(id: string): Promise<DiaryResponse> {
- const diary = await this.diary.findOneByOrFail({
- _id: ObjectId.createFromHexString(id),
- });
- const [response] = await this.reformat([diary]);
- return response;
- }
- /**
- * Get all diaries in mongo
- */
- public async getAll(): Promise<DiaryResponse[]> {
- const diaries = await this.diary.find({});
- return this.reformat(diaries);
- }
- /**
- * Reformat log diaries to resolve all users both the owner AND reviewers
- */
- private async reformat (diaries: Diary[] = []): Promise<DiaryResponse[]> {
- const userIds = [...new Set(
- ...diaries.map(({ userId, reviews, markers }) => [
- userId,
- ...reviews.map(({ userId }) => userId),
- ...markers.map((userId) => userId),
- ])
- )];
- const users = await this.user.findBy({
- id: In(userIds),
- });
- return diaries.map(({ userId, ...diary }) => ({
- ...diary,
- id: diary.id.toString(),
- user: users.find(({ id }) => id === userId),
- markers: diary.markers.map((marker) => users.find(({ id }) => id === marker)),
- reviews: diary.reviews.map(({ userId: uId, ...review }) => ({
- ...review,
- user: users.find(({ id }) => uId === id),
- })),
- }));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement