translate-errors-extension.ts 1.0 KB

1234567891011121314151617181920212223242526272829
  1. import { Response } from 'express-serve-static-core';
  2. import { GraphQLError } from 'graphql';
  3. import { GraphQLExtension, GraphQLResponse } from 'graphql-extensions';
  4. import { I18nRequest, I18nService } from '../../i18n/i18n.service';
  5. /**
  6. * This extension intercepts outgoing responses and translates any error messages into the
  7. * current request language.
  8. */
  9. export class TranslateErrorExtension implements GraphQLExtension {
  10. constructor(private i18nService: I18nService) {}
  11. willSendResponse(o: {
  12. graphqlResponse: GraphQLResponse;
  13. context: { req: I18nRequest; res: Response };
  14. }): void | {
  15. graphqlResponse: GraphQLResponse;
  16. context: { req: I18nRequest; res: Response };
  17. } {
  18. const { graphqlResponse, context } = o;
  19. if (graphqlResponse.errors) {
  20. graphqlResponse.errors = graphqlResponse.errors.map(err => {
  21. return this.i18nService.translateError(context.req, err as GraphQLError) as any;
  22. });
  23. }
  24. return o;
  25. }
  26. }