import { API, graphqlOperation } from 'aws-amplify'; import Observable from 'zen-observable-ts'; import { App } from '../config'; export interface SyncMessage { stage: string, type: string, topic: string, key: string, body: { version: string | number, account: string | number, time: string | number, region: string, resources: string[], detail: { [key: string]: any } } } export function subscribeToNotifications(topic: string, callback: (message: SyncMessage) => void) { const env = App.Environment; const appsync = env && env['APP SYNC']; const envStage = App.IsLocalhost || !env ? 'dev' : env.stage; const syncStage = appsync && appsync.stages && appsync.stages[envStage] ? appsync.stages[envStage] : envStage; const operation: Observable = API.graphql( graphqlOperation( ` subscription ListenMessage($stage: String!, $topic: String!) { listenMessage(stage: $stage, topic: $topic) { stage body key topic } } `, { stage: syncStage, topic } ) ) as any; return operation.subscribe({ next: ({ value }: any) => { const message = { ...value.data.listenMessage, body: JSON.parse(value.data.listenMessage.body) } callback(message); }, error: (error: any) => console.warn(error) }) } export async function sendNotification(topic: string, key: string, body: any) { const env = App.Environment; const appsync = env && env['APP SYNC']; const envStage = App.IsLocalhost || !env ? 'dev' : env.stage; const syncStage = appsync && appsync.stages && appsync.stages[envStage] ? appsync.stages[envStage] : envStage; const operation = await API.graphql( graphqlOperation( ` mutation SendMessage($message: MessageInput!) { sendMessage(message: $message) { stage topic key body } } `, { stage: syncStage, topic, key, body: JSON.stringify({ version: '1.0.0', time: Date.now(), region: 'us-east-2', resources: ['appsync.amazon.com'], detail: body, }, null, '') } ) ); operation }