Skip to content

Instantly share code, notes, and snippets.

@abedzantout
Created October 2, 2019 10:07
Show Gist options
  • Save abedzantout/8a14b5ebdc5266f15db494524abd9803 to your computer and use it in GitHub Desktop.
Save abedzantout/8a14b5ebdc5266f15db494524abd9803 to your computer and use it in GitHub Desktop.
contentful suggestions function
async fetchSuggestions(tags: string[], currentArticleSlug: string) {
const limit = 3; // limit of posts we want to fetch
let entries = [];
const initialOptions = {
content_type: CONTENT_TYPE_BLOGPOST,
limit,
// find at least one matching tag, else undefined properties are not copied
'fields.tags.sys.id[in]': tags.length ? tags.join(',') : undefined,
'fields.slug[ne]': currentArticleSlug, // exclude current article
};
try {
const suggestionsByTags = await this.client.getEntries(initialOptions);
entries = suggestionsByTags.items;
// number of suggestions by tag is less than the limit
if (suggestionsByTags.total < limit) {
// exclude already picked slugs
const slugsToExclude = [...suggestionsByTags.items, {fields: {slug: currentArticleSlug}}]
.map((item: { fields: any }) => item.fields.slug)
.join(',');
// fetch random suggestions
const randomSuggestions = await this.client.getEntries({
content_type: CONTENT_TYPE_BLOGPOST,
limit: limit - suggestionsByTags.total,
'fields.slug[nin]': slugsToExclude, // exclude slugs already fetched
});
entries = [...entries, ...randomSuggestions.items];
}
entries = this.mapData(entries);
return entries;
} catch (e) {
console.error(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment