import { Injectable } from '@nestjs/common' import { isEmpty, omit } from 'lodash' import { classToPlain, plainToClass } from 'class-transformer' import { CountryCode, CountryHelper } from '../utils/countries' import { Notification, NotificationType } from '../models' import { HttpService } from '../services/http' import { BaseRepository } from './base.repository' const INSERT = ` mutation insertNotification($notification: notification_insert_input!) { insert_notification_one(object: $notification) { id } } ` const DELETE = ` mutation deleteNotification($id: uuid!) { delete_notification_by_pk(id: $id) { id } } ` const GET = ` query notification($id: uuid!) { notification(where: {id: {_eq: $id}}) { id user_id type title message created_at read_at patient_id resource_id } } ` const FIND_UNREAD_BY_TYPE_USER_PATIENT = ` query notification($userId: String!, $patientId: String!, $type: String!) { notification(where: {read_at: {_is_null: true}, user_id: {_eq: $userId}, patient_id: {_eq: $patientId}, type: {_eq: $type}}) { id type title message resource_id } } ` @Injectable() export class NotificationRepository extends BaseRepository { constructor(protected readonly httpService: HttpService) { super(httpService, 'notification') } async create(notification: Notification, countryCode: CountryCode): Promise { const language = CountryHelper.extractOnlyLanguage(countryCode) const qv = { notification: omit( { ...classToPlain(notification), [`title_${language}`]: notification.title, [`message_${language}`]: notification.message, }, ['title', 'message'], ), } const { data } = await this.fetchGraphQL({ body: { query: INSERT, variables: qv }, }) return data.insert_notification_one.id } async delete(id: string): Promise { await this.fetchGraphQL({ body: { query: DELETE, variables: { id }, }, }) } async get(id: number): Promise { const { data } = await this.fetchGraphQL({ body: { query: GET, variables: { id } }, }) return isEmpty(data.notification) ? null : plainToClass(Notification, data.notification[0]) } async findUnreadsByTypeAndUserAndPatient( userId: string, patientId: string, type: NotificationType, ): Promise { const { data } = await this.fetchGraphQL({ body: { query: FIND_UNREAD_BY_TYPE_USER_PATIENT, variables: { userId, patientId, type } }, }) return isEmpty(data.notification) ? [] : data.notification.map(value => plainToClass(Notification, value)) } }