Skip to content

Commit

Permalink
feat(nls): support nested localized messages
Browse files Browse the repository at this point in the history
  • Loading branch information
alex8088 committed Apr 6, 2024
1 parent 578f210 commit 45352f9
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
7 changes: 5 additions & 2 deletions packages/nls/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,19 @@ npm i @tiny-libs/nls
import nls from '@tiny-libs/nls'

const messages = {
'say.hello': '你好, {0}'
'say.hello': '你好, {0}',
say: {
yes: '好的, {0}'
}
}

const localize = nls.loadMessages(messages)

console.log(localize('hello.world', 'Hello World')) // Output: Hello World
console.log(localize('say.hello', 'Hello, {0}', 'Alex')) // Output: 你好, Alex
console.log(localize('say.yes', 'Yes, {0}', 'Alex')) // Output: 好的, Alex
```

## License

[MIT](./LICENSE) copyright © 2024-present alex wei

30 changes: 27 additions & 3 deletions packages/nls/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,37 @@ function format(
return result
}

function createLocalizeFunc(messages: Record<string, string>): LocalizeFunc {
function findNestedObject(
obj: Record<string, unknown>,
key: string
): string | undefined {
const value = obj[key]

if (value !== undefined && typeof value === 'string') {
return value
}

const keys = key.split('.')
let result: string | Record<string, unknown> = obj

for (const k of keys) {
if (result[k] !== undefined) {
result = result[k]
} else {
return undefined
}
}

return typeof result === 'string' ? result : undefined
}

function createLocalizeFunc(messages: Record<string, unknown>): LocalizeFunc {
return function (key: string, message: string, ...args: any[]): string {
return format(messages[key] || message, args)
return format(findNestedObject(messages, key) || message, args)
}
}

function loadMessages(messages: Record<string, string> = {}): LocalizeFunc {
function loadMessages(messages: Record<string, unknown> = {}): LocalizeFunc {
return createLocalizeFunc(messages)
}

Expand Down
6 changes: 5 additions & 1 deletion packages/nls/test.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import nls from './dist/index.mjs'

const messages = {
'say.hello': '你好, {0}'
'say.hello': '你好, {0}',
say: {
yes: '好的, {0}'
}
}

const localize = nls.loadMessages(messages)

console.log(localize('hello.world', 'Hello World'))
console.log(localize('say.hello', 'Hello, {0}', 'Alex'))
console.log(localize('say.yes', 'Yes, {0}', 'Alex'))

0 comments on commit 45352f9

Please sign in to comment.