Skip to content

Commit

Permalink
add simple toJSON function to fix uncontrolled serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
adrai committed May 22, 2021
1 parent 24ed5ab commit 3352276
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
### 20.3.0

- add simple toJSON function to fix uncontrolled serialization, fixes [1322](https://github.com/i18next/react-i18next/issues/1322)

### 20.2.4

- fix types for LanguageDetector detect function
Expand Down
10 changes: 10 additions & 0 deletions i18next.js
Original file line number Diff line number Diff line change
Expand Up @@ -2468,6 +2468,16 @@
};
return clone;
}
}, {
key: "toJSON",
value: function toJSON() {
return {
options: this.options,
store: this.store,
language: this.language,
languages: this.languages
};
}
}]);

return I18n;
Expand Down
2 changes: 1 addition & 1 deletion i18next.min.js

Large diffs are not rendered by default.

9 changes: 9 additions & 0 deletions src/i18next.js
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,15 @@ class I18n extends EventEmitter {

return clone;
}

toJSON() {
return {
options: this.options,
store: this.store,
language: this.language,
languages: this.languages
};
}
}

export default new I18n();
46 changes: 46 additions & 0 deletions test/i18next.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import i18next from '../src/i18next.js';
import { get as getDefaults } from '../src/defaults';

describe('i18next', () => {
before(() => {
Expand Down Expand Up @@ -131,4 +132,49 @@ describe('i18next', () => {
});
});
});

describe('#JSON.stringify', () => {
let newInstance;
before(() => {
newInstance = i18next.createInstance({ some: 'options' });
});

it('it should JSON.stringify non-initialized without errors', () => {
expect(JSON.stringify(newInstance)).to.equal(
JSON.stringify({
options: { some: 'options' },
}),
);
});

it('it should JSON.stringify initialized without errors', done => {
newInstance.init({ other: 'opts' }, err => {
if (err) return done(err);

newInstance.addResourceBundle('en', 'translation', { key: 'value' });
newInstance.changeLanguage('en');

expect(JSON.stringify(newInstance)).to.equal(
JSON.stringify({
options: {
...getDefaults(),
some: 'options',
other: 'opts',
ignoreJSONStructure: true,
},
store: {
en: {
translation: {
key: 'value',
},
},
},
language: 'en',
languages: ['en', 'dev'],
}),
);
done();
});
});
});
});

0 comments on commit 3352276

Please sign in to comment.