summaryrefslogtreecommitdiff
path: root/src/api/endpoints/posts/context.ts
diff options
context:
space:
mode:
authorsyuilo <syuilotan@yahoo.co.jp>2017-03-02 17:08:09 +0900
committersyuilo <syuilotan@yahoo.co.jp>2017-03-02 17:08:09 +0900
commitf3d5c07ada08a089969176cdb7b7bfc3f0132fda (patch)
treef54d6b6d7702bbd3d2c4d2777c2c1c6262ec6ce3 /src/api/endpoints/posts/context.ts
parentwip (diff)
downloadsharkey-f3d5c07ada08a089969176cdb7b7bfc3f0132fda.tar.gz
sharkey-f3d5c07ada08a089969176cdb7b7bfc3f0132fda.tar.bz2
sharkey-f3d5c07ada08a089969176cdb7b7bfc3f0132fda.zip
wip
Diffstat (limited to 'src/api/endpoints/posts/context.ts')
-rw-r--r--src/api/endpoints/posts/context.ts81
1 files changed, 81 insertions, 0 deletions
diff --git a/src/api/endpoints/posts/context.ts b/src/api/endpoints/posts/context.ts
new file mode 100644
index 0000000000..673da0fab8
--- /dev/null
+++ b/src/api/endpoints/posts/context.ts
@@ -0,0 +1,81 @@
+'use strict';
+
+/**
+ * Module dependencies
+ */
+import validate from '../../validator';
+import Post from '../../models/post';
+import serialize from '../../serializers/post';
+
+/**
+ * Show a context of a post
+ *
+ * @param {any} params
+ * @param {any} user
+ * @return {Promise<any>}
+ */
+module.exports = (params, user) =>
+ new Promise(async (res, rej) =>
+{
+ // Get 'post_id' parameter
+ const [postId, postIdErr] = validate(params.post_id, 'id', true);
+ if (postIdErr) return rej('invalid post_id');
+
+ // Get 'limit' parameter
+ let [limit, limitErr] = validate(params.limit, 'number');
+ if (limitErr) return rej('invalid limit');
+
+ if (limit !== null) {
+ // From 1 to 100
+ if (!(1 <= limit && limit <= 100)) {
+ return rej('invalid limit range');
+ }
+ } else {
+ limit = 10;
+ }
+
+ // Get 'offset' parameter
+ let offset = params.offset;
+ if (offset !== undefined && offset !== null) {
+ offset = parseInt(offset, 10);
+ } else {
+ offset = 0;
+ }
+
+ // Lookup post
+ const post = await Post.findOne({
+ _id: new mongo.ObjectID(postId)
+ });
+
+ if (post === null) {
+ return rej('post not found', 'POST_NOT_FOUND');
+ }
+
+ const context = [];
+ let i = 0;
+
+ async function get(id) {
+ i++;
+ const p = await Post.findOne({ _id: id });
+
+ if (i > offset) {
+ context.push(p);
+ }
+
+ if (context.length == limit) {
+ return;
+ }
+
+ if (p.reply_to_id) {
+ await get(p.reply_to_id);
+ }
+ }
+
+ if (post.reply_to_id) {
+ await get(post.reply_to_id);
+ }
+
+ // Serialize
+ res(await Promise.all(context.map(async post =>
+ await serialize(post, user))));
+});