Files
mattermost-mobile/app/database/operator/utils/post.ts
Elias Nahum 324dbbd054 [Gekidou] fix database schema and models (#5553)
* fix database schema and models

* fix types
2021-07-20 23:24:42 +04:00

68 lines
2.1 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import type {ChainPostsArgs, SanitizePostsArgs} from '@typings/database/database';
/**
* sanitizePosts: Creates arrays of ordered and unordered posts. Unordered posts are those posts that are not
* present in the orders array
* @param {SanitizePostsArgs} sanitizePosts
* @param {Post[]} sanitizePosts.posts
* @param {string[]} sanitizePosts.orders
*/
export const sanitizePosts = ({posts, orders}: SanitizePostsArgs) => {
const orderedPosts: Post[] = [];
const unOrderedPosts: Post[] = [];
posts.forEach((post) => {
if (post?.id && orders.includes(post.id)) {
orderedPosts.push(post);
} else {
unOrderedPosts.push(post);
}
});
return {
postsOrdered: orderedPosts,
postsUnordered: unOrderedPosts,
};
};
/**
* createPostsChain: Basically creates the 'chain of posts' using the 'orders' array; each post is linked to the other
* by the previous_post_id field.
* @param {ChainPostsArgs} chainPosts
* @param {string[]} chainPosts.order
* @param {Post[]} chainPosts.posts
* @param {string} chainPosts.previousPostId
* @returns {Post[]}
*/
export const createPostsChain = ({order, posts, previousPostId = ''}: ChainPostsArgs) => {
return order.reduce((result, id, index) => {
const post = posts.find((p) => p.id === id);
if (post) {
if (index === order.length - 1) {
result.push({...post, prev_post_id: previousPostId});
} else {
result.push({...post, prev_post_id: order[index + 1]});
}
}
return result;
}, [] as Post[]);
};
export const getPostListEdges = (posts: Post[]) => {
// Sort a clone of 'posts' array by create_at
const sortedPosts = [...posts].sort((a, b) => {
return a.create_at - b.create_at;
});
// The first element (beginning of chain)
const firstPost = sortedPosts[0];
const lastPost = sortedPosts[sortedPosts.length - 1];
return {firstPost, lastPost};
};