refactor(localize): tighten up recognition of simple JSON translations (#36745)
PR Close #36745
This commit is contained in:
parent
afd2cbc3c4
commit
3962908d36
|
@ -23,13 +23,21 @@ import {ParsedTranslationBundle, TranslationParser} from './translation_parser';
|
|||
* }
|
||||
* ```
|
||||
*/
|
||||
export class SimpleJsonTranslationParser implements TranslationParser {
|
||||
canParse(filePath: string, _contents: string): boolean {
|
||||
return (extname(filePath) === '.json');
|
||||
export class SimpleJsonTranslationParser implements TranslationParser<Object> {
|
||||
canParse(filePath: string, contents: string): Object|false {
|
||||
if (extname(filePath) !== '.json') {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const json = JSON.parse(contents);
|
||||
return (typeof json.locale === 'string' && typeof json.translations === 'object') && json;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
parse(_filePath: string, contents: string): ParsedTranslationBundle {
|
||||
const {locale: parsedLocale, translations} = JSON.parse(contents);
|
||||
parse(_filePath: string, contents: string, json?: Object): ParsedTranslationBundle {
|
||||
const {locale: parsedLocale, translations} = json || JSON.parse(contents);
|
||||
const parsedTranslations: Record<ɵMessageId, ɵParsedTranslation> = {};
|
||||
for (const messageId in translations) {
|
||||
const targetMessage = translations[messageId];
|
||||
|
|
|
@ -10,11 +10,16 @@ import {SimpleJsonTranslationParser} from '../../../../src/translate/translation
|
|||
|
||||
describe('SimpleJsonTranslationParser', () => {
|
||||
describe('canParse()', () => {
|
||||
it('should return true if the file extension is `.json`', () => {
|
||||
const parser = new SimpleJsonTranslationParser();
|
||||
expect(parser.canParse('/some/file.xlf', '')).toBe(false);
|
||||
expect(parser.canParse('/some/file.json', '')).toBe(true);
|
||||
});
|
||||
it('should return true if the file extension is `.json` and contains top level `locale` and `translations` properties',
|
||||
() => {
|
||||
const parser = new SimpleJsonTranslationParser();
|
||||
expect(parser.canParse('/some/file.xlf', '')).toBe(false);
|
||||
expect(parser.canParse('/some/file.json', '{}')).toBe(false);
|
||||
expect(parser.canParse('/some/file.json', '{ "translations" : {} }')).toBe(false);
|
||||
expect(parser.canParse('/some/file.json', '{ "locale" : "fr" }')).toBe(false);
|
||||
expect(parser.canParse('/some/file.json', '{ "locale" : "fr", "translations" : {}}'))
|
||||
.toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('parse()', () => {
|
||||
|
|
Loading…
Reference in New Issue