Skip to content

Commit

Permalink
Allow rejection of attempted load via returning falsy loadPath (#88)
Browse files Browse the repository at this point in the history
* Allow rejection of attempted load via returning falsy loadPath

* callback with empty object {} if resolvedLoadPath is falsy
  • Loading branch information
ItsOnlyBinary committed Mar 13, 2022
1 parent d6f745f commit b1e9823
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ for plain browser:
// function(lngs, namespaces) { return customPath; }
// the returned path will interpolate lng, ns if provided like giving a static path
// the function might return a promise
// returning falsy will abort the download
//
// If allowMultiLoading is false, lngs and namespaces will have only one element each,
// If allowMultiLoading is true, lngs and namespaces can have multiple elements
Expand Down
1 change: 1 addition & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class Backend {
loadPath = makePromise(loadPath)

loadPath.then(resolvedLoadPath => {
if (!resolvedLoadPath) return callback(null, {})
const url = this.services.interpolator.interpolate(resolvedLoadPath, { lng: languages.join('+'), ns: namespaces.join('+') })
this.loadUrl(url, callback, loadUrlLanguages, loadUrlNamespaces)
})
Expand Down
34 changes: 34 additions & 0 deletions test/http.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,40 @@ describe(`http backend using ${hasXMLHttpRequest ? 'XMLHttpRequest' : 'fetch'}`,
})
})

describe('with loadPath function returning falsy', () => {
let backend
let calledLanguages = []
let calledNamespaces = []
const loadPathSpy = (languages, namespaces) => {
calledLanguages = calledLanguages.concat(languages)
calledNamespaces = calledNamespaces.concat(namespaces)
return ''
}

before(() => {
backend = new Http(
{
interpolator: i18next.services.interpolator
},
{
loadPath: loadPathSpy
}
)
})

describe('#read', () => {
it('should not load data', (done) => {
backend.read('en', 'test', (err, data) => {
expect(err).not.to.be.ok()
expect(calledLanguages).to.eql(['en'])
expect(calledNamespaces).to.eql(['test'])
expect(data).to.eql({})
done()
})
})
})
})

describe('with addPath function', () => {
let backend
const calledLanguages = []
Expand Down

0 comments on commit b1e9823

Please sign in to comment.