katoikia-app/servicio-comunidad-viviendas/src/communities/communities.service.ts

74 lines
2.3 KiB
TypeScript
Raw Normal View History

import { Injectable, Inject } from '@nestjs/common';
2022-06-29 10:12:27 +00:00
import { Model } from 'mongoose';
import { Community, CommunityDocument } from 'src/schemas/community.schema';
2022-06-29 10:12:27 +00:00
import { InjectModel } from '@nestjs/mongoose';
import { RpcException, ClientProxy } from '@nestjs/microservices';
import { from, lastValueFrom, map, scan, mergeMap } from 'rxjs';
import { Admin } from 'src/schemas/admin.entity';
import { appendFileSync } from 'fs';
2022-06-29 10:12:27 +00:00
@Injectable()
export class CommunitiesService {
constructor(
2022-07-25 04:38:48 +00:00
@InjectModel(Community.name)
private readonly communityModel: Model<CommunityDocument>,
@Inject('SERVICIO_USUARIOS') private readonly clientUserApp: ClientProxy,
2022-07-25 04:38:48 +00:00
) {}
2022-06-29 10:12:27 +00:00
async create(community: CommunityDocument): Promise<Community> {
return this.communityModel.create(community);
}
async findAll(): Promise<Community[]> {
return await this.communityModel
.find()
.setOptions({ sanitizeFilter: true })
.exec()
2022-07-25 04:38:48 +00:00
.then(async (community) => {
if (community) {
2022-07-25 04:38:48 +00:00
await Promise.all(
community.map(async (c) => {
//buscar al usuario con el id de la comunidad anexado
let admin = await this.findCommunityAdmin(c['_id'], '2');
if (admin) {
c['id_admin'] = admin['_id'];
c['name_admin'] = admin['name'];
}
return c;
}),
);
}
return community;
2022-07-25 04:38:48 +00:00
});
2022-06-29 10:12:27 +00:00
}
findOne(id: string): Promise<Community> {
return this.communityModel.findOne({ _id: id }).exec();
}
findOneName(id: string): Promise<Community> {
return this.communityModel.findOne({ _id: id }).exec();
}
2022-06-29 10:12:27 +00:00
update(id: string, community: CommunityDocument) {
return this.communityModel.findOneAndUpdate({ _id: id }, community, {
new: true,
});
}
async remove(id: string) {
return this.communityModel.findByIdAndRemove({ _id: id }).exec();
}
async findCommunityAdmin(community: string, user_type: string) {
2022-07-25 04:38:48 +00:00
const pattern = { cmd: 'findOneCommunityUser' };
const payload = { community_id: community, user_type: user_type };
let callback = await this.clientUserApp
.send<string>(pattern, payload)
2022-07-25 04:38:48 +00:00
.pipe(map((response: string) => ({ response })));
const finalValue = await lastValueFrom(callback);
return finalValue['response'];
}
2022-06-29 10:12:27 +00:00
}