Skip to content

Commit

Permalink
fix: not allow to override the app.locals.__ method (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 authored Jan 12, 2025
1 parent 4de5740 commit 6e8447c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,15 @@ export default class I18n implements ILifecycleBoot {
return ctx.gettext(key, ...args);
}
// 在 view 中使用 `__(key, value, ...args)`
this.app.locals.gettext = gettextInContext;
this.app.locals.__ = gettextInContext;
Object.defineProperties(app.locals, {
__: {
value: gettextInContext,
enumerable: true,
},
gettext: {
value: gettextInContext,
enumerable: true,
},
});
}
}
14 changes: 14 additions & 0 deletions test/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,20 @@ describe('test/i18n.test.ts', () => {
assert.strictEqual(ctx.app.__('en-us', 'Email {0} {1}', [ 'a', 'b' ]), 'Email a b');
assert.strictEqual(ctx.app.__('en-us', '', [ 'a', 'b' ]), '');
});

it('should ctx.locals.__() work', () => {
const ctx = app.mockContext();
assert.equal(ctx.locals.__('Email %s', 'ok'), 'Email ok');
ctx.locals.a = 'aaa';
assert.equal(ctx.locals.a, 'aaa');
assert.deepEqual(Object.keys(ctx.locals), [ '__', 'gettext', 'a' ]);
});

it('should not allow to override the app.locals.__', () => {
assert.throws(() => {
app.locals.__ = () => 'app.__';
}, /Cannot assign to read only property '__' of object/);
});
});

describe('with cookieDomain', () => {
Expand Down

0 comments on commit 6e8447c

Please sign in to comment.