🐛 Fixed broken index when API returns no results

refs https://github.com/TryGhost/Team/issues/1665

- The search index should be initialized regardless, even if there are no items to put into it the index should be an empty one.
This commit is contained in:
Naz 2022-07-06 11:31:23 +02:00
parent cc87eb4bc9
commit 21a9a4eaba
2 changed files with 22 additions and 16 deletions

View File

@ -62,37 +62,37 @@ export default class SearchIndex {
const postsResponse = await fetch(postsAPIUrl);
const posts = await postsResponse.json();
if (posts.posts.length > 0) {
this.postsIndex = elasticlunr();
this.postsIndex.addField('title');
this.postsIndex.addField('url');
this.postsIndex.addField('excerpt');
this.postsIndex.setRef('id');
this.postsIndex = elasticlunr();
this.postsIndex.addField('title');
this.postsIndex.addField('url');
this.postsIndex.addField('excerpt');
this.postsIndex.setRef('id');
if (posts.posts.length > 0) {
this.#updatePostIndex(posts);
}
const authorsResponse = await fetch(authorsAPIUrl);
const authors = await authorsResponse.json();
if (authors.authors.length > 0) {
this.authorsIndex = elasticlunr();
this.authorsIndex.addField('name');
this.authorsIndex.addField('url');
this.authorsIndex.setRef('id');
this.authorsIndex = elasticlunr();
this.authorsIndex.addField('name');
this.authorsIndex.addField('url');
this.authorsIndex.setRef('id');
if (authors.authors.length > 0) {
this.#updateAuthorsIndex(authors);
}
const tagsResponse = await fetch(tagsAPIUrl);
const tags = await tagsResponse.json();
if (tags.tags.length > 0) {
this.tagsIndex = elasticlunr();
this.tagsIndex.addField('name');
this.tagsIndex.addField('url');
this.tagsIndex.setRef('id');
this.tagsIndex = elasticlunr();
this.tagsIndex.addField('name');
this.tagsIndex.addField('url');
this.tagsIndex.setRef('id');
if (tags.tags.length > 0) {
this.#updateTagsIndex(tags);
}
} else {

View File

@ -28,6 +28,12 @@ describe('search index', function () {
await searchIndex.init({apiUrl, apiKey});
expect(scope.isDone()).toBeTruthy();
const searchResults = searchIndex.search('find nothing');
expect(searchResults.posts.length).toEqual(0);
expect(searchResults.authors.length).toEqual(0);
expect(searchResults.tags.length).toEqual(0);
});
test('allows to search for indexed posts and authors', async () => {