I have developed a Post and Comment module inside SPFx. where i have 3 sharepoint lists, that are connected to each other using lookup fields:-
here is the SPFX, with 2 posts and the first post has 2 comments:-
Currently the Posts and their Comments will be shown sorted by the created date , here is the method to show the posts:-
async getPostsPage(pageSize: number = 10, afterId?: number) {
let url = `${this.siteUrl}/_api/web/lists/getByTitle('SocialPosts')/items`
+ `?$select=Id,Title,Body,Created,Author/Id,Author/Title,LikeCount,CommentCount`
+ `&$expand=Author&$orderby=Id desc&$top=${pageSize}`;
if (afterId) url += `&$filter=Id lt ${afterId}`;
const data = await this.getJson<{ value: any[] }>(url);
return data.value.map(v => ({
Id: v.Id,
Title: v.Title,
Body: v.Body,
Created: v.Created,
AuthorId: v.Author?.Id,
AuthorTitle: v.Author?.Title,
LikeCount: v.LikeCount || 0,
CommentCount: v.CommentCount || 0
})) as import('../Models/Models').Post[];
}
and the comments:-
// ---------- Comments ----------
async getComments(postId: number): Promise<Comment[]> {
const url =
this.commentsUrl() +
`?$select=Id,Body,Created,Author/Id,Author/Title,LikeCount,Post/Id,PostId` +
`&$expand=Author,Post&$filter=PostId eq ${postId}&$orderby=Created asc`;
const data = await this.getJson<{ value: any[] }>(url);
return data.value.map((v) => ({
Id: v.Id,
Body: v.Body,
Created: v.Created,
AuthorId: v.Author?.Id,
AuthorTitle: v.Author?.Title,
LikeCount: v.LikeCount || 0,
PostId: v.PostId ?? v.Post?.Id,
}));
}
but the client is asking us if there is a way to order the items using AI algorithm so it show the most relevant posts and comments
first? which approach i can follow? to order items inside SPFx using AI algorithm instead of Created date?? any advice?
ageHours = (now - Created) in hours
freshness = exp(-ageHours / 48) // time decay, Ï„=48h
engagement = log1p(LikeCount) + 0.5*log1p(CommentCount)
authorAffinity = 1 if currentUser follows/mentions author else 0 // optional
RankScore = 0.6*freshness + 0.35*engagement + 0.05*authorAffinity
wilson95(p, n) // p = likes/n, n = likes+downs (if only likes, use n=likes, p≈min(1, likes/5))
freshness = exp(-ageHours / 72)
RankScore = 0.7*wilson95 + 0.3*freshness
// Posts
let url = `${this.siteUrl}/_api/web/lists/getByTitle('SocialPosts')/items`
+ `?$select=Id,Title,Body,Created,Author/Id,Author/Title,LikeCount,CommentCount,RankScore`
+ `&$expand=Author&$orderby=RankScore desc,Id desc&$top=${pageSize}`;
// Use $skiptoken pagination with custom order
if (skiptoken) url += `&$skiptoken=${encodeURIComponent(skiptoken)}`;
// Comments for a post
const url = this.commentsUrl()
+ `?$select=Id,Body,Created,Author/Id,Author/Title,LikeCount,PostId,RankScore`
+ `&$expand=Author&$filter=PostId eq ${postId}`
+ `&$orderby=RankScore desc,Id desc`;