refactor(localize): tighten up recognition of simple JSON translations (#36745)

PR Close #36745
This commit is contained in:
Pete Bacon Darwin 2020-04-19 17:42:37 +01:00 committed by Matias Niemelä
parent afd2cbc3c4
commit 3962908d36
2 changed files with 23 additions and 10 deletions

View File

@ -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];

View File

@ -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()', () => {