File

lib/shared/modules/locale/locale.service.ts

Description

Service for handling localization operations.

Index

Methods

Constructor

constructor(languageRep: Repository<LanguageEntity>, localizedStringRep: Repository<LocalizedStringEntity>, localizedMediaRep: Repository<LocalizedMediaEntity>)
Parameters :
Name Type Optional
languageRep Repository<LanguageEntity> No
localizedStringRep Repository<LocalizedStringEntity> No
localizedMediaRep Repository<LocalizedMediaEntity> No

Methods

Async createLocalizedStrings
createLocalizedStrings(value: string, code?: string)

Creates localized strings for all available languages.

Parameters :
Name Type Optional Description
value string No
  • The value to be localized.
code string Yes
  • An optional code to be used for the localized strings.

A promise that resolves to an array of LocalizedStringEntity objects.

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { LanguageEntity } from "./entity/language.entity";
import { LocalizedStringEntity } from "./entity/localized-string.entity";
import { LocalizedMediaEntity } from "./entity/localized-media.entity";

/**
 * Service for handling localization operations.
 */
@Injectable()
export class LocaleService {
  constructor(
    @InjectRepository(LanguageEntity)
    private readonly languageRep: Repository<LanguageEntity>,
    @InjectRepository(LocalizedStringEntity)
    private readonly localizedStringRep: Repository<LocalizedStringEntity>,
    @InjectRepository(LocalizedMediaEntity)
    private readonly localizedMediaRep: Repository<LocalizedMediaEntity>,
  ) {}

  /**
   * Creates localized strings for all available languages.
   * @param value - The value to be localized.
   * @param code - An optional code to be used for the localized strings.
   * @returns A promise that resolves to an array of LocalizedStringEntity objects.
   */
  async createLocalizedStrings(
    value: string,
    code?: string,
  ): Promise<LocalizedStringEntity[]> {
    const languages = await this.languageRep.find();
    const res: LocalizedStringEntity[] = [];
    for (const language of languages) {
      const ls = new LocalizedStringEntity();
      ls.lang = language;
      ls.value = value;
      if (code) {
        ls.code = `${code}_${language.id}`;
        const existed = await this.localizedStringRep.findOne({
          where: { code: ls.code },
        });
        ls.id = existed?.id;
      }
      await this.localizedStringRep.save(ls);
      res.push(ls);
    }
    return res;
  }
}

results matching ""

    No results matching ""