npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@steroidsjs/nest-translation

v0.0.1

Published

Steroids Nest Translation Module

Downloads

44

Readme

Steroids Nest Translation Module

Модуль для перевода строк в http-ответах

Настройка приложения

Для перевода строк необходимо настроить приложение. Нужно:

  1. Импортировать TranslationModule:
import {Module} from '@steroidsjs/nest/infrastructure/decorators/Module';
import {TranslationModule} from '@steroidsjs/nest-translation/infrastructure/TranslationModule';

@Module({
    module: (config) => {
        const module = baseConfig.module(config);
        return {
            ...module,
            imports: [
                TranslationModule.forRoot(),
                ...module.imports,
            ].filter(Boolean),
        };
    },
})
export class AppModule {}
  1. Переопределить RestApplication, чтобы переводить ошибки валидации и nestjs http исключения:
import {RestApplication as BaseRestApplication} from '@steroidsjs/nest/infrastructure/applications/rest/RestApplication';
import {TranslationHelper} from '@steroidsjs/nest-translation/domain/helpers/TranslationHelper';
import {
    TranslationValidationExceptionFilter,
} from '@steroidsjs/nest-translation/infrastructure/filters/TranslationValidationExceptionFilter';
import {
    TranslationHttpExceptionFilter,
} from '@steroidsjs/nest-translation/infrastructure/filters/TranslationHttpExceptionFilter';
import {I18nService} from 'nestjs-i18n';

export class RestApplication extends BaseRestApplication {
    protected initFilters() {
        this._app.useGlobalFilters(
            // Используем вместо ValidationExceptionFilter
            new TranslationValidationExceptionFilter(),
            // Используем вместо HttpExceptionFilter
            new TranslationHttpExceptionFilter(),
            ...otherFilters,
        );
    }

    protected initTranslation() {
        TranslationHelper.translationService = this._app.get(I18nService);
    }

    async init(): Promise<void> {
        await super.init();
        this.initTranslation();
    }
}

Использование

Чтобы перевести строку, нужно использовать функцию TranslationHelper.translate или короткий алиас __. По умолчанию желаемый язык ответа передаётся в хедере Accept-Language, но можно кастомизировать логику, передав нужные значения в вызов TranslationModule.forRoot (интерфейс ITranslationModuleConfig).

Рассмотрим пример:

import {Controller, Get} from '@nestjs/common';
import {ApiHeader, ApiTags} from '@nestjs/swagger';
import {ValidationException} from '@steroidsjs/nest/usecases/exceptions/ValidationException';
import {BadRequestException} from '@steroidsjs/nest/usecases/exceptions';
import {__, TranslationHelper} from '@steroidsjs/nest-translation/domain/helpers/TranslationHelper';

@ApiHeader({
    name: 'Accept-Language',
    description: 'Язык ответа',
    required: false,
    schema: {
        type: 'string',
        default: 'ru',
    },
})
@ApiTags('Translation')
@Controller('/translation')
export class TranslationController {
    @Get('')
    stringTest() {
        return __('Привет мир!');
    }

    @Get('/arg')
    stringArgTest() {
        return TranslationHelper.translate('Привет {worldArg}!', {
            args: {
                worldArg: TranslationHelper.translate('мир'),
            },
        });
    }

    @Get('/error/val')
    errorValidationTest() {
        throw new ValidationException({field: 'Ошибка'});
    }

    @Get('/error/bad-request')
    errorBadRequestTest() {
        throw new BadRequestException('Плохой запрос');
    }
}

Передача аргументов в строке показана в функции stringArgTest. Не стоит использовать js шаблонные строки, как, например, Привет ${мир}.

Наконец, чтобы собрать файлы с переводами, нужно выполнить команду:

yarn cli extract-translations

Если использовать настройки по умолчанию, то из примера выше соберётся два файла в папке translations:

ru.json:

{
  "Плохой запрос": "Плохой запрос",
  "Ошибка": "Ошибка",
  "Привет {worldArg}!": "Привет {worldArg}!",
  "мир": "мир",
  "Привет мир!": "Привет мир!"
}

en.json:

{
  "Плохой запрос": "",
  "Ошибка": "",
  "Привет {worldArg}!": "",
  "мир": "",
  "Привет мир!": ""
}

При использовании языка en если в файле значение ключа будет пустой строкой, то в качестве значения будет использоваться сам ключ.