import { inject as service } from '@ember/service'; import { isEmpty } from '@ember/utils'; import NotificationService from 'ember-cli-notifications/services/notifications'; import IntlService from 'ember-intl/services/intl'; import { ServerError, ServerErrorPayload } from '<%= modulePrefix %>'; export default class Notifications extends NotificationService { @service declare intl: IntlService; /** * Displays toast notifications for the given server errors * @param {ServerErrorPayload} payload * @param {Object} options */ errors(payload?: ServerErrorPayload, options?: Record) { const errors = payload?.errors ?? ([{ code: 'unknown.unexpected' }] as ServerError[]); errors.forEach((error) => { const message = this.intl.t(`serverErrors.${error.code}`, { meta: error.meta, defaultMessage: error.message?.detail || error.detail }); this.addNotification( Object.assign( { message, type: 'error' }, options ) ); }); } /** * Displays a single grouped toast notification for the given server errors * @param {ServerErrorPayload} payload * @param {Object} options */ groupErrors(payload: ServerErrorPayload, options?: Record) { if (!payload || isEmpty(payload.errors)) { return this.errors(payload, options); } const errors = payload.errors; const heading = options?.groupHeading || this.intl.t('serverErrors.heading', { count: errors.length }); const message = `

${heading}

    ${errors.reduce( (prev, e) => `${prev}
  • ${this.intl.t(`serverErrors.${e.code}`, { meta: e.meta, defaultMessage: (e.message && e.message.detail) || e.detail })}
  • `, '' )}
`; this.addNotification( Object.assign( { message, type: 'error', htmlContent: true }, options ) ); } } declare module '@ember/service' { interface Registry { notification: Notification; } }