Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

YmlLoaderImpl #311

Merged
merged 3 commits into from
Apr 12, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -88,6 +88,7 @@
"accept-language-parser": "^1.5.0",
"chokidar": "^3.5.3",
"cookie": "^0.4.1",
"js-yaml": "^4.1.0",
"string-format": "^2.0.0"
},
"peerDependencies": {
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -36,6 +36,7 @@ export * from './resolvers/grpc-metadata.resolver';
// build in loaders
export * from './loaders/i18n.loader';
export * from './loaders/i18n.json.loader';
export * from './loaders/i18n.yaml.loader';

// interceptor
export * from './interceptors/i18n-language.interceptor';
163 changes: 163 additions & 0 deletions src/loaders/i18n.abstract.loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import { I18nLoader } from './i18n.loader';
import { I18N_LOADER_OPTIONS } from '../i18n.constants';
import { Inject, OnModuleDestroy } from '@nestjs/common';
import * as path from 'path';
import * as fs from 'fs';
import { getDirectories, getFiles } from '../utils/file';
import { promisify } from 'util';
import { I18nTranslation } from '../interfaces/i18n-translation.interface';
import {
Observable,
Subject,
merge as ObservableMerge,
from as ObservableFrom,
} from 'rxjs';
import * as chokidar from 'chokidar';
import { switchMap } from 'rxjs/operators';
const readFile = promisify(fs.readFile);
const exists = promisify(fs.exists);

export interface I18nAbstractLoaderOptions {
path: string;
filePattern?: string;
watch?: boolean;
}

// const defaultOptions: Partial<I18nAbstractLoaderOptions> = {
// filePattern: '*.json',
// watch: false,
// };

export abstract class I18nAbstractLoader extends I18nLoader implements OnModuleDestroy {
private watcher?: chokidar.FSWatcher;

private events: Subject<string> = new Subject();

constructor(
@Inject(I18N_LOADER_OPTIONS)
private options: I18nAbstractLoaderOptions,
) {
super();
this.options = this.sanitizeOptions(options);

if (this.options.watch) {
this.watcher = chokidar
.watch(this.options.path, { ignoreInitial: true })
.on('all', (event) => {
this.events.next(event);
});
}
}

async onModuleDestroy() {
if (this.watcher) {
await this.watcher.close();
}
}

async languages(): Promise<string[] | Observable<string[]>> {
if (this.options.watch) {
return ObservableMerge(
ObservableFrom(this.parseLanguages()),
this.events.pipe(switchMap(() => this.parseLanguages())),
);
}
return this.parseLanguages();
}

async load(): Promise<I18nTranslation | Observable<I18nTranslation>> {
if (this.options.watch) {
return ObservableMerge(
ObservableFrom(this.parseTranslations()),
this.events.pipe(switchMap(() => this.parseTranslations())),
);
}
return this.parseTranslations();
}

private async parseTranslations(): Promise<I18nTranslation> {
const i18nPath = path.normalize(this.options.path + path.sep);

const translations: I18nTranslation = {};

if (!(await exists(i18nPath))) {
throw new Error(`i18n path (${i18nPath}) cannot be found`);
}

if (!this.options.filePattern.match(/\*\.[A-z]+/)) {
throw new Error(
`filePattern should be formatted like: *.json, *.txt, *.custom etc`,
);
}

const languages = await this.parseLanguages();

const pattern = new RegExp(
'.' + this.options.filePattern.replace('.', '.'),
);

const files = await [
...languages.map((l) => path.join(i18nPath, l)),
i18nPath,
].reduce(async (f: Promise<string[]>, p: string) => {
(await f).push(...(await getFiles(p, pattern)));
return f;
}, Promise.resolve([]));

for (const file of files) {
let global = false;

const key = path
.dirname(path.relative(i18nPath, file))
.split(path.sep)[0];

if (key === '.') {
global = true;
}

// const data = JSON.parse(await readFile(file, 'utf8'));
const data = this.formatData(await readFile(file, 'utf8'));

const prefix = path.basename(file).split('.')[0];

for (const property of Object.keys(data)) {
[...(global ? languages : [key])].forEach((lang) => {
translations[lang] = translations[lang] ? translations[lang] : {};

if (global) {
translations[lang][property] = data[property];
} else {
translations[lang][prefix] = translations[lang][prefix]
? translations[lang][prefix]
: {};

translations[lang][prefix][property] = data[property];
}
});
}
}

return translations;
}

private async parseLanguages(): Promise<string[]> {
const i18nPath = path.normalize(this.options.path + path.sep);
return (await getDirectories(i18nPath)).map((dir) =>
path.relative(i18nPath, dir),
);
}

private sanitizeOptions(options: I18nAbstractLoaderOptions) {
options = { ...this.getDefaultOptions(), ...options };

options.path = path.normalize(options.path + path.sep);
if (!options.filePattern.startsWith('*.')) {
options.filePattern = '*.' + options.filePattern;
}

return options;
}

abstract formatData(data: any);
abstract getDefaultOptions(): Partial<I18nAbstractLoaderOptions>;
}
164 changes: 9 additions & 155 deletions src/loaders/i18n.json.loader.ts
Original file line number Diff line number Diff line change
@@ -1,159 +1,13 @@
import { I18nLoader } from './i18n.loader';
import { I18N_LOADER_OPTIONS } from '../i18n.constants';
import { Inject, OnModuleDestroy } from '@nestjs/common';
import * as path from 'path';
import * as fs from 'fs';
import { getDirectories, getFiles } from '../utils/file';
import { promisify } from 'util';
import { I18nTranslation } from '../interfaces/i18n-translation.interface';
import {
Observable,
Subject,
merge as ObservableMerge,
from as ObservableFrom,
} from 'rxjs';
import * as chokidar from 'chokidar';
import { switchMap } from 'rxjs/operators';
const readFile = promisify(fs.readFile);
const exists = promisify(fs.exists);
import { I18nAbstractLoader, I18nAbstractLoaderOptions } from './i18n.abstract.loader';

export interface I18nJsonLoaderOptions {
path: string;
filePattern?: string;
watch?: boolean;
}

const defaultOptions: Partial<I18nJsonLoaderOptions> = {
filePattern: '*.json',
watch: false,
};

export class I18nJsonLoader extends I18nLoader implements OnModuleDestroy {
private watcher?: chokidar.FSWatcher;

private events: Subject<string> = new Subject();

constructor(
@Inject(I18N_LOADER_OPTIONS)
private options: I18nJsonLoaderOptions,
) {
super();
this.options = this.sanitizeOptions(options);

if (this.options.watch) {
this.watcher = chokidar
.watch(this.options.path, { ignoreInitial: true })
.on('all', (event) => {
this.events.next(event);
});
}
}

async onModuleDestroy() {
if (this.watcher) {
await this.watcher.close();
}
}

async languages(): Promise<string[] | Observable<string[]>> {
if (this.options.watch) {
return ObservableMerge(
ObservableFrom(this.parseLanguages()),
this.events.pipe(switchMap(() => this.parseLanguages())),
);
}
return this.parseLanguages();
}

async load(): Promise<I18nTranslation | Observable<I18nTranslation>> {
if (this.options.watch) {
return ObservableMerge(
ObservableFrom(this.parseTranslations()),
this.events.pipe(switchMap(() => this.parseTranslations())),
);
}
return this.parseTranslations();
}

private async parseTranslations(): Promise<I18nTranslation> {
const i18nPath = path.normalize(this.options.path + path.sep);

const translations: I18nTranslation = {};

if (!(await exists(i18nPath))) {
throw new Error(`i18n path (${i18nPath}) cannot be found`);
}

if (!this.options.filePattern.match(/\*\.[A-z]+/)) {
throw new Error(
`filePattern should be formatted like: *.json, *.txt, *.custom etc`,
);
}

const languages = await this.parseLanguages();

const pattern = new RegExp(
'.' + this.options.filePattern.replace('.', '.'),
);

const files = await [
...languages.map((l) => path.join(i18nPath, l)),
i18nPath,
].reduce(async (f: Promise<string[]>, p: string) => {
(await f).push(...(await getFiles(p, pattern)));
return f;
}, Promise.resolve([]));

for (const file of files) {
let global = false;

const key = path
.dirname(path.relative(i18nPath, file))
.split(path.sep)[0];

if (key === '.') {
global = true;
}

const data = JSON.parse(await readFile(file, 'utf8'));

const prefix = path.basename(file).split('.')[0];

for (const property of Object.keys(data)) {
[...(global ? languages : [key])].forEach((lang) => {
translations[lang] = translations[lang] ? translations[lang] : {};

if (global) {
translations[lang][property] = data[property];
} else {
translations[lang][prefix] = translations[lang][prefix]
? translations[lang][prefix]
: {};

translations[lang][prefix][property] = data[property];
}
});
}
}

return translations;
}

private async parseLanguages(): Promise<string[]> {
const i18nPath = path.normalize(this.options.path + path.sep);
return (await getDirectories(i18nPath)).map((dir) =>
path.relative(i18nPath, dir),
);
export class I18nJsonLoader extends I18nAbstractLoader {
getDefaultOptions(): Partial<I18nAbstractLoaderOptions> {
return {
filePattern: '*.json',
watch: false,
};
}

private sanitizeOptions(options: I18nJsonLoaderOptions) {
options = { ...defaultOptions, ...options };

options.path = path.normalize(options.path + path.sep);
if (!options.filePattern.startsWith('*.')) {
options.filePattern = '*.' + options.filePattern;
}

return options;
formatData(data: any) {
return JSON.parse(data)
}
}
Loading