import { Body, Controller, Post } from '@nestjs/common' import { first } from 'lodash' import { UnprocessableEntityError } from '../../../errors' import { fromBase64ToJson } from '../../../utils' import { AppleInApp, GoogleInApp } from '../domain' import { GoogleInAppNotification } from '../domain/types' import { AppleEventParams, PubSubParams } from './params' const TEST_NOTIFICATION_RECEIVED_ERROR_MESSAGE = 'Test subscription notification received' @Controller('in-app') export class InAppController { constructor(private readonly googleInApp: GoogleInApp, private readonly appleInApp: AppleInApp) {} @Post('google') async handleGoogleNotification(@Body() { message }: PubSubParams): Promise { const data = fromBase64ToJson(message.data) console.log('PUBSUB NOTIFICATION', JSON.stringify(data)) try { if (data['testNotification']) throw new UnprocessableEntityError(TEST_NOTIFICATION_RECEIVED_ERROR_MESSAGE) return this.googleInApp.handle(data) } catch (err) { console.error( err.message, data.packageName, data.subscriptionNotification.purchaseToken, data.subscriptionNotification.notificationType, ) } } @Post('apple') async handleAppleNotification( @Body() { environment, notification_type, unified_receipt }: AppleEventParams, ): Promise { try { if (environment === 'Sandbox') throw new UnprocessableEntityError(TEST_NOTIFICATION_RECEIVED_ERROR_MESSAGE) return this.appleInApp.handle(notification_type, first(unified_receipt.latest_receipt_info)) } catch (err) { console.error( err.message, environment, notification_type, unified_receipt.latest_receipt, unified_receipt.latest_receipt_info, ) } } }