toonvanstrijp / nestjs-i18n

The i18n module for nestjs.
https://nestjs-i18n.com
Other
642 stars 106 forks source link

Option to return null/undefined instead of the translation key if no translation was found #520

Closed Susccy closed 1 year ago

Susccy commented 1 year ago

Clear and concise description of the problem

If I read the source code correctly, the current implementation of the translate method will return the translation key if no translation could be found in any of the fallback languages: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/src/services/i18n.service.ts#L125

In my code however I sometimes want to provide inline fallback strings to display when a dynamic translation doesn't exist. Currently I need to do that like this:

foo (label: string) {
  let translation = this.i18n.translate(`sampleKey.${label}`);
  if (translation === `sampleKey.${label}`) translation = 'fallback string';
}

Suggested solution

It would be way more convenient if the translate method returned null or undefined instead of the key in this case so I could do it like this:

foo (label: string) {
  const translation = this.i18n.translate(`sampleKey.${label}`) ?? 'fallback string';
}

Being able to achieve this in one line is a huge advantage over always having to add another conditional check.

Alternative

No response

Additional context

A module config option to enable nullish returns (e.g. useNullReturn: boolean) would allow opt-in for this functionality and not cause any breaking changes with existing code.

Validations

rubiin commented 1 year ago

would you like to create a PR

Susccy commented 1 year ago

noted, will do if I have time

Susccy commented 1 year ago

@rubiin I just discovered the defaultValue option for the translate method which solves this problem for me. I didn't know it existed previously because it isn't documented anywhere. So a possible solution for this issue could be to simply add documentation for that option.

rubiin commented 1 year ago

Added a section on getting started with all the translate option. This should help anyone out with similar issue https://nestjs-i18n.com/quick-start#translate-options