GithubHelp home page GithubHelp logo

toonvanstrijp / nestjs-i18n Goto Github PK

View Code? Open in Web Editor NEW
605.0 4.0 103.0 9.03 MB

The i18n module for nestjs.

Home Page: https://nestjs-i18n.com

License: Other

JavaScript 2.69% TypeScript 97.17% Handlebars 0.03% CSS 0.02% Pug 0.04% EJS 0.06%
nestjs i18n nodejs typescript

nestjs-i18n's Introduction

nestjs-i18n Logo

The i18n library for nestjs. It makes working with languages in your nestjs project easy. Everything is made to be highly configurable. You can write and plug-in your own language resolvers or loaders.

npm version NPM npm downloads coverage

Features

nestjs-i18n comes with a bunch of tools to help add multiple language support to your project.

Getting started

To get started follow the quickstart, or take a look at the docs.

License

nestjs-i18n is MIT licensed.

Breaking changes:

  • from V10.0.0 on we removed the I18nRequestScopeService. This because we now have async_hooks support. This allows you to get the current I18nContext by doing I18nContext.current().

  • from V9.0.0 on we renamed the parser property to loader. The translate function no longer returns a promise πŸŽ‰. A lot of new features and new docs, see nestjs-i18n.com.

  • from V8.0.0 on we changed the internal I18n-middleware for an interceptor this way we can provide the ExecutionContext so that nestjs-i18n works on different protocols as well, such as gRPC and WebSockets. This contains one breaking change. It only applies to your code if you've made a custom resolver. To resolve this breaking change take a look at this example. Instead of providing the req in the resolve method, change this to take the ExecutionContext as argument.

  • from V6.0.0 on we implemented the I18nParser, by using this we can easily support different formats other than JSON. To migrate to this change look at the quickstart. There are some changes in the declaration of the I18nModule. Note: the translate function returns a Promise<string>. So you need to call it using await i18n.translate('HELLO');

  • from V4.0.0 on we changed the signature of the translate function, the language is now optional, if no language is given it'll fallback to the fallbackLanguage.

  • from V3.0.0 on we load translations based on their directory name instead of file name. Change your translations files to the structure found in the quickstart.

nestjs-i18n's People

Contributors

bengeois avatar brussev avatar david-szabo97 avatar demostenes1509 avatar dependabot[bot] avatar goufix avatar greenkeeper[bot] avatar hyzyla avatar iliazeus avatar johannesschobel avatar kcfindstr avatar lehuygiang28 avatar lucas-gregoire avatar lukadriel7 avatar minh-hoang-trinh avatar mitchdorrestijn avatar neo-zhixing avatar psyrenpark avatar ramzamzam avatar rubiin avatar schroedersteffen avatar scrip7 avatar snyk-bot avatar stimulcross avatar thuan00 avatar tkalmar avatar toonvanstrijp avatar toonvanstrijpwavy avatar willianfalbo avatar wunax avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

nestjs-i18n's Issues

How to reexport the module

For example I want to initialize it once and use it in other modules

@Module({
    imports: [
        I18nModule.forRootAsync({
            useFactory: () => ({
                path: path.join(__dirname, '../../locales'),
                filePattern: '*.json',
                fallbackLanguage: 'en',
            }),
            inject: [],
        }),
    ],
    controllers: [],
    exports: [],
    providers: [],
})
export class LocalizationModule {}

How to get initialized I18nService in another modules with above settings?

nestjs-i18n JSON.parse error

[Nest] 23128 - 2020-03-23 16:43:22 [ExceptionsHandler] Unexpected end of JSON input +4081ms
SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at I18nJsonParser.parseTranslations (/home/ankur/Desktop/ashwani/nest-project-client/node_modules/nestjs-i18n/dist/parsers/i18n.json.parser.js:89:31)
at

why is this error shows many time


async check(@Body() data){
const langauges = await this.i18nService.getSupportedLanguages()
const { lang ,message } = data
if(langauges.includes(lang)){
const transMessage = await this.i18nService.translate(message , {
lang
})
console.log(transMessage)
return transMessage
}
}

my json file structure is like your as mentions in docmentation i18n
β”œβ”€β”€ en
β”‚ β”œβ”€β”€ category.json
β”‚ └── auth.json
└── nl
β”œβ”€β”€ category.json
└── auth.json


I18nModule.forRoot({
fallbackLanguage: 'en',
parser: I18nJsonParser,
parserOptions: {
path: path.join(__dirname, '../i18n/'),
watch : true,
},
resolvers: [
{ use: QueryResolver, options: ['lang', 'locale', 'l'] }
],
}),

QueryResolver not executed

I implemented i18n as in documentation I created a Custom QueryResolver but it seems that when I make a request, the request does not hit the resolver.
Changing to forRoot instead of forRootAsync it works ok

I18nModule.forRootAsync({
      useFactory: (configService: ConfigService) => ({
        fallbackLanguage: configService.get('fallbackLanguage'), // e.g., 'en'
        parserOptions: {
          path: path.join(__dirname, '/i18n/'),
          // add this to enable live translations
          watch: true,
        },
        resolvers:[
          new HeaderResolver(['x-lang']),
          new QueryLangResolver()
        ]
      }),
      parser: I18nJsonParser,
      inject: [ConfigService],
    }),
@Injectable()
export class QueryLangResolver implements I18nResolver {
    
  resolve(req: any) {
    console.log(req);
    return "fr";
  }
}

Thanks

[Feature] Resolve Language of User

Dear @toonvanstrijp ,

i think it would be good if we could resolve the language of the current user (i.e., the client that is interacting with the API).
However, there may be some different approaches in "telling" the API, how the client would like to communicate:

  1. Request Headers: There is an offical accept-language http header that may be used. However, the client / api may use custom headers (e.g., X-user-language) as well.
  2. Query Params: The user may submit the requested language as a query param (e.g., ?lang=de)
  3. Path Segment: The user may set the language via the path (e.g., /de/users/4711)

Either way, the currently selected language should be added to the request of NestJS because this may be used to automatically change the language based on this setting (see my other issue #18 ).

We could have different LanguageDetectorMiddlewares (e.g, Header, Query, Path, ...) that may be used to detect the requested language. Each middleware should be customizable (e.g., i want to use the accept-language header-field for detecting the language)

What do you think?

Does not copy the i18n folder to the dist

Hello again,
the i18n folder is not moved into the dist folder. Is there any idea why this is the case? My path is src/i18n. Am I missing any extra configurations that are not documented?

When I run "npm run start:dev" the following error occurs:

[Nest] 48830   - 25.02.2020, 16:05:01   [I18nService] failed getting languages +0ms
Error: ENOENT: no such file or directory, scandir '/dist/i18n/'
  • volbrene

Nested JSON not working

I assumed you would be able to have a nested JSON-Object like this:

{ "test": { "test": "hello" } }

And to get "hello" you would call: translate('en', 'test.test') but this does not work. Can you implement this feature? The Angular package ngx-translate as well as the NodeJS package i18n do it the same way.

Best regards

How to change the language and handle other languages?

Hey there.
How we can change the language on the server-side?
If a user tries to change it's language in view (front), how we can handle it on the server-side?
Currently, I'm using Nunjucks for the template engine.
And this an example of the way I use this package:

@Get('/')
	@Render('default.njk')
	async getIndex(@I18n() i18n: I18nContext): Promise<object> {
		const sloganLine1 = await i18n.translate('home.HOME_SLOGAN.LINE1');
		const sloganLine2 = await i18n.translate('home.HOME_SLOGAN.LINE2');

		return {
			slogan: {
				line1: sloganLine1,
				line2: sloganLine2
			}
		}
	}

I pass an object to the view that contains the translations. And it working fine!
But I don't know how to handle other languages.
I'm new to Nest.js, and it's a little complicated for me.
If I open /en or /fa in the browser, it throws a 404 error message.
It's only working if I open / in the browser.

An in-range update of @nestjs/platform-express is breaking the build 🚨

The devDependency @nestjs/platform-express was updated from 6.6.1 to 6.6.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@nestjs/platform-express is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v6.6.2

Bug Fixes

  • core: maximum call stack size exceeded for circular deps #2834
  • platform-fastify: unhandled exception when throwing an error in the middleware #2640
FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.12.14 to 12.12.15.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Filename should not be included in the translations dictionary

In the parse.ts file, there's some prefix manipulation that takes the file name and prepends that to the dictionary of translations:

https://github.com/ToonvanStrijp/nestjs-i18n/blob/241ec1003726be39a4577b6c5a0d472b241536a7/src/lib/utils/parse.ts#L71

However, IMHO, this is far from ideal because:

  • It is not well document in the README/docs (I just found out by debugging and checking the tests)
  • It does not seem to provide any value, and creates confusion
  • If your files have different file names (let's say intl_en_US.json and intl_es_ES.json), but are located in different folders (such as en_US and es_ES), you won't be able to access your translations.

Before making any changes, I wanted to understand first if that code is there for a special reason. If not, I can open a PR and make the changes to remove that prefix manipulation. Let me know.

Thank you!

Why do I get a promise when trying to get the message?

I am trying to get the message in my module service or controller, but when I see the answer of my request I get nothing, but I realize putting it in the console.log() and I realize that it is returning a promise or something like that And I don't understand why, if you could be so kind to help me please.

This is my code to import the nest-i18n module

imports: [
I18nModule.forRoot({
      fallbackLanguage: 'en',
      parser: I18nJsonParser,
      parserOptions: {
        path: join(__dirname, '/util/i18n/'),
        watch: true,
      },
      resolvers: [
        { use: QueryResolver, options: ['lang', 'locale', 'l'] },
        new HeaderResolver(['x-custom-lang']),
        AcceptLanguageResolver,
        new CookieResolver(['lang', 'locale', 'l']),
      ],
    }),
]

This is my code to get a message

constructor(
    private readonly _i18nService: I18nRequestScopeService,
  ) {}

public method() {
   console.log('Message' + this._i18nService.translate('auth.service.create_account.general'));
}

This is the structure of my language .json file, the file is called "auth.json" and it is inside the folder called "en"

{
  "controller": {
    "create_acount": "Excellent! Welcome to Kodachi, we hope you enjoy the best anime experience."
  },
  "service": {
    "create_account": {
      "account_exist": "We are sorry but there is already an account with this data.",
      "general": "We are sorry but we were unable to process your account creation request. Try again later.",
      "send_email": "We are sorry but we were unable to send the registration confirmation message. Please contact us to solve it as soon as possible."
    }
  }
}

This is the response I get on the console doing the test

1

I hope you can solve my problem, thank you very much in advance.

Why you have to set lang manually?

Take a look at the example, where you manually have to pipe the detected language to the translation method:

@Controller()
export class SampleController {

  constructor(
    private readonly i18n: I18nService,
  ) {}

  @Get()
  sample(@I18nLang() lang: string) {
    this.i18n.translate('HELLO_MESSAGE', {lang: lang, args: {id: 1, username: 'Toon'}});
  }
}

While this falls back to fallbackLanguage:

@Controller()
export class SampleController {

  constructor(
    private readonly i18n: I18nService,
  ) {}

  @Get()
  sample() {
    this.i18n.translate('HELLO_MESSAGE', {args: {id: 1, username: 'Toon'}});
  }
}

As a user, I dont wan't to pipe anything through my actions which I don't use. This results just in boilerplate code every time I translate anything.

An in-range update of apollo-server is breaking the build 🚨

There have been updates to the apollo-server monorepo:

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the apollo-server group definition.

apollo-server is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).
  • βœ… coverage/coveralls: First build on greenkeeper/monorepo.apollo-server-20200206124828 at 89.756% (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @nestjs/testing is breaking the build 🚨

The devDependency @nestjs/testing was updated from 6.5.3 to 6.6.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@nestjs/testing is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v6.6.0

Features:

  • all: add API docs (better DX) #2688
  • common: add log levels (Logger) #2813
  • common: add seconds to Logger timestamp #2770
  • common: add @Redirect() decorator #2632
  • core: move createResponseBody function to HttpException #2796
  • core: allow NestModule.configure() method to be async #2767
  • core: provide more descriptive error for unknown element exception #2725
  • core: add beforeApplicationShutdown hook #2567
  • core: execute middleware of dependent modules first #2406
  • core: add resolve() method to load scoped (either request or transient) providers #2682
  • microservices: use hot observables for emit() (ClientProxy) #2814
  • microservices: improve microservices performance by scheduling emission on nextTick() #2653
  • microservices: add serializers/deserializers feature to allow adapting external services #2653

Bug Fixes:

  • core: do not call onModuleInit if null #2790
  • core: fix request-scoped middleware #2648
  • microservices: pass all arguments to request-scoped proxies #2805
  • microservices: update isTermined value when manually closed #2708
  • *platform-express: fix PreservePath boolean property location in multer configuration #2800

Other:

  • ci: migrate towards CircleCI #2720
FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of apollo-server is breaking the build 🚨

There have been updates to the apollo-server monorepo:

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the apollo-server group definition.

apollo-server is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Not able to start application after upgrading to Nest 7 and nestjs-i18n 7.0.0

Screenshot from 2020-03-16 12-55-55
Screenshot from 2020-03-16 12-51-29
error: Nest can't resolve dependencies of the I18nRequestScopeService (?, I18nService). Please make sure that the argument REQUEST at index [0] is available in the I18nModule context.

Potential solutions:

  • If REQUEST is a provider, is it part of the current I18nModule?
  • If REQUEST is exported from a separate @module, is that module imported within I18nModule?
    @module({
    imports: [ /* the Module containing REQUEST */ ]
    })

Usage with Bull

Hi,

We have some APIs translated using this project and it works pretty well :)

But now, we want to translate Nest micro services that are using Bull to receive messages.

We looked at custom resolvers but it seems it's http request based. I can't figure out how to get Bull related messages.

Thanks :)

An in-range update of apollo-server is breaking the build 🚨

There have been updates to the apollo-server monorepo:

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the apollo-server group definition.

apollo-server is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).
  • βœ… coverage/coveralls: First build on greenkeeper/monorepo.apollo-server-20200206124830 at 89.756% (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

How to copy i18n folder in dist folder ?

Hello,
I started using your nestjs-i18n package, and it looks awesome.

Just one question : when I build my nestjs app, my i18n folder does not appear in my dist folder.

Do you have any clue ?
Thank you.

UPDATE : I found my error, but it would be nice to put it in the README.md because I was looking at this problem for like 2 hours...

Thank you.

Import for tests

Hello and thank you for the lib, it works great. I have a question. How do I import it in the shared test module, so that tests are not failing because of the missing dependencies? Could you please give an example? Thank you in advance!

Wrong usage-example or typings

You have the following usage-example in your Readme:

this.i18n.translate('en', 'HELLO_MESSAGE', {id: 1, username: 'Toon'});

But your translate-method requires an array as third argument. Either your typing is wrong or your example.

If it matters: I would prefer to be able to just insert an object as the third argument (like your example).

Best regards!

Provide forRootAsync

I use to use a configuration service that is aware of the environment, and it uses different settings for each environment. In e2e tests I need to configure I18NModule with a different path, so it would be nice to have something like this:

imports: [ I18nModule.forRootAsync({ useFactory: (config: ConfigurationService) => ({ path: configService.i18nPath, fallbackLanguage: 'es' }), inject: [ConfigurationService] }) ]

An in-range update of @nestjs/testing is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye πŸ‘‹ and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The devDependency @nestjs/testing was updated from 7.0.3 to 7.0.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@nestjs/testing is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… coverage/coveralls: First build on greenkeeper/@nestjs/testing-7.0.4 at 89.941% (Details).
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Discussion: split files by language and not by domain

Hey there,
i thought it would be better / easier to separate the translations by language (e.g., en or de folders) and not by domain (e.g., company or mail folder).
Especially when it comes to translating content to a new language, you can simply copy/paste one existing folder (e.g., en) and rename it to de and then send it to your translator - and you are good to go.

otherwise you would need to manually pick all files in a potentially endless deep folder structure - not cool ;)

So basically, i am proposing a folder-structure like this:

i18n \
  en \
    company.json
    mail.json
    social.json
  de \ 
    company.json
    mail.json
    social.json

instead of

i18n \
  company \
    de.json
    en.json
  mail \
    de.json
    en.json
  social \
    de.json
    en.json

in order to not break existing applications, we could provide a loadFilesByLanguage or loadFilesByDomain flag..

what do you think?
All the best

An in-range update of nestjs is breaking the build 🚨

There have been updates to the nestjs monorepo:

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the nestjs group definition.

nestjs is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

[Feature] Load labels by prefix

Dear @toonvanstrijp ,

i think it would be a good idea to "prefix" all labels from one particular file. For example, all labels in the mail.json file should be prefixed with mail.

Consider, the following example: Your en\mail.json file may look like this:

{
  "from": "Support"
}

then the key for accessing this label should be prefixed with the name of the file (mail). Currently you need to access it with from, but this may be ambiguous, as the key may be provided in different files. It would be better to access it via mail.from.

What do you think?

All the best

An in-range update of @nestjs/platform-fastify is breaking the build 🚨

The devDependency @nestjs/platform-fastify was updated from 6.6.1 to 6.6.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@nestjs/platform-fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v6.6.2

Bug Fixes

  • core: maximum call stack size exceeded for circular deps #2834
  • platform-fastify: unhandled exception when throwing an error in the middleware #2640
FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

HeaderResolver makes no sense for a website

If we talk about the given header accept-language, it makes no sense to return the whole string.

Take a look in your browser request and it will look similar to this:
de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7,und;q=0.6

The package needs to make a decision based on this string.

AcceptLanguageResolver TypeError for NestJS GraphQL app

I have a NestJS app with GraphQL setup, when adding nestjs-i18n and trying to load /graphql endpoint from browser, the app throws TypeError: cannot read property 'raw' of undefined

TypeError: Cannot read property 'raw' of undefined
    at AcceptLanguageResolver.resolve (/<path>/node_modules/nestjs-i18n/dist/resolvers/accept-language.resolver.js:18:26)
    at I18nLanguageInterceptor.intercept (/<path>/node_modules/nestjs-i18n/dist/interceptors/i18n-language.interceptor.js:35:37)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async target (/<path>/node_modules/@nestjs/core/helpers/external-context-creator.js:75:28)
    at async /<path>/node_modules/@nestjs/core/helpers/external-proxy.js:8:24

Looking into the problem I think there are two issues: AcceptLanguageResolver only retrieves HTTP context at the moment, and for GraphQL i18nService is assigned to context and not context.req

Changing resolve method of AcceptLanguageResolver to something like below probably can fix the issue:

async resolve(context) {
    let req, service;
    if (context.getType() === 'http') {
      req = context.switchToHttp().getRequest();
      req = req.raw ? req.raw : req;
      service = req.i18nService;
    } else if ((context as GraphQLExecutionContext).getType() === 'graphql') {
      [, , { req, i18nService: service }] = context.getArgs();
    }
    const lang = req.raw
      ? req.raw.headers['accept-language']
      : req.headers['accept-language'];
    if (lang) {
      return acceptLanguageParser.pick(await service.getSupportedLanguages(), lang);
    }
    return lang;
  }

For the second cause where i18n-language.interceptor.ts is assigning i18nService to context and not context.req . A simpler fix would just be changing context.ts like below, but this is a breaking change

case 'graphql':
      const [, , { req }] = context.getArgs();
      return req;

An in-range update of fastify is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye πŸ‘‹ and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The devDependency fastify was updated from 2.12.1 to 2.13.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).
  • βœ… coverage/coveralls: First build on greenkeeper/fastify-2.13.0 at 88.955% (Details).

Release Notes for v2.13.0

πŸ“š PR:

  • Update deps
  • update GH checkout action (#2122)
  • fix add schema conflict (#2077)
  • Use light-my-request types instead of duplicating typings. fixes #2098 (#2124)
  • feat(#1930): added option to overrind onBadUrl callback (#2106)
  • quicker quick start (#2125)
  • docs: Clarify thrown values must be Errors (#2126)
  • Update decorators documentation (#2127)
  • fix: throw error if decorator is called after start (#2128)
  • Update ci.yml (#2133)
  • Remove Gitter links (#2132)
  • fix test ready-start order (#2136)
  • chore(package): update @typescript-eslint/parser to version 2.24.0 (#2138)
Commits

The new version differs by 14 commits.

  • 04b696b Bumped v2.13.0
  • a071150 Update deps
  • a6db281 chore(package): update @typescript-eslint/parser to version 2.24.0 (#2138)
  • 627c756 fix test ready-start order (#2136)
  • 3dbeb64 Remove Gitter links (#2132)
  • 9b533f5 Update ci.yml (#2133)
  • 512561f fix: throw error if decorator is called after start (#2128)
  • 2874af5 Update decorators documentation (#2127)
  • ba9086b docs: Clarify thrown values must be Errors (#2126)
  • a8d5448 quicker quick start (#2125)
  • 14059cf feat(#1930): added option to overrind onBadUrl callback (#2106)
  • 911c8c0 Use light-my-request types instead of duplicating typings. fixes #2098 (#2124)
  • 0b50f38 fix add schema conflict (#2077)
  • a272f15 update GH checkout action (#2122)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

[Discuss] Change Signature of `translate` method

Hey @toonvanstrijp ,

i would like to raise the question, if we should change the signature of the translate(locale: string, label: string) method.. Currently, this signature implies, that you must set a locale to translate it to.. However, if we change the signature to

translate(label: string, locale?: string)

we could make the second (locale) param optional and default to the fallbackLocale..

What do you think?

Nest can't resolve dependencies of the I18nOptions after upgrade to nest 6.3.1

Hi @toonvanstrijp,

We are using the async module inititialization like this:

@Module({
  imports: [
    ConfigModule,
    I18nModule.forRootAsync({
      imports: [ConfigModule],
      useExisting: ConfigService,
    }),
  ],
  providers: [TranslationService],
  exports: [TranslationService],
})
export class TranslationModule {}

This worked well until we upgraded to version 6.3.1 (was 6.2.4). I suspect, nestjs/nest#2341 boke something. We also use https://github.com/nestjs/jwt/ and initialize it in a very similiar way:

@Module({
  imports: [
    ConfigModule,
    JwtModule.registerAsync({
      imports: [ConfigModule],
      useExisting: ConfigService,
    }),
    PassportModule.register({ defaultStrategy: 'jwt' }),
    UserModule,
  ],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy, LocalStrategy],
  exports: [AuthService],
})
export class AuthModule {}

This works flawless even with 6.3.1. I'm not an expert with nest modules, but looking at the source code of JwtModule, I suspect https://github.com/nestjs/jwt/blob/master/lib/jwt.module.ts#L26 is needed for this to work. A similiar imports entry is missing in I18nModule's declaration, so this might be the reason why above configuration is not working. Can you provide a fix or should I try create a PR?

Please fix documentation

I've worked as a professional software developer for 8+ years. This is the most useless package I've ever tried that is available at npm. I hope the Nest team replaces the developers of this package or do something about this complete incompetency . Documentation is outdated. It breaks with many versions of Nest including the latest. Every minor update breaks everything and require rewrite of all code everywhere. No useful error messages. The syntax becomes worse each release. The package is incrementally more difficult to use. The initial version of this package was the best (and it was never good).

This package is the reason I would advice people to stay away from Nest if you plan to build anything meant for production. Please fix documentation so people don't get confused. Make sure the basic stuff works before you use a lots of time to add nice to have features.

[Feature] Missing Translations

Dear @toonvanstrijp ,

here is another feature request for discussion.
I think, it would be good to have some kind of "document missing translations" feature. Consider, the following example. i have an application that is already provided in EN, but now i want to add a second language DE. However, in the process of translating everything, new labels for EN gets added.

Of course, these new labels are not translated in DE - so they will be missing. In order to "automatically" document, that those translations are missing, i suggest to automatically generate a respective xyz.missing.json file.

For example:
In the en\mail.json i added a new thankyou. This key is missing in the de\mail.json file. So if i now output the mail.thankyou text somewhere (with the de locale) it should get recorded in the de\mail.missing.json file. This file then has the following input:

{
  "thankyou": "THE TEXT FOR THIS LABEL FROM THE DEFAULT LANGUAGE"
}

This would make the "continuous translation" so much easier..
What do you think?

An in-range update of @nestjs/platform-fastify is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye πŸ‘‹ and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The devDependency @nestjs/platform-fastify was updated from 7.0.3 to 7.0.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@nestjs/platform-fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @nestjs/common is breaking the build 🚨

The devDependency @nestjs/common was updated from 6.5.3 to 6.6.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@nestjs/common is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

How to get the real time content?

I can't get the updated locale content in real time unless I restart the service

This is my code

import { Module } from '@nestjs/common'
import * as path from 'path'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { I18nModule, QueryResolver, AcceptLanguageResolver } from 'nestjs-i18n'

@Module({
    imports: [
        // I18nModule.forRoot({
        //     path: path.join(__dirname, '../../locales'),
        //     filePattern: '*.json',
        //     fallbackLanguage: 'en-US',
        //     resolvers: [{ use: QueryResolver, options: ['language'] }, AcceptLanguageResolver],
        //     saveMissing: false
        // })
        I18nModule.forRootAsync({
            useFactory: () => {
                return {
                    path: path.join(__dirname, '../../locales'),
                    fallbackLanguage: 'en-US',
                    saveMissing: false
                }
            },
            resolvers: [{ use: QueryResolver, options: ['language'] }, AcceptLanguageResolver]
        })
    ],
    controllers: [AppController],
    providers: [AppService]
})
export class AppModule {}

Support for XLIFF formatted translation files

I have an Angular/Nest.JS monorepo setup (using Nx) in my project and have XLIFF translation files in the frontend.
Adding translation files in the backend that have a different format does not seem like a good solution to me. And with a monorepo setup the translation files of frontend and backend could even be merged together into one file per locale.

My proposition: add support for XLIFF formatted files and let the developer choose the translation file format.

This could be an advantage for the package since XLIFF is a well established translation file standard that is widely used in professional applications since most external translation services/platforms support it.

this.i18n.translate translate is undefiend

TypeError: Cannot read property 'test.HELLO' of undefined
at I18nService.translate (E:\elephant-tech\projects\theelephanttech-backend-boilerplate\node_modules\nestjs-i18n\dist\services\i18n.service.js:48:49)

and when theapplication start
i got this
[Nest] 14632 - 11/13/2019, 9:00:12 PM [I18nService] Object:
{}

Translation not refreshed on dist folder

I copied instructions from nest-cli.json copy i18n and live reloading but this doesn't refresh the files in dist folder so translations are not updated when modified. I have to relaunch manually the whole nest application to have translation updated.

Do you have any idea ? I am using version 6. And npm start:dev

app.module.ts

      fallbackLanguage: 'en',
      parser: I18nJsonParser,
      parserOptions: {
        path: path.join(__dirname, '/../i18n/'),
        watch: true,
      },
      resolvers: [{ use: QueryResolver, options: ['lang'] }],
    }),

nest-cli.json

  "language": "ts",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "assets": ["i18n/**/*"]
  }
}

An in-range update of graphql is breaking the build 🚨

The devDependency graphql was updated from 14.5.3 to 14.5.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

graphql is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v14.5.4

v14.5.4 (2019-08-29)

Bug Fix 🐞

Polish πŸ’…

Committers: 3

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Why I18nResolver#resolve returns a string?

First of all, really good job on the v4! I like the new features a lot!

I was wondering why the resolve method has to return string | void. Would it be possible to return any object? Or specified by generics?

My use case would be that in the accept-language some customers will actually pass a Locale object, like en_US, so I would expect a resolver to take that as an input, and I could model it to a model that could give me:

  • the locale: en_US
  • just the language: en
  • just the country: US

Thoughts? If you think it is a good idea, I could work on the changes ;)

this.i18nOptions.resolvers is not iterable

I receive a runtime error this.i18nOptions.resolvers is not iterable.

TypeError: this.i18nOptions.resolvers is not iterable
core            |     at I18nLanguageMiddleware.use (/usr/src/app/node_modules/nestjs-i18n/dist/middleware/i18n-language-middleware.js:25:49)

I used forRootAsync() to import into app.module.
The structure of json files is like in the descriptions.
My options look like this:

import * as path from 'path';

export default {
    path: path.join(__dirname, '/lang'),
    fallbackLanguage: 'en',
    filePattern: '*.json'
}

What could be the issue here?

An in-range update of nestjs is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye πŸ‘‹ and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


There have been updates to the nestjs monorepo:

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the nestjs group definition.

nestjs is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… coverage/coveralls: First build on greenkeeper/monorepo.nestjs-20200321213840 at 89.941% (Details).
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @nestjs/common is breaking the build 🚨

The devDependency @nestjs/common was updated from 6.7.0 to 6.7.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@nestjs/common is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.