translate-errors-plugin.ts 937 B

12345678910111213141516171819202122232425
  1. import { ApolloServerPlugin, GraphQLRequestListener } from '@apollo/server';
  2. import { I18nService } from '../../i18n/i18n.service';
  3. /**
  4. * This plugin intercepts outgoing responses and translates any error messages into the
  5. * current request language.
  6. */
  7. export class TranslateErrorsPlugin implements ApolloServerPlugin {
  8. constructor(private i18nService: I18nService) {}
  9. async requestDidStart(): Promise<GraphQLRequestListener<any>> {
  10. return {
  11. willSendResponse: async requestContext => {
  12. const { errors, contextValue } = requestContext;
  13. const { body } = requestContext.response;
  14. if (errors && body.kind === 'single') {
  15. body.singleResult.errors = errors.map(err => {
  16. return this.i18nService.translateError(contextValue.req, err) as any;
  17. });
  18. }
  19. },
  20. };
  21. }
  22. }