From a53edc96bec3503517daa24837def5d3ecd82624 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 03:16:39 +0900 Subject: wip --- src/api/endpoints/posts/create.js | 40 +++++++++++++-------------------------- 1 file changed, 13 insertions(+), 27 deletions(-) (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/create.js b/src/api/endpoints/posts/create.js index 57e95bd712..2f03ebd8e9 100644 --- a/src/api/endpoints/posts/create.js +++ b/src/api/endpoints/posts/create.js @@ -4,8 +4,9 @@ * Module dependencies */ import * as mongo from 'mongodb'; +import validate from '../../validator'; import parse from '../../../common/text'; -import Post from '../../models/post'; +import { Post, isValidText } from '../../models/post'; import User from '../../models/user'; import Following from '../../models/following'; import DriveFile from '../../models/drive-file'; @@ -15,16 +16,15 @@ import notify from '../../common/notify'; import event from '../../event'; import config from '../../../conf'; -/** - * 最大文字数 - */ -const maxTextLength = 1000; - /** * 添付できるファイルの数 */ const maxMediaCount = 4; +function hasDuplicates(array) { + return (new Set(array)).size !== array.length; +} + /** * Create a post * @@ -37,30 +37,16 @@ module.exports = (params, user, app) => new Promise(async (res, rej) => { // Get 'text' parameter - let text = params.text; - if (text !== undefined && text !== null) { - if (typeof text != 'string') { - return rej('text must be a string'); - } - text = text.trim(); - if (text.length == 0) { - text = null; - } else if (text.length > maxTextLength) { - return rej('too long text'); - } - } else { - text = null; - } + const [text, textErr] = validate(params.text, 'string', false, isValidText); + if (textErr) return rej('invalid text'); // Get 'media_ids' parameter - let medias = params.media_ids; - let files = []; - if (medias !== undefined && medias !== null) { - if (!Array.isArray(medias)) { - return rej('media_ids must be an array'); - } + const [mediaIds, mediaIdsErr] = validate(params.media_ids, 'array', false, x => !hasDuplicates(x)); + if (mediaIdsErr) return rej('invalid media_ids'); - if (medias.length > maxMediaCount) { + let files = []; + if (mediaIds !== null) { + if (mediaIds.length > maxMediaCount) { return rej('too many media'); } -- cgit v1.2.3-freya From fd0ce15b1b08abc72f3b45de90d6a47657440983 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 05:11:37 +0900 Subject: wip --- src/api/endpoints/posts/create.js | 157 ++++++++++++-------------------------- 1 file changed, 50 insertions(+), 107 deletions(-) (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/create.js b/src/api/endpoints/posts/create.js index 2f03ebd8e9..9070dcb413 100644 --- a/src/api/endpoints/posts/create.js +++ b/src/api/endpoints/posts/create.js @@ -3,7 +3,6 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; import validate from '../../validator'; import parse from '../../../common/text'; import { Post, isValidText } from '../../models/post'; @@ -16,11 +15,6 @@ import notify from '../../common/notify'; import event from '../../event'; import config from '../../../conf'; -/** - * 添付できるファイルの数 - */ -const maxMediaCount = 4; - function hasDuplicates(array) { return (new Set(array)).size !== array.length; } @@ -41,37 +35,25 @@ module.exports = (params, user, app) => if (textErr) return rej('invalid text'); // Get 'media_ids' parameter - const [mediaIds, mediaIdsErr] = validate(params.media_ids, 'array', false, x => !hasDuplicates(x)); + const [mediaIds, mediaIdsErr] = validate(params.media_ids, 'array', false, [ + x => !hasDuplicates(x), + x => x.length > 4 ? 'too many media' : true + ]); if (mediaIdsErr) return rej('invalid media_ids'); let files = []; if (mediaIds !== null) { - if (mediaIds.length > maxMediaCount) { - return rej('too many media'); - } - - // Drop duplications - medias = medias.filter((x, i, s) => s.indexOf(x) == i); - // Fetch files // forEach だと途中でエラーなどがあっても return できないので // 敢えて for を使っています。 - for (let i = 0; i < medias.length; i++) { - const media = medias[i]; - - if (typeof media != 'string') { - return rej('media id must be a string'); - } - - // Validate id - if (!mongo.ObjectID.isValid(media)) { - return rej('incorrect media id'); - } + for (let i = 0; i < mediaIds.length; i++) { + const [mediaId, mediaIdErr] = validate(mediaIds[i], 'id', true); + if (mediaIdErr) return rej('invalid media id'); // Fetch file // SELECT _id const entity = await DriveFile.findOne({ - _id: new mongo.ObjectID(media), + _id: mediaId, user_id: user._id }, { _id: true @@ -88,20 +70,14 @@ module.exports = (params, user, app) => } // Get 'repost_id' parameter - let repost = params.repost_id; - if (repost !== undefined && repost !== null) { - if (typeof repost != 'string') { - return rej('repost_id must be a string'); - } - - // Validate id - if (!mongo.ObjectID.isValid(repost)) { - return rej('incorrect repost_id'); - } + const [repostId, repostIdErr] = validate(params.repost_id, 'id'); + if (repostIdErr) return rej('invalid repost_id'); + let repost = null; + if (repostId !== null) { // Fetch repost to post repost = await Post.findOne({ - _id: new mongo.ObjectID(repost) + _id: repostId }); if (repost == null) { @@ -133,96 +109,63 @@ module.exports = (params, user, app) => text === null && files === null) { return rej('二重Repostです(NEED TRANSLATE)'); } - } else { - repost = null; } - // Get 'reply_to_id' parameter - let replyTo = params.reply_to_id; - if (replyTo !== undefined && replyTo !== null) { - if (typeof replyTo != 'string') { - return rej('reply_to_id must be a string'); - } - - // Validate id - if (!mongo.ObjectID.isValid(replyTo)) { - return rej('incorrect reply_to_id'); - } + // Get 'in_reply_to_post_id' parameter + const [inReplyToPostId, inReplyToPostIdErr] = validate(params.reply_to_id, 'id'); + if (inReplyToPostIdErr) return rej('invalid in_reply_to_post_id'); + let inReplyToPost = null; + if (inReplyToPostId !== null) { // Fetch reply - replyTo = await Post.findOne({ - _id: new mongo.ObjectID(replyTo) + inReplyToPost = await Post.findOne({ + _id: inReplyToPostId }); - if (replyTo === null) { - return rej('reply to post is not found'); + if (inReplyToPost === null) { + return rej('in reply to post is not found'); } // 返信対象が引用でないRepostだったらエラー - if (replyTo.repost_id && !replyTo.text && !replyTo.media_ids) { + if (inReplyToPost.repost_id && !inReplyToPost.text && !inReplyToPost.media_ids) { return rej('cannot reply to repost'); } - } else { - replyTo = null; } // Get 'poll' parameter - let poll = params.poll; - if (poll !== undefined && poll !== null) { - // 選択肢が無かったらエラー - if (poll.choices == null) { - return rej('poll choices is required'); - } - - // 選択肢が配列でなかったらエラー - if (!Array.isArray(poll.choices)) { - return rej('poll choices must be an array'); - } - - // 選択肢が空の配列でエラー - if (poll.choices.length == 0) { - return rej('poll choices is required'); - } - - // Validate each choices - const shouldReject = poll.choices.some(choice => { - if (typeof choice !== 'string') return true; - if (choice.trim().length === 0) return true; - if (choice.trim().length > 100) return true; - }); - - if (shouldReject) { - return rej('invalid poll choices'); - } - - // Trim choices - poll.choices = poll.choices.map(choice => choice.trim()); - - // Drop duplications - poll.choices = poll.choices.filter((x, i, s) => s.indexOf(x) == i); - - // 選択肢がひとつならエラー - if (poll.choices.length == 1) { - return rej('poll choices must be ひとつ以上'); - } - - // 選択肢が多すぎてもエラー - if (poll.choices.length > 10) { - return rej('many poll choices'); - } - - // serialize - poll.choices = poll.choices.map((choice, i) => ({ + const [_poll, pollErr] = validate(params.poll, 'object'); + if (pollErr) return rej('invalid poll'); + + let poll = null; + if (_poll !== null) { + const [pollChoices, pollChoicesErr] = validate(params.poll, 'array', false, [ + choices => !hasDuplicates(choices), + choices => { + const shouldReject = choices.some(choice => { + if (typeof choice != 'string') return true; + if (choice.trim().length == 0) return true; + if (choice.trim().length > 50) return true; + }); + return shouldReject ? 'invalid poll choices' : true; + }, + // 選択肢がひとつならエラー + choices => choices.length == 1 ? 'poll choices must be ひとつ以上' : true, + // 選択肢が多すぎてもエラー + choices => choices.length > 10 ? 'many poll choices' : true, + ]); + if (pollChoicesErr) return rej('invalid poll choices'); + + _poll.choices = pollChoices.map((choice, i) => ({ id: i, // IDを付与 - text: choice, + text: choice.trim(), votes: 0 })); - } else { - poll = null; + + poll = _poll; } // テキストが無いかつ添付ファイルが無いかつRepostも無いかつ投票も無かったらエラー - if (text === null && files === null && repost === null && poll === null) { + if (text === null && files === null && repost === null && pollChoices === null) { return rej('text, media_ids, repost_id or poll is required'); } -- cgit v1.2.3-freya From 17c8969fd2ff51096fcde8d0ae272ca67202f55d Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 05:12:59 +0900 Subject: fix --- src/api/endpoints/posts/create.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/create.js b/src/api/endpoints/posts/create.js index 9070dcb413..151938004d 100644 --- a/src/api/endpoints/posts/create.js +++ b/src/api/endpoints/posts/create.js @@ -165,7 +165,7 @@ module.exports = (params, user, app) => } // テキストが無いかつ添付ファイルが無いかつRepostも無いかつ投票も無かったらエラー - if (text === null && files === null && repost === null && pollChoices === null) { + if (text === null && files === null && repost === null && poll === null) { return rej('text, media_ids, repost_id or poll is required'); } -- cgit v1.2.3-freya From b3455bf1cb30beb46859345c482e6585845ca388 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 05:24:20 +0900 Subject: Extract hasDuplicates function --- src/api/endpoints/posts/create.js | 5 +---- src/common/has-duplicates.ts | 1 + 2 files changed, 2 insertions(+), 4 deletions(-) create mode 100644 src/common/has-duplicates.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/create.js b/src/api/endpoints/posts/create.js index 151938004d..92aeb3d08e 100644 --- a/src/api/endpoints/posts/create.js +++ b/src/api/endpoints/posts/create.js @@ -4,6 +4,7 @@ * Module dependencies */ import validate from '../../validator'; +import hasDuplicates from '../../../common/has-duplicates'; import parse from '../../../common/text'; import { Post, isValidText } from '../../models/post'; import User from '../../models/user'; @@ -15,10 +16,6 @@ import notify from '../../common/notify'; import event from '../../event'; import config from '../../../conf'; -function hasDuplicates(array) { - return (new Set(array)).size !== array.length; -} - /** * Create a post * diff --git a/src/common/has-duplicates.ts b/src/common/has-duplicates.ts new file mode 100644 index 0000000000..dd5e6759f1 --- /dev/null +++ b/src/common/has-duplicates.ts @@ -0,0 +1 @@ +export default (array: any[]) => (new Set(array)).size !== array.length; -- cgit v1.2.3-freya From f3f5869f5214085637276b077ece739eac2e5dff Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 05:31:30 +0900 Subject: Add 'set' type --- src/api/endpoints/posts/create.js | 9 +++------ src/api/validator.ts | 12 +++++++++++- 2 files changed, 14 insertions(+), 7 deletions(-) (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/create.js b/src/api/endpoints/posts/create.js index 92aeb3d08e..eadc886c5c 100644 --- a/src/api/endpoints/posts/create.js +++ b/src/api/endpoints/posts/create.js @@ -4,7 +4,6 @@ * Module dependencies */ import validate from '../../validator'; -import hasDuplicates from '../../../common/has-duplicates'; import parse from '../../../common/text'; import { Post, isValidText } from '../../models/post'; import User from '../../models/user'; @@ -32,10 +31,9 @@ module.exports = (params, user, app) => if (textErr) return rej('invalid text'); // Get 'media_ids' parameter - const [mediaIds, mediaIdsErr] = validate(params.media_ids, 'array', false, [ - x => !hasDuplicates(x), + const [mediaIds, mediaIdsErr] = validate(params.media_ids, 'set', false, x => x.length > 4 ? 'too many media' : true - ]); + ); if (mediaIdsErr) return rej('invalid media_ids'); let files = []; @@ -135,8 +133,7 @@ module.exports = (params, user, app) => let poll = null; if (_poll !== null) { - const [pollChoices, pollChoicesErr] = validate(params.poll, 'array', false, [ - choices => !hasDuplicates(choices), + const [pollChoices, pollChoicesErr] = validate(params.poll, 'set', false, [ choices => { const shouldReject = choices.some(choice => { if (typeof choice != 'string') return true; diff --git a/src/api/validator.ts b/src/api/validator.ts index 830786a18d..3c426054e8 100644 --- a/src/api/validator.ts +++ b/src/api/validator.ts @@ -1,6 +1,7 @@ import * as mongo from 'mongodb'; +import hasDuplicates from '../common/has-duplicates'; -type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'object'; +type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'set' | 'object'; type Validator = ((x: T) => boolean | string) | ((x: T) => boolean | string)[]; @@ -9,6 +10,7 @@ function validate(value: any, type: 'string', isRequired?: boolean, validator?: function validate(value: any, type: 'number', isRequired?: boolean, validator?: Validator): [number, string]; function validate(value: any, type: 'boolean', isRequired?: boolean): [boolean, string]; function validate(value: any, type: 'array', isRequired?: boolean, validator?: Validator): [any[], string]; +function validate(value: any, type: 'set', isRequired?: boolean, validator?: Validator>): [Set, string]; function validate(value: any, type: 'object', isRequired?: boolean, validator?: Validator): [Object, string]; function validate(value: any, type: Type, isRequired?: boolean, validator?: Validator): [T, string] { if (value === undefined || value === null) { @@ -50,6 +52,14 @@ function validate(value: any, type: Type, isRequired?: boolean, validator?: V } break; + case 'set': + if (!Array.isArray(value)) { + return [null, 'must-be-an-array']; + } else if (hasDuplicates(value)) { + return [null, 'duplicated-contents']; + } + break; + case 'object': if (typeof value != 'object') { return [null, 'must-be-an-onject']; -- cgit v1.2.3-freya From 168039e68299029b11161b53f90cc103788c0cd3 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 15:25:27 +0900 Subject: :v: --- src/api/endpoints/posts/create.js | 355 ------------------------------------- src/api/endpoints/posts/create.ts | 356 ++++++++++++++++++++++++++++++++++++++ src/api/validator.ts | 4 +- 3 files changed, 358 insertions(+), 357 deletions(-) delete mode 100644 src/api/endpoints/posts/create.js create mode 100644 src/api/endpoints/posts/create.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/create.js b/src/api/endpoints/posts/create.js deleted file mode 100644 index eadc886c5c..0000000000 --- a/src/api/endpoints/posts/create.js +++ /dev/null @@ -1,355 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import validate from '../../validator'; -import parse from '../../../common/text'; -import { Post, isValidText } from '../../models/post'; -import User from '../../models/user'; -import Following from '../../models/following'; -import DriveFile from '../../models/drive-file'; -import serialize from '../../serializers/post'; -import createFile from '../../common/add-file-to-drive'; -import notify from '../../common/notify'; -import event from '../../event'; -import config from '../../../conf'; - -/** - * Create a post - * - * @param {any} params - * @param {any} user - * @param {any} app - * @return {Promise} - */ -module.exports = (params, user, app) => - new Promise(async (res, rej) => -{ - // Get 'text' parameter - const [text, textErr] = validate(params.text, 'string', false, isValidText); - if (textErr) return rej('invalid text'); - - // Get 'media_ids' parameter - const [mediaIds, mediaIdsErr] = validate(params.media_ids, 'set', false, - x => x.length > 4 ? 'too many media' : true - ); - if (mediaIdsErr) return rej('invalid media_ids'); - - let files = []; - if (mediaIds !== null) { - // Fetch files - // forEach だと途中でエラーなどがあっても return できないので - // 敢えて for を使っています。 - for (let i = 0; i < mediaIds.length; i++) { - const [mediaId, mediaIdErr] = validate(mediaIds[i], 'id', true); - if (mediaIdErr) return rej('invalid media id'); - - // Fetch file - // SELECT _id - const entity = await DriveFile.findOne({ - _id: mediaId, - user_id: user._id - }, { - _id: true - }); - - if (entity === null) { - return rej('file not found'); - } else { - files.push(entity); - } - } - } else { - files = null; - } - - // Get 'repost_id' parameter - const [repostId, repostIdErr] = validate(params.repost_id, 'id'); - if (repostIdErr) return rej('invalid repost_id'); - - let repost = null; - if (repostId !== null) { - // Fetch repost to post - repost = await Post.findOne({ - _id: repostId - }); - - if (repost == null) { - return rej('repostee is not found'); - } else if (repost.repost_id && !repost.text && !repost.media_ids) { - return rej('cannot repost to repost'); - } - - // Fetch recently post - const latestPost = await Post.findOne({ - user_id: user._id - }, { - sort: { - _id: -1 - } - }); - - // 直近と同じRepost対象かつ引用じゃなかったらエラー - if (latestPost && - latestPost.repost_id && - latestPost.repost_id.equals(repost._id) && - text === null && files === null) { - return rej('二重Repostです(NEED TRANSLATE)'); - } - - // 直近がRepost対象かつ引用じゃなかったらエラー - if (latestPost && - latestPost._id.equals(repost._id) && - text === null && files === null) { - return rej('二重Repostです(NEED TRANSLATE)'); - } - } - - // Get 'in_reply_to_post_id' parameter - const [inReplyToPostId, inReplyToPostIdErr] = validate(params.reply_to_id, 'id'); - if (inReplyToPostIdErr) return rej('invalid in_reply_to_post_id'); - - let inReplyToPost = null; - if (inReplyToPostId !== null) { - // Fetch reply - inReplyToPost = await Post.findOne({ - _id: inReplyToPostId - }); - - if (inReplyToPost === null) { - return rej('in reply to post is not found'); - } - - // 返信対象が引用でないRepostだったらエラー - if (inReplyToPost.repost_id && !inReplyToPost.text && !inReplyToPost.media_ids) { - return rej('cannot reply to repost'); - } - } - - // Get 'poll' parameter - const [_poll, pollErr] = validate(params.poll, 'object'); - if (pollErr) return rej('invalid poll'); - - let poll = null; - if (_poll !== null) { - const [pollChoices, pollChoicesErr] = validate(params.poll, 'set', false, [ - choices => { - const shouldReject = choices.some(choice => { - if (typeof choice != 'string') return true; - if (choice.trim().length == 0) return true; - if (choice.trim().length > 50) return true; - }); - return shouldReject ? 'invalid poll choices' : true; - }, - // 選択肢がひとつならエラー - choices => choices.length == 1 ? 'poll choices must be ひとつ以上' : true, - // 選択肢が多すぎてもエラー - choices => choices.length > 10 ? 'many poll choices' : true, - ]); - if (pollChoicesErr) return rej('invalid poll choices'); - - _poll.choices = pollChoices.map((choice, i) => ({ - id: i, // IDを付与 - text: choice.trim(), - votes: 0 - })); - - poll = _poll; - } - - // テキストが無いかつ添付ファイルが無いかつRepostも無いかつ投票も無かったらエラー - if (text === null && files === null && repost === null && poll === null) { - return rej('text, media_ids, repost_id or poll is required'); - } - - // 投稿を作成 - const post = await Post.insert({ - created_at: new Date(), - media_ids: files ? files.map(file => file._id) : undefined, - reply_to_id: replyTo ? replyTo._id : undefined, - repost_id: repost ? repost._id : undefined, - poll: poll ? poll : undefined, - text: text, - user_id: user._id, - app_id: app ? app._id : null - }); - - // Serialize - const postObj = await serialize(post); - - // Reponse - res(postObj); - - //-------------------------------- - // Post processes - - let mentions = []; - - function addMention(mentionee, type) { - // Reject if already added - if (mentions.some(x => x.equals(mentionee))) return; - - // Add mention - mentions.push(mentionee); - - // Publish event - if (!user._id.equals(mentionee)) { - event(mentionee, type, postObj); - } - } - - // Publish event to myself's stream - event(user._id, 'post', postObj); - - // Fetch all followers - const followers = await Following - .find({ - followee_id: user._id, - // 削除されたドキュメントは除く - deleted_at: { $exists: false } - }, { - follower_id: true, - _id: false - }); - - // Publish event to followers stream - followers.forEach(following => - event(following.follower_id, 'post', postObj)); - - // Increment my posts count - User.update({ _id: user._id }, { - $inc: { - posts_count: 1 - } - }); - - // If has in reply to post - if (replyTo) { - // Increment replies count - Post.update({ _id: replyTo._id }, { - $inc: { - replies_count: 1 - } - }); - - // 自分自身へのリプライでない限りは通知を作成 - notify(replyTo.user_id, user._id, 'reply', { - post_id: post._id - }); - - // Add mention - addMention(replyTo.user_id, 'reply'); - } - - // If it is repost - if (repost) { - // Notify - const type = text ? 'quote' : 'repost'; - notify(repost.user_id, user._id, type, { - post_id: post._id - }); - - // If it is quote repost - if (text) { - // Add mention - addMention(repost.user_id, 'quote'); - } else { - // Publish event - if (!user._id.equals(repost.user_id)) { - event(repost.user_id, 'repost', postObj); - } - } - - // 今までで同じ投稿をRepostしているか - const existRepost = await Post.findOne({ - user_id: user._id, - repost_id: repost._id, - _id: { - $ne: post._id - } - }); - - if (!existRepost) { - // Update repostee status - Post.update({ _id: repost._id }, { - $inc: { - repost_count: 1 - } - }); - } - } - - // If has text content - if (text) { - // Analyze - const tokens = parse(text); - - // Extract a hashtags - const hashtags = tokens - .filter(t => t.type == 'hashtag') - .map(t => t.hashtag) - // Drop dupulicates - .filter((v, i, s) => s.indexOf(v) == i); - - // ハッシュタグをデータベースに登録 - //registerHashtags(user, hashtags); - - // Extract an '@' mentions - const atMentions = tokens - .filter(t => t.type == 'mention') - .map(m => m.username) - // Drop dupulicates - .filter((v, i, s) => s.indexOf(v) == i); - - // Resolve all mentions - await Promise.all(atMentions.map(async (mention) => { - // Fetch mentioned user - // SELECT _id - const mentionee = await User - .findOne({ - username_lower: mention.toLowerCase() - }, { _id: true }); - - // When mentioned user not found - if (mentionee == null) return; - - // 既に言及されたユーザーに対する返信や引用repostの場合も無視 - if (replyTo && replyTo.user_id.equals(mentionee._id)) return; - if (repost && repost.user_id.equals(mentionee._id)) return; - - // Add mention - addMention(mentionee._id, 'mention'); - - // Create notification - notify(mentionee._id, user._id, 'mention', { - post_id: post._id - }); - - return; - })); - } - - // Register to search database - if (text && config.elasticsearch.enable) { - const es = require('../../../db/elasticsearch'); - - es.index({ - index: 'misskey', - type: 'post', - id: post._id.toString(), - body: { - text: post.text - } - }); - } - - // Append mentions data - if (mentions.length > 0) { - Post.update({ _id: post._id }, { - $set: { - mentions: mentions - } - }); - } -}); diff --git a/src/api/endpoints/posts/create.ts b/src/api/endpoints/posts/create.ts new file mode 100644 index 0000000000..0ecce4e9ad --- /dev/null +++ b/src/api/endpoints/posts/create.ts @@ -0,0 +1,356 @@ +'use strict'; + +/** + * Module dependencies + */ +import validate from '../../validator'; +import parse from '../../../common/text'; +import Post from '../../models/post'; +import { isValidText } from '../../models/post'; +import User from '../../models/user'; +import Following from '../../models/following'; +import DriveFile from '../../models/drive-file'; +import serialize from '../../serializers/post'; +import notify from '../../common/notify'; +import event from '../../event'; +import config from '../../../conf'; + +/** + * Create a post + * + * @param {any} params + * @param {any} user + * @param {any} app + * @return {Promise} + */ +module.exports = (params, user, app) => + new Promise(async (res, rej) => +{ + // Get 'text' parameter + const [text, textErr] = validate(params.text, 'string', false, isValidText); + if (textErr) return rej('invalid text'); + + // Get 'media_ids' parameter + const [mediaIds, mediaIdsErr] = validate(params.media_ids, 'set', false, + x => x.length > 4 ? 'too many media' : true + ); + if (mediaIdsErr) return rej('invalid media_ids'); + + let files = []; + if (mediaIds !== null) { + // Fetch files + // forEach だと途中でエラーなどがあっても return できないので + // 敢えて for を使っています。 + for (let i = 0; i < mediaIds.length; i++) { + const [mediaId, mediaIdErr] = validate(mediaIds[i], 'id', true); + if (mediaIdErr) return rej('invalid media id'); + + // Fetch file + // SELECT _id + const entity = await DriveFile.findOne({ + _id: mediaId, + user_id: user._id + }, { + _id: true + }); + + if (entity === null) { + return rej('file not found'); + } else { + files.push(entity); + } + } + } else { + files = null; + } + + // Get 'repost_id' parameter + const [repostId, repostIdErr] = validate(params.repost_id, 'id'); + if (repostIdErr) return rej('invalid repost_id'); + + let repost = null; + if (repostId !== null) { + // Fetch repost to post + repost = await Post.findOne({ + _id: repostId + }); + + if (repost == null) { + return rej('repostee is not found'); + } else if (repost.repost_id && !repost.text && !repost.media_ids) { + return rej('cannot repost to repost'); + } + + // Fetch recently post + const latestPost = await Post.findOne({ + user_id: user._id + }, { + sort: { + _id: -1 + } + }); + + // 直近と同じRepost対象かつ引用じゃなかったらエラー + if (latestPost && + latestPost.repost_id && + latestPost.repost_id.equals(repost._id) && + text === null && files === null) { + return rej('二重Repostです(NEED TRANSLATE)'); + } + + // 直近がRepost対象かつ引用じゃなかったらエラー + if (latestPost && + latestPost._id.equals(repost._id) && + text === null && files === null) { + return rej('二重Repostです(NEED TRANSLATE)'); + } + } + + // Get 'in_reply_to_post_id' parameter + const [inReplyToPostId, inReplyToPostIdErr] = validate(params.reply_to_id, 'id'); + if (inReplyToPostIdErr) return rej('invalid in_reply_to_post_id'); + + let inReplyToPost = null; + if (inReplyToPostId !== null) { + // Fetch reply + inReplyToPost = await Post.findOne({ + _id: inReplyToPostId + }); + + if (inReplyToPost === null) { + return rej('in reply to post is not found'); + } + + // 返信対象が引用でないRepostだったらエラー + if (inReplyToPost.repost_id && !inReplyToPost.text && !inReplyToPost.media_ids) { + return rej('cannot reply to repost'); + } + } + + // Get 'poll' parameter + const [_poll, pollErr] = validate(params.poll, 'object'); + if (pollErr) return rej('invalid poll'); + + let poll = null; + if (_poll !== null) { + const [pollChoices, pollChoicesErr] = validate(params.poll, 'set', false, [ + choices => { + const shouldReject = choices.some(choice => { + if (typeof choice != 'string') return true; + if (choice.trim().length == 0) return true; + if (choice.trim().length > 50) return true; + return false; + }); + return shouldReject ? 'invalid poll choices' : true; + }, + // 選択肢がひとつならエラー + choices => choices.length == 1 ? 'poll choices must be ひとつ以上' : true, + // 選択肢が多すぎてもエラー + choices => choices.length > 10 ? 'many poll choices' : true, + ]); + if (pollChoicesErr) return rej('invalid poll choices'); + + _poll.choices = pollChoices.map((choice, i) => ({ + id: i, // IDを付与 + text: choice.trim(), + votes: 0 + })); + + poll = _poll; + } + + // テキストが無いかつ添付ファイルが無いかつRepostも無いかつ投票も無かったらエラー + if (text === null && files === null && repost === null && poll === null) { + return rej('text, media_ids, repost_id or poll is required'); + } + + // 投稿を作成 + const post = await Post.insert({ + created_at: new Date(), + media_ids: files ? files.map(file => file._id) : undefined, + reply_to_id: inReplyToPost ? inReplyToPost._id : undefined, + repost_id: repost ? repost._id : undefined, + poll: poll ? poll : undefined, + text: text, + user_id: user._id, + app_id: app ? app._id : null + }); + + // Serialize + const postObj = await serialize(post); + + // Reponse + res(postObj); + + //-------------------------------- + // Post processes + + let mentions = []; + + function addMention(mentionee, type) { + // Reject if already added + if (mentions.some(x => x.equals(mentionee))) return; + + // Add mention + mentions.push(mentionee); + + // Publish event + if (!user._id.equals(mentionee)) { + event(mentionee, type, postObj); + } + } + + // Publish event to myself's stream + event(user._id, 'post', postObj); + + // Fetch all followers + const followers = await Following + .find({ + followee_id: user._id, + // 削除されたドキュメントは除く + deleted_at: { $exists: false } + }, { + follower_id: true, + _id: false + }); + + // Publish event to followers stream + followers.forEach(following => + event(following.follower_id, 'post', postObj)); + + // Increment my posts count + User.update({ _id: user._id }, { + $inc: { + posts_count: 1 + } + }); + + // If has in reply to post + if (inReplyToPost) { + // Increment replies count + Post.update({ _id: inReplyToPost._id }, { + $inc: { + replies_count: 1 + } + }); + + // 自分自身へのリプライでない限りは通知を作成 + notify(inReplyToPost.user_id, user._id, 'reply', { + post_id: post._id + }); + + // Add mention + addMention(inReplyToPost.user_id, 'reply'); + } + + // If it is repost + if (repost) { + // Notify + const type = text ? 'quote' : 'repost'; + notify(repost.user_id, user._id, type, { + post_id: post._id + }); + + // If it is quote repost + if (text) { + // Add mention + addMention(repost.user_id, 'quote'); + } else { + // Publish event + if (!user._id.equals(repost.user_id)) { + event(repost.user_id, 'repost', postObj); + } + } + + // 今までで同じ投稿をRepostしているか + const existRepost = await Post.findOne({ + user_id: user._id, + repost_id: repost._id, + _id: { + $ne: post._id + } + }); + + if (!existRepost) { + // Update repostee status + Post.update({ _id: repost._id }, { + $inc: { + repost_count: 1 + } + }); + } + } + + // If has text content + if (text) { + // Analyze + const tokens = parse(text); +/* + // Extract a hashtags + const hashtags = tokens + .filter(t => t.type == 'hashtag') + .map(t => t.hashtag) + // Drop dupulicates + .filter((v, i, s) => s.indexOf(v) == i); + + // ハッシュタグをデータベースに登録 + registerHashtags(user, hashtags); +*/ + // Extract an '@' mentions + const atMentions = tokens + .filter(t => t.type == 'mention') + .map(m => m.username) + // Drop dupulicates + .filter((v, i, s) => s.indexOf(v) == i); + + // Resolve all mentions + await Promise.all(atMentions.map(async (mention) => { + // Fetch mentioned user + // SELECT _id + const mentionee = await User + .findOne({ + username_lower: mention.toLowerCase() + }, { _id: true }); + + // When mentioned user not found + if (mentionee == null) return; + + // 既に言及されたユーザーに対する返信や引用repostの場合も無視 + if (inReplyToPost && inReplyToPost.user_id.equals(mentionee._id)) return; + if (repost && repost.user_id.equals(mentionee._id)) return; + + // Add mention + addMention(mentionee._id, 'mention'); + + // Create notification + notify(mentionee._id, user._id, 'mention', { + post_id: post._id + }); + + return; + })); + } + + // Register to search database + if (text && config.elasticsearch.enable) { + const es = require('../../../db/elasticsearch'); + + es.index({ + index: 'misskey', + type: 'post', + id: post._id.toString(), + body: { + text: post.text + } + }); + } + + // Append mentions data + if (mentions.length > 0) { + Post.update({ _id: post._id }, { + $set: { + mentions: mentions + } + }); + } +}); diff --git a/src/api/validator.ts b/src/api/validator.ts index bc50da3a37..3f1678e35d 100644 --- a/src/api/validator.ts +++ b/src/api/validator.ts @@ -10,8 +10,8 @@ function validate(value: any, type: 'string', isRequired?: boolean, validator?: function validate(value: any, type: 'number', isRequired?: boolean, validator?: Validator): [number, string]; function validate(value: any, type: 'boolean', isRequired?: boolean): [boolean, string]; function validate(value: any, type: 'array', isRequired?: boolean, validator?: Validator): [any[], string]; -function validate(value: any, type: 'set', isRequired?: boolean, validator?: Validator>): [Set, string]; -function validate(value: any, type: 'object', isRequired?: boolean, validator?: Validator): [Object, string]; +function validate(value: any, type: 'set', isRequired?: boolean, validator?: Validator): [any[], string]; +function validate(value: any, type: 'object', isRequired?: boolean, validator?: Validator): [any, string]; function validate(value: any, type: Type, isRequired?: boolean, validator?: Validator): [T, string] { if (value === undefined || value === null) { if (isRequired) { -- cgit v1.2.3-freya From f3d5c07ada08a089969176cdb7b7bfc3f0132fda Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 17:08:09 +0900 Subject: wip --- src/api/endpoints/posts/context.js | 83 -------------------------------------- src/api/endpoints/posts/context.ts | 81 +++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 83 deletions(-) delete mode 100644 src/api/endpoints/posts/context.js create mode 100644 src/api/endpoints/posts/context.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/context.js b/src/api/endpoints/posts/context.js deleted file mode 100644 index b843044642..0000000000 --- a/src/api/endpoints/posts/context.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Post from '../../models/post'; -import serialize from '../../serializers/post'; - -/** - * Show a context of a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => -{ - // Get 'post_id' parameter - const postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // 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)))); -}); 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} + */ +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)))); +}); -- cgit v1.2.3-freya From 789deecfe96a32adfd98ebede749380f81520402 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 21:54:46 +0900 Subject: wip --- src/api/endpoints/posts/create.ts | 18 +- src/api/it.ts | 518 ++++++++++++++++++++++++++++++++++++++ src/api/validator.ts | 87 ------- src/api/validator2.ts | 385 ---------------------------- 4 files changed, 526 insertions(+), 482 deletions(-) create mode 100644 src/api/it.ts delete mode 100644 src/api/validator.ts delete mode 100644 src/api/validator2.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/create.ts b/src/api/endpoints/posts/create.ts index 0ecce4e9ad..f707c81b1d 100644 --- a/src/api/endpoints/posts/create.ts +++ b/src/api/endpoints/posts/create.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import validate from '../../validator'; +import it from '../../it'; import parse from '../../../common/text'; import Post from '../../models/post'; import { isValidText } from '../../models/post'; @@ -27,13 +27,11 @@ module.exports = (params, user, app) => new Promise(async (res, rej) => { // Get 'text' parameter - const [text, textErr] = validate(params.text, 'string', false, isValidText); + const [text, textErr] = it(params.text).must.be.a.string().validate(isValidText).get(); if (textErr) return rej('invalid text'); // Get 'media_ids' parameter - const [mediaIds, mediaIdsErr] = validate(params.media_ids, 'set', false, - x => x.length > 4 ? 'too many media' : true - ); + const [mediaIds, mediaIdsErr] = it(params.media_ids).must.be.an.array().unique().range(1, 4).get(); if (mediaIdsErr) return rej('invalid media_ids'); let files = []; @@ -42,7 +40,7 @@ module.exports = (params, user, app) => // forEach だと途中でエラーなどがあっても return できないので // 敢えて for を使っています。 for (let i = 0; i < mediaIds.length; i++) { - const [mediaId, mediaIdErr] = validate(mediaIds[i], 'id', true); + const [mediaId, mediaIdErr] = it(mediaIds[i]).must.be.an.id().required().get(); if (mediaIdErr) return rej('invalid media id'); // Fetch file @@ -65,7 +63,7 @@ module.exports = (params, user, app) => } // Get 'repost_id' parameter - const [repostId, repostIdErr] = validate(params.repost_id, 'id'); + const [repostId, repostIdErr] = it(params.repost_id).must.be.an.id().get(); if (repostIdErr) return rej('invalid repost_id'); let repost = null; @@ -107,7 +105,7 @@ module.exports = (params, user, app) => } // Get 'in_reply_to_post_id' parameter - const [inReplyToPostId, inReplyToPostIdErr] = validate(params.reply_to_id, 'id'); + const [inReplyToPostId, inReplyToPostIdErr] = it(params.reply_to_id, 'id'); if (inReplyToPostIdErr) return rej('invalid in_reply_to_post_id'); let inReplyToPost = null; @@ -128,12 +126,12 @@ module.exports = (params, user, app) => } // Get 'poll' parameter - const [_poll, pollErr] = validate(params.poll, 'object'); + const [_poll, pollErr] = it(params.poll, 'object'); if (pollErr) return rej('invalid poll'); let poll = null; if (_poll !== null) { - const [pollChoices, pollChoicesErr] = validate(params.poll, 'set', false, [ + const [pollChoices, pollChoicesErr] = it(params.poll, 'set', false, [ choices => { const shouldReject = choices.some(choice => { if (typeof choice != 'string') return true; diff --git a/src/api/it.ts b/src/api/it.ts new file mode 100644 index 0000000000..1aff99c9e7 --- /dev/null +++ b/src/api/it.ts @@ -0,0 +1,518 @@ +import * as mongo from 'mongodb'; +import hasDuplicates from '../common/has-duplicates'; + +type Validator = (value: T) => boolean | Error; +type Modifier = (value: T) => T; + +interface Factory { + get: () => [any, Error]; + + required: () => Factory; + + validate: (validator: Validator) => Factory; + + modify: (modifier: Modifier) => Factory; +} + +class FactoryCore implements Factory { + value: any; + error: Error; + + constructor() { + this.value = null; + this.error = null; + } + + /** + * このインスタンスの値が undefined または null の場合エラーにします + */ + required() { + if (this.error === null && this.value === null) { + this.error = new Error('required'); + } + return this; + } + + /** + * このインスタンスの値およびエラーを取得します + */ + get(): [any, Error] { + return [this.value, this.error]; + } + + /** + * このインスタンスの値に対して妥当性を検証します + * バリデータが false またはエラーを返した場合エラーにします + * @param validator バリデータ + */ + validate(validator: Validator) { + if (this.error || this.value === null) return this; + const result = validator(this.value); + if (result === false) { + this.error = new Error('invalid-format'); + } else if (result instanceof Error) { + this.error = result; + } + return this; + } + + modify(modifier: Modifier) { + if (this.error || this.value === null) return this; + try { + this.value = modifier(this.value); + } catch (e) { + this.error = e; + } + return this; + } +} + +class BooleanFactory extends FactoryCore { + value: boolean; + error: Error; + + constructor(value) { + super(); + if (value === undefined || value === null) { + this.value = null; + } else if (typeof value != 'boolean') { + this.error = new Error('must-be-a-boolean'); + } else { + this.value = value; + } + } + + /** + * このインスタンスの値が undefined または null の場合エラーにします + */ + required() { + return super.required(); + } + + /** + * このインスタンスの値およびエラーを取得します + */ + get(): [boolean, Error] { + return super.get(); + } + + /** + * このインスタンスの値に対して妥当性を検証します + * バリデータが false またはエラーを返した場合エラーにします + * @param validator バリデータ + */ + validate(validator: Validator) { + return super.validate(validator); + } + + modify(modifier: Modifier) { + return super.modify(modifier); + } +} + +class NumberFactory extends FactoryCore { + value: number; + error: Error; + + constructor(value) { + super(); + if (value === undefined || value === null) { + this.value = null; + } else if (!Number.isFinite(value)) { + this.error = new Error('must-be-a-number'); + } else { + this.value = value; + } + } + + /** + * 値が指定された範囲内にない場合エラーにします + * @param min 下限 + * @param max 上限 + */ + range(min: number, max: number) { + if (this.error || this.value === null) return this; + if (this.value < min || this.value > max) { + this.error = new Error('invalid-range'); + } + return this; + } + + /** + * このインスタンスの値が undefined または null の場合エラーにします + */ + required() { + return super.required(); + } + + /** + * このインスタンスの値およびエラーを取得します + */ + get(): [number, Error] { + return super.get(); + } + + /** + * このインスタンスの値に対して妥当性を検証します + * バリデータが false またはエラーを返した場合エラーにします + * @param validator バリデータ + */ + validate(validator: Validator) { + return super.validate(validator); + } + + modify(modifier: Modifier) { + return super.modify(modifier); + } +} + +class StringFactory extends FactoryCore { + value: string; + error: Error; + + constructor(value) { + super(); + if (value === undefined || value === null) { + this.value = null; + } else if (typeof value != 'string') { + this.error = new Error('must-be-a-string'); + } else { + this.value = value; + } + } + + /** + * 文字数が指定された範囲内にない場合エラーにします + * @param min 下限 + * @param max 上限 + */ + range(min: number, max: number) { + if (this.error || this.value === null) return this; + if (this.value.length < min || this.value.length > max) { + this.error = new Error('invalid-range'); + } + return this; + } + + trim() { + if (this.error || this.value === null) return this; + this.value = this.value.trim(); + return this; + } + + /** + * このインスタンスの値が undefined または null の場合エラーにします + */ + required() { + return super.required(); + } + + /** + * このインスタンスの値およびエラーを取得します + */ + get(): [string, Error] { + return super.get(); + } + + /** + * このインスタンスの値に対して妥当性を検証します + * バリデータが false またはエラーを返した場合エラーにします + * @param validator バリデータ + */ + validate(validator: Validator) { + return super.validate(validator); + } + + modify(modifier: Modifier) { + return super.modify(modifier); + } +} + +class ArrayFactory extends FactoryCore { + value: any[]; + error: Error; + + constructor(value) { + super(); + if (value === undefined || value === null) { + this.value = null; + } else if (!Array.isArray(value)) { + this.error = new Error('must-be-an-array'); + } else { + this.value = value; + } + } + + /** + * 配列の値がユニークでない場合(=重複した項目がある場合)エラーにします + */ + unique() { + if (this.error || this.value === null) return this; + if (hasDuplicates(this.value)) { + this.error = new Error('must-be-unique'); + } + return this; + } + + /** + * 配列の長さが指定された範囲内にない場合エラーにします + * @param min 下限 + * @param max 上限 + */ + range(min: number, max: number) { + if (this.error || this.value === null) return this; + if (this.value.length < min || this.value.length > max) { + this.error = new Error('invalid-range'); + } + return this; + } + + /** + * このインスタンスの値が undefined または null の場合エラーにします + */ + required() { + return super.required(); + } + + /** + * このインスタンスの値およびエラーを取得します + */ + get(): [any[], Error] { + return super.get(); + } + + /** + * このインスタンスの値に対して妥当性を検証します + * バリデータが false またはエラーを返した場合エラーにします + * @param validator バリデータ + */ + validate(validator: Validator) { + return super.validate(validator); + } + + modify(modifier: Modifier) { + return super.modify(modifier); + } +} + +class IdFactory extends FactoryCore { + value: mongo.ObjectID; + error: Error; + + constructor(value) { + super(); + if (value === undefined || value === null) { + this.value = null; + } else if (typeof value != 'string' || !mongo.ObjectID.isValid(value)) { + this.error = new Error('must-be-an-id'); + } else { + this.value = new mongo.ObjectID(value); + } + } + + /** + * このインスタンスの値が undefined または null の場合エラーにします + */ + required() { + return super.required(); + } + + /** + * このインスタンスの値およびエラーを取得します + */ + get(): [any[], Error] { + return super.get(); + } + + /** + * このインスタンスの値に対して妥当性を検証します + * バリデータが false またはエラーを返した場合エラーにします + * @param validator バリデータ + */ + validate(validator: Validator) { + return super.validate(validator); + } + + modify(modifier: Modifier) { + return super.modify(modifier); + } +} + +class ObjectFactory extends FactoryCore { + value: any; + error: Error; + + constructor(value) { + super(); + if (value === undefined || value === null) { + this.value = null; + } else if (typeof value != 'object') { + this.error = new Error('must-be-an-object'); + } else { + this.value = value; + } + } + + /** + * このインスタンスの値が undefined または null の場合エラーにします + */ + required() { + return super.required(); + } + + /** + * このインスタンスの値およびエラーを取得します + */ + get(): [any, Error] { + return super.get(); + } + + /** + * このインスタンスの値に対して妥当性を検証します + * バリデータが false またはエラーを返した場合エラーにします + * @param validator バリデータ + */ + validate(validator: Validator) { + return super.validate(validator); + } + + modify(modifier: Modifier) { + return super.modify(modifier); + } +} + +type MustBe = { + must: { + be: { + a: { + string: () => StringFactory; + number: () => NumberFactory; + boolean: () => BooleanFactory; + }; + an: { + id: () => IdFactory; + array: () => ArrayFactory; + object: () => ObjectFactory; + }; + }; + }; +}; + +const mustBe = (value: any) => ({ + must: { + be: { + a: { + string: () => new StringFactory(value), + number: () => new NumberFactory(value), + boolean: () => new BooleanFactory(value) + }, + an: { + id: () => new IdFactory(value), + array: () => new ArrayFactory(value), + object: () => new ObjectFactory(value) + } + } + } +}); + +type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'set' | 'object'; +type Pipe = (x: T) => T | boolean | Error; + +function validate(value: any, type: 'id', isRequired?: boolean, pipe?: Pipe | Pipe[]): [mongo.ObjectID, Error]; +function validate(value: any, type: 'string', isRequired?: boolean, pipe?: Pipe | Pipe[]): [string, Error]; +function validate(value: any, type: 'number', isRequired?: boolean, pipe?: Pipe | Pipe[]): [number, Error]; +function validate(value: any, type: 'boolean', isRequired?: boolean): [boolean, Error]; +function validate(value: any, type: 'array', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any[], Error]; +function validate(value: any, type: 'set', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any[], Error]; +function validate(value: any, type: 'object', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any, Error]; +function validate(value: any, type: Type, isRequired?: boolean, pipe?: Pipe | Pipe[]): [any, Error] { + if (value === undefined || value === null) { + if (isRequired) { + return [null, new Error('is-required')] + } else { + return [null, null] + } + } + + switch (type) { + case 'id': + if (typeof value != 'string' || !mongo.ObjectID.isValid(value)) { + return [null, new Error('incorrect-id')]; + } + break; + + case 'string': + if (typeof value != 'string') { + return [null, new Error('must-be-a-string')]; + } + break; + + case 'number': + if (!Number.isFinite(value)) { + return [null, new Error('must-be-a-number')]; + } + break; + + case 'boolean': + if (typeof value != 'boolean') { + return [null, new Error('must-be-a-boolean')]; + } + break; + + case 'array': + if (!Array.isArray(value)) { + return [null, new Error('must-be-an-array')]; + } + break; + + case 'set': + if (!Array.isArray(value)) { + return [null, new Error('must-be-an-array')]; + } else if (hasDuplicates(value)) { + return [null, new Error('duplicated-contents')]; + } + break; + + case 'object': + if (typeof value != 'object') { + return [null, new Error('must-be-an-object')]; + } + break; + } + + if (type == 'id') value = new mongo.ObjectID(value); + + if (pipe) { + const pipes = Array.isArray(pipe) ? pipe : [pipe]; + for (let i = 0; i < pipes.length; i++) { + const result = pipes[i](value); + if (result === false) { + return [null, new Error('invalid-format')]; + } else if (result instanceof Error) { + return [null, result]; + } else if (result !== true) { + value = result; + } + } + } + + return [value, null]; +} + +function it(value: any): MustBe; +function it(value: any, type: 'id', isRequired?: boolean, pipe?: Pipe | Pipe[]): [mongo.ObjectID, Error]; +function it(value: any, type: 'string', isRequired?: boolean, pipe?: Pipe | Pipe[]): [string, Error]; +function it(value: any, type: 'number', isRequired?: boolean, pipe?: Pipe | Pipe[]): [number, Error]; +function it(value: any, type: 'boolean', isRequired?: boolean): [boolean, Error]; +function it(value: any, type: 'array', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any[], Error]; +function it(value: any, type: 'set', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any[], Error]; +function it(value: any, type: 'object', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any, Error]; +function it(value: any, type?: any, isRequired?: boolean, pipe?: Pipe | Pipe[]): any { + if (typeof type === 'undefined') { + return mustBe(value); + } else { + return validate(value, type, isRequired, pipe); + } +} + +export default it; diff --git a/src/api/validator.ts b/src/api/validator.ts deleted file mode 100644 index 3f1678e35d..0000000000 --- a/src/api/validator.ts +++ /dev/null @@ -1,87 +0,0 @@ -import * as mongo from 'mongodb'; -import hasDuplicates from '../common/has-duplicates'; - -type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'set' | 'object'; - -type Validator = ((x: T) => boolean | string) | ((x: T) => boolean | string)[]; - -function validate(value: any, type: 'id', isRequired?: boolean): [mongo.ObjectID, string]; -function validate(value: any, type: 'string', isRequired?: boolean, validator?: Validator): [string, string]; -function validate(value: any, type: 'number', isRequired?: boolean, validator?: Validator): [number, string]; -function validate(value: any, type: 'boolean', isRequired?: boolean): [boolean, string]; -function validate(value: any, type: 'array', isRequired?: boolean, validator?: Validator): [any[], string]; -function validate(value: any, type: 'set', isRequired?: boolean, validator?: Validator): [any[], string]; -function validate(value: any, type: 'object', isRequired?: boolean, validator?: Validator): [any, string]; -function validate(value: any, type: Type, isRequired?: boolean, validator?: Validator): [T, string] { - if (value === undefined || value === null) { - if (isRequired) { - return [null, 'is-required'] - } else { - return [null, null] - } - } - - switch (type) { - case 'id': - if (typeof value != 'string' || !mongo.ObjectID.isValid(value)) { - return [null, 'incorrect-id']; - } - break; - - case 'string': - if (typeof value != 'string') { - return [null, 'must-be-a-string']; - } - break; - - case 'number': - if (!Number.isFinite(value)) { - return [null, 'must-be-a-number']; - } - break; - - case 'boolean': - if (typeof value != 'boolean') { - return [null, 'must-be-a-boolean']; - } - break; - - case 'array': - if (!Array.isArray(value)) { - return [null, 'must-be-an-array']; - } - break; - - case 'set': - if (!Array.isArray(value)) { - return [null, 'must-be-an-array']; - } else if (hasDuplicates(value)) { - return [null, 'duplicated-contents']; - } - break; - - case 'object': - if (typeof value != 'object') { - return [null, 'must-be-an-object']; - } - break; - } - - if (type == 'id') value = new mongo.ObjectID(value); - - if (validator) { - const validators = Array.isArray(validator) ? validator : [validator]; - for (let i = 0; i < validators.length; i++) { - const result = validators[i](value); - if (result === false) { - return [null, 'invalid-format']; - } else if (typeof result == 'string') { - return [null, result]; - } - } - } - - return [value, null]; -} - -export default validate; diff --git a/src/api/validator2.ts b/src/api/validator2.ts deleted file mode 100644 index 04dff59aac..0000000000 --- a/src/api/validator2.ts +++ /dev/null @@ -1,385 +0,0 @@ -import * as mongo from 'mongodb'; -import hasDuplicates from '../common/has-duplicates'; - -type Validator = (value: T) => boolean | string; -type Modifier = (value: T) => T; - -interface Fuctory { - get: () => [any, string]; - - required: () => Fuctory; - - validate: (validator: Validator) => Fuctory; - - modify: (modifier: Modifier) => Fuctory; -} - -class FuctoryCore implements Fuctory { - value: any; - error: string; - - constructor() { - this.value = null; - this.error = null; - } - - /** - * この値が undefined または null の場合エラーにします - */ - required() { - if (this.error === null && this.value === null) { - this.error = 'required'; - } - return this; - } - - /** - * このインスタンスの値およびエラーを取得します - */ - get(): [any, string] { - return [this.value, this.error]; - } - - /** - * このインスタンスの値に対して妥当性を検証します - * バリデータが false または(エラーを表す)文字列を返した場合エラーにします - * @param validator バリデータ - */ - validate(validator: Validator) { - if (this.error || this.value === null) return this; - const result = validator(this.value); - if (result === false) { - this.error = 'invalid-format'; - } else if (typeof result == 'string') { - this.error = result; - } - return this; - } - - modify(modifier: Modifier) { - if (this.error || this.value === null) return this; - try { - this.value = modifier(this.value); - } catch (e) { - this.error = e; - } - return this; - } -} - -class BooleanFuctory extends FuctoryCore { - value: boolean; - error: string; - - constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (typeof value != 'boolean') { - this.error = 'must-be-a-boolean'; - } else { - this.value = value; - } - } - - required() { - return super.required(); - } - - /** - * このインスタンスの値およびエラーを取得します - */ - get(): [boolean, string] { - return super.get(); - } - - /** - * このインスタンスの値に対して妥当性を検証します - * バリデータが false または(エラーを表す)文字列を返した場合エラーにします - * @param validator バリデータ - */ - validate(validator: Validator) { - return super.validate(validator); - } - - modify(modifier: Modifier) { - return super.modify(modifier); - } -} - -class NumberFuctory extends FuctoryCore { - value: number; - error: string; - - constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (!Number.isFinite(value)) { - this.error = 'must-be-a-number'; - } else { - this.value = value; - } - } - - /** - * 値が指定された範囲内にない場合エラーにします - * @param min 下限 - * @param max 上限 - */ - range(min: number, max: number) { - if (this.error || this.value === null) return this; - if (this.value < min || this.value > max) { - this.error = 'invalid-range'; - } - return this; - } - - required() { - return super.required(); - } - - /** - * このインスタンスの値およびエラーを取得します - */ - get(): [number, string] { - return super.get(); - } - - /** - * このインスタンスの値に対して妥当性を検証します - * バリデータが false または(エラーを表す)文字列を返した場合エラーにします - * @param validator バリデータ - */ - validate(validator: Validator) { - return super.validate(validator); - } - - modify(modifier: Modifier) { - return super.modify(modifier); - } -} - -class StringFuctory extends FuctoryCore { - value: string; - error: string; - - constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (typeof value != 'string') { - this.error = 'must-be-a-string'; - } else { - this.value = value; - } - } - - /** - * 文字数が指定された範囲内にない場合エラーにします - * @param min 下限 - * @param max 上限 - */ - range(min: number, max: number) { - if (this.error || this.value === null) return this; - if (this.value.length < min || this.value.length > max) { - this.error = 'invalid-range'; - } - return this; - } - - trim() { - if (this.error || this.value === null) return this; - this.value = this.value.trim(); - return this; - } - - required() { - return super.required(); - } - - /** - * このインスタンスの値およびエラーを取得します - */ - get(): [string, string] { - return super.get(); - } - - /** - * このインスタンスの値に対して妥当性を検証します - * バリデータが false または(エラーを表す)文字列を返した場合エラーにします - * @param validator バリデータ - */ - validate(validator: Validator) { - return super.validate(validator); - } - - modify(modifier: Modifier) { - return super.modify(modifier); - } -} - -class ArrayFuctory extends FuctoryCore { - value: any[]; - error: string; - - constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (!Array.isArray(value)) { - this.error = 'must-be-an-array'; - } else { - this.value = value; - } - } - - /** - * 配列の値がユニークでない場合(=重複した項目がある場合)エラーにします - */ - unique() { - if (this.error || this.value === null) return this; - if (hasDuplicates(this.value)) { - this.error = 'must-be-unique'; - } - return this; - } - - /** - * 配列の長さが指定された範囲内にない場合エラーにします - * @param min 下限 - * @param max 上限 - */ - range(min: number, max: number) { - if (this.error || this.value === null) return this; - if (this.value.length < min || this.value.length > max) { - this.error = 'invalid-range'; - } - return this; - } - - required() { - return super.required(); - } - - /** - * このインスタンスの値およびエラーを取得します - */ - get(): [any[], string] { - return super.get(); - } - - /** - * このインスタンスの値に対して妥当性を検証します - * バリデータが false または(エラーを表す)文字列を返した場合エラーにします - * @param validator バリデータ - */ - validate(validator: Validator) { - return super.validate(validator); - } - - modify(modifier: Modifier) { - return super.modify(modifier); - } -} - -class IdFuctory extends FuctoryCore { - value: mongo.ObjectID; - error: string; - - constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (typeof value != 'string' || !mongo.ObjectID.isValid(value)) { - this.error = 'must-be-an-id'; - } else { - this.value = new mongo.ObjectID(value); - } - } - - required() { - return super.required(); - } - - /** - * このインスタンスの値およびエラーを取得します - */ - get(): [any[], string] { - return super.get(); - } - - /** - * このインスタンスの値に対して妥当性を検証します - * バリデータが false または(エラーを表す)文字列を返した場合エラーにします - * @param validator バリデータ - */ - validate(validator: Validator) { - return super.validate(validator); - } - - modify(modifier: Modifier) { - return super.modify(modifier); - } -} - -class ObjectFuctory extends FuctoryCore { - value: any; - error: string; - - constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (typeof value != 'object') { - this.error = 'must-be-an-object'; - } else { - this.value = value; - } - } - - required() { - return super.required(); - } - - /** - * このインスタンスの値およびエラーを取得します - */ - get(): [any, string] { - return super.get(); - } - - /** - * このインスタンスの値に対して妥当性を検証します - * バリデータが false または(エラーを表す)文字列を返した場合エラーにします - * @param validator バリデータ - */ - validate(validator: Validator) { - return super.validate(validator); - } - - modify(modifier: Modifier) { - return super.modify(modifier); - } -} - -const it = (value: any) => ({ - must: { - be: { - a: { - string: () => new StringFuctory(value), - number: () => new NumberFuctory(value), - boolean: () => new BooleanFuctory(value) - }, - an: { - id: () => new IdFuctory(value), - array: () => new ArrayFuctory(value), - object: () => new ObjectFuctory(value) - } - } - } -}); - -export default it; - -const [n, e] = it(42).must.be.a.number().required().range(10, 70).validate(x => x != 21).get(); -- cgit v1.2.3-freya From 2fee8fbba36376651161249964e1a3eca0f3d573 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 02:10:27 +0900 Subject: wip --- src/api/endpoints/posts/create.ts | 8 +- src/api/it.ts | 203 +++++++++++--------------------------- 2 files changed, 64 insertions(+), 147 deletions(-) (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/create.ts b/src/api/endpoints/posts/create.ts index f707c81b1d..5ce852280a 100644 --- a/src/api/endpoints/posts/create.ts +++ b/src/api/endpoints/posts/create.ts @@ -27,11 +27,11 @@ module.exports = (params, user, app) => new Promise(async (res, rej) => { // Get 'text' parameter - const [text, textErr] = it(params.text).must.be.a.string().validate(isValidText).get(); + const [text, textErr] = it(params.text).must.be.a.string().validate(isValidText).qed(); if (textErr) return rej('invalid text'); // Get 'media_ids' parameter - const [mediaIds, mediaIdsErr] = it(params.media_ids).must.be.an.array().unique().range(1, 4).get(); + const [mediaIds, mediaIdsErr] = it(params.media_ids).must.be.an.array().unique().range(1, 4).qed(); if (mediaIdsErr) return rej('invalid media_ids'); let files = []; @@ -40,7 +40,7 @@ module.exports = (params, user, app) => // forEach だと途中でエラーなどがあっても return できないので // 敢えて for を使っています。 for (let i = 0; i < mediaIds.length; i++) { - const [mediaId, mediaIdErr] = it(mediaIds[i]).must.be.an.id().required().get(); + const [mediaId, mediaIdErr] = it(mediaIds[i]).must.be.an.id().required().qed(); if (mediaIdErr) return rej('invalid media id'); // Fetch file @@ -63,7 +63,7 @@ module.exports = (params, user, app) => } // Get 'repost_id' parameter - const [repostId, repostIdErr] = it(params.repost_id).must.be.an.id().get(); + const [repostId, repostIdErr] = it(params.repost_id).must.be.an.id().qed(); if (repostIdErr) return rej('invalid repost_id'); let repost = null; diff --git a/src/api/it.ts b/src/api/it.ts index 1aff99c9e7..6e8aefdf2d 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -2,16 +2,16 @@ import * as mongo from 'mongodb'; import hasDuplicates from '../common/has-duplicates'; type Validator = (value: T) => boolean | Error; -type Modifier = (value: T) => T; interface Factory { - get: () => [any, Error]; + /** + * qedはQ.E.D.でもあり'QueryENd'の略でもある + */ + qed: () => [any, Error]; required: () => Factory; validate: (validator: Validator) => Factory; - - modify: (modifier: Modifier) => Factory; } class FactoryCore implements Factory { @@ -36,7 +36,7 @@ class FactoryCore implements Factory { /** * このインスタンスの値およびエラーを取得します */ - get(): [any, Error] { + qed(): [any, Error] { return [this.value, this.error]; } @@ -55,16 +55,6 @@ class FactoryCore implements Factory { } return this; } - - modify(modifier: Modifier) { - if (this.error || this.value === null) return this; - try { - this.value = modifier(this.value); - } catch (e) { - this.error = e; - } - return this; - } } class BooleanFactory extends FactoryCore { @@ -92,8 +82,8 @@ class BooleanFactory extends FactoryCore { /** * このインスタンスの値およびエラーを取得します */ - get(): [boolean, Error] { - return super.get(); + qed(): [boolean, Error] { + return super.qed(); } /** @@ -104,10 +94,6 @@ class BooleanFactory extends FactoryCore { validate(validator: Validator) { return super.validate(validator); } - - modify(modifier: Modifier) { - return super.modify(modifier); - } } class NumberFactory extends FactoryCore { @@ -148,8 +134,8 @@ class NumberFactory extends FactoryCore { /** * このインスタンスの値およびエラーを取得します */ - get(): [number, Error] { - return super.get(); + qed(): [number, Error] { + return super.qed(); } /** @@ -160,10 +146,6 @@ class NumberFactory extends FactoryCore { validate(validator: Validator) { return super.validate(validator); } - - modify(modifier: Modifier) { - return super.modify(modifier); - } } class StringFactory extends FactoryCore { @@ -210,8 +192,8 @@ class StringFactory extends FactoryCore { /** * このインスタンスの値およびエラーを取得します */ - get(): [string, Error] { - return super.get(); + qed(): [string, Error] { + return super.qed(); } /** @@ -222,10 +204,6 @@ class StringFactory extends FactoryCore { validate(validator: Validator) { return super.validate(validator); } - - modify(modifier: Modifier) { - return super.modify(modifier); - } } class ArrayFactory extends FactoryCore { @@ -277,8 +255,8 @@ class ArrayFactory extends FactoryCore { /** * このインスタンスの値およびエラーを取得します */ - get(): [any[], Error] { - return super.get(); + qed(): [any[], Error] { + return super.qed(); } /** @@ -289,10 +267,6 @@ class ArrayFactory extends FactoryCore { validate(validator: Validator) { return super.validate(validator); } - - modify(modifier: Modifier) { - return super.modify(modifier); - } } class IdFactory extends FactoryCore { @@ -320,8 +294,8 @@ class IdFactory extends FactoryCore { /** * このインスタンスの値およびエラーを取得します */ - get(): [any[], Error] { - return super.get(); + qed(): [any[], Error] { + return super.qed(); } /** @@ -332,10 +306,6 @@ class IdFactory extends FactoryCore { validate(validator: Validator) { return super.validate(validator); } - - modify(modifier: Modifier) { - return super.modify(modifier); - } } class ObjectFactory extends FactoryCore { @@ -363,8 +333,8 @@ class ObjectFactory extends FactoryCore { /** * このインスタンスの値およびエラーを取得します */ - get(): [any, Error] { - return super.get(); + qed(): [any, Error] { + return super.qed(); } /** @@ -375,13 +345,9 @@ class ObjectFactory extends FactoryCore { validate(validator: Validator) { return super.validate(validator); } - - modify(modifier: Modifier) { - return super.modify(modifier); - } } -type MustBe = { +type It = { must: { be: { a: { @@ -396,9 +362,17 @@ type MustBe = { }; }; }; + expect: { + string: () => StringFactory; + number: () => NumberFactory; + boolean: () => BooleanFactory; + id: () => IdFactory; + array: () => ArrayFactory; + object: () => ObjectFactory; + }; }; -const mustBe = (value: any) => ({ +const it = (value: any) => ({ must: { be: { a: { @@ -412,107 +386,50 @@ const mustBe = (value: any) => ({ object: () => new ObjectFactory(value) } } + }, + expect: { + string: () => new StringFactory(value), + number: () => new NumberFactory(value), + boolean: () => new BooleanFactory(value), + id: () => new IdFactory(value), + array: () => new ArrayFactory(value), + object: () => new ObjectFactory(value) } }); type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'set' | 'object'; -type Pipe = (x: T) => T | boolean | Error; - -function validate(value: any, type: 'id', isRequired?: boolean, pipe?: Pipe | Pipe[]): [mongo.ObjectID, Error]; -function validate(value: any, type: 'string', isRequired?: boolean, pipe?: Pipe | Pipe[]): [string, Error]; -function validate(value: any, type: 'number', isRequired?: boolean, pipe?: Pipe | Pipe[]): [number, Error]; -function validate(value: any, type: 'boolean', isRequired?: boolean): [boolean, Error]; -function validate(value: any, type: 'array', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any[], Error]; -function validate(value: any, type: 'set', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any[], Error]; -function validate(value: any, type: 'object', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any, Error]; -function validate(value: any, type: Type, isRequired?: boolean, pipe?: Pipe | Pipe[]): [any, Error] { - if (value === undefined || value === null) { - if (isRequired) { - return [null, new Error('is-required')] - } else { - return [null, null] - } - } - switch (type) { - case 'id': - if (typeof value != 'string' || !mongo.ObjectID.isValid(value)) { - return [null, new Error('incorrect-id')]; - } - break; +function x(value: any): It; +function x(value: any, type: 'id', isRequired?: boolean, validator?: Validator | Validator[]): [mongo.ObjectID, Error]; +function x(value: any, type: 'string', isRequired?: boolean, validator?: Validator | Validator[]): [string, Error]; +function x(value: any, type: 'number', isRequired?: boolean, validator?: Validator | Validator[]): [number, Error]; +function x(value: any, type: 'boolean', isRequired?: boolean): [boolean, Error]; +function x(value: any, type: 'array', isRequired?: boolean, validator?: Validator | Validator[]): [any[], Error]; +function x(value: any, type: 'set', isRequired?: boolean, validator?: Validator | Validator[]): [any[], Error]; +function x(value: any, type: 'object', isRequired?: boolean, validator?: Validator | Validator[]): [any, Error]; +function x(value: any, type?: Type, isRequired?: boolean, validator?: Validator | Validator[]): any { + if (typeof type === 'undefined') return it(value); - case 'string': - if (typeof value != 'string') { - return [null, new Error('must-be-a-string')]; - } - break; + let factory: Factory = null; - case 'number': - if (!Number.isFinite(value)) { - return [null, new Error('must-be-a-number')]; - } - break; - - case 'boolean': - if (typeof value != 'boolean') { - return [null, new Error('must-be-a-boolean')]; - } - break; - - case 'array': - if (!Array.isArray(value)) { - return [null, new Error('must-be-an-array')]; - } - break; - - case 'set': - if (!Array.isArray(value)) { - return [null, new Error('must-be-an-array')]; - } else if (hasDuplicates(value)) { - return [null, new Error('duplicated-contents')]; - } - break; - - case 'object': - if (typeof value != 'object') { - return [null, new Error('must-be-an-object')]; - } - break; + switch (type) { + case 'id': factory = it(value).expect.id(); break; + case 'string': factory = it(value).expect.string(); break; + case 'number': factory = it(value).expect.number(); break; + case 'boolean': factory = it(value).expect.boolean(); break; + case 'array': factory = it(value).expect.array(); break; + case 'set': factory = it(value).expect.array().unique(); break; + case 'object': factory = it(value).expect.object(); break; } - if (type == 'id') value = new mongo.ObjectID(value); + if (isRequired) factory = factory.required(); - if (pipe) { - const pipes = Array.isArray(pipe) ? pipe : [pipe]; - for (let i = 0; i < pipes.length; i++) { - const result = pipes[i](value); - if (result === false) { - return [null, new Error('invalid-format')]; - } else if (result instanceof Error) { - return [null, result]; - } else if (result !== true) { - value = result; - } - } + if (validator) { + (Array.isArray(validator) ? validator : [validator]) + .forEach(v => factory = factory.validate(v)); } - return [value, null]; -} - -function it(value: any): MustBe; -function it(value: any, type: 'id', isRequired?: boolean, pipe?: Pipe | Pipe[]): [mongo.ObjectID, Error]; -function it(value: any, type: 'string', isRequired?: boolean, pipe?: Pipe | Pipe[]): [string, Error]; -function it(value: any, type: 'number', isRequired?: boolean, pipe?: Pipe | Pipe[]): [number, Error]; -function it(value: any, type: 'boolean', isRequired?: boolean): [boolean, Error]; -function it(value: any, type: 'array', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any[], Error]; -function it(value: any, type: 'set', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any[], Error]; -function it(value: any, type: 'object', isRequired?: boolean, pipe?: Pipe | Pipe[]): [any, Error]; -function it(value: any, type?: any, isRequired?: boolean, pipe?: Pipe | Pipe[]): any { - if (typeof type === 'undefined') { - return mustBe(value); - } else { - return validate(value, type, isRequired, pipe); - } + return factory; } -export default it; +export default x; -- cgit v1.2.3-freya From c94de44f2726ba59cfb5d02751abdda5d0b9dca1 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 02:12:32 +0900 Subject: Fix bug --- src/api/endpoints/posts/create.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/create.ts b/src/api/endpoints/posts/create.ts index 5ce852280a..686c3a67d0 100644 --- a/src/api/endpoints/posts/create.ts +++ b/src/api/endpoints/posts/create.ts @@ -139,12 +139,12 @@ module.exports = (params, user, app) => if (choice.trim().length > 50) return true; return false; }); - return shouldReject ? 'invalid poll choices' : true; + return shouldReject ? new Error('invalid poll choices') : true; }, // 選択肢がひとつならエラー - choices => choices.length == 1 ? 'poll choices must be ひとつ以上' : true, + choices => choices.length == 1 ? new Error('poll choices must be ひとつ以上') : true, // 選択肢が多すぎてもエラー - choices => choices.length > 10 ? 'many poll choices' : true, + choices => choices.length > 10 ? new Error('many poll choices') : true, ]); if (pollChoicesErr) return rej('invalid poll choices'); -- cgit v1.2.3-freya From d5e5419dfc14bbb8a1329c2028134b0999883258 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 02:42:17 +0900 Subject: wip --- src/api/endpoints/posts/context.ts | 27 ++++--------- src/api/it.ts | 83 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 20 deletions(-) (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/context.ts b/src/api/endpoints/posts/context.ts index 673da0fab8..25ac687d34 100644 --- a/src/api/endpoints/posts/context.ts +++ b/src/api/endpoints/posts/context.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import validate from '../../validator'; +import it from '../../it'; import Post from '../../models/post'; import serialize from '../../serializers/post'; @@ -18,37 +18,24 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'post_id' parameter - const [postId, postIdErr] = validate(params.post_id, 'id', true); + const [postId, postIdErr] = it(params.post_id, 'id', true); if (postIdErr) return rej('invalid post_id'); // Get 'limit' parameter - let [limit, limitErr] = validate(params.limit, 'number'); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); 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; - } + const [offset, offsetErr] = it(params.limit).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset'); // Lookup post const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { - return rej('post not found', 'POST_NOT_FOUND'); + return rej('post not found'); } const context = []; diff --git a/src/api/it.ts b/src/api/it.ts index 6e8aefdf2d..ec42547488 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -1,3 +1,8 @@ +/** + * it + * 楽しいバリデーション + */ + import * as mongo from 'mongodb'; import hasDuplicates from '../common/has-duplicates'; @@ -11,6 +16,8 @@ interface Factory { required: () => Factory; + default: (value: any) => Factory; + validate: (validator: Validator) => Factory; } @@ -33,6 +40,16 @@ class FactoryCore implements Factory { return this; } + /** + * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します + */ + default(value: any) { + if (this.value === null) { + this.value = value; + } + return this; + } + /** * このインスタンスの値およびエラーを取得します */ @@ -79,6 +96,13 @@ class BooleanFactory extends FactoryCore { return super.required(); } + /** + * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します + */ + default(value: boolean) { + return super.default(value); + } + /** * このインスタンスの値およびエラーを取得します */ @@ -124,6 +148,30 @@ class NumberFactory extends FactoryCore { return this; } + /** + * このインスタンスの値が指定された下限より下回っている場合エラーにします + * @param value 下限 + */ + min(value: number) { + if (this.error || this.value === null) return this; + if (this.value < value) { + this.error = new Error('invalid-range'); + } + return this; + } + + /** + * このインスタンスの値が指定された上限より上回っている場合エラーにします + * @param value 上限 + */ + max(value: number) { + if (this.error || this.value === null) return this; + if (this.value > value) { + this.error = new Error('invalid-range'); + } + return this; + } + /** * このインスタンスの値が undefined または null の場合エラーにします */ @@ -131,6 +179,13 @@ class NumberFactory extends FactoryCore { return super.required(); } + /** + * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します + */ + default(value: number) { + return super.default(value); + } + /** * このインスタンスの値およびエラーを取得します */ @@ -189,6 +244,13 @@ class StringFactory extends FactoryCore { return super.required(); } + /** + * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します + */ + default(value: string) { + return super.default(value); + } + /** * このインスタンスの値およびエラーを取得します */ @@ -252,6 +314,13 @@ class ArrayFactory extends FactoryCore { return super.required(); } + /** + * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します + */ + default(value: any[]) { + return super.default(value); + } + /** * このインスタンスの値およびエラーを取得します */ @@ -291,6 +360,13 @@ class IdFactory extends FactoryCore { return super.required(); } + /** + * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します + */ + default(value: mongo.ObjectID) { + return super.default(value); + } + /** * このインスタンスの値およびエラーを取得します */ @@ -330,6 +406,13 @@ class ObjectFactory extends FactoryCore { return super.required(); } + /** + * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します + */ + default(value: any) { + return super.default(value); + } + /** * このインスタンスの値およびエラーを取得します */ -- cgit v1.2.3-freya From 8985d55b1bf34d81b553f77005d4bb5a856b6aef Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 05:33:59 +0900 Subject: fix --- src/api/endpoints/posts/context.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/context.ts b/src/api/endpoints/posts/context.ts index 25ac687d34..53fc4737e5 100644 --- a/src/api/endpoints/posts/context.ts +++ b/src/api/endpoints/posts/context.ts @@ -26,7 +26,7 @@ module.exports = (params, user) => if (limitErr) return rej('invalid limit'); // Get 'offset' parameter - const [offset, offsetErr] = it(params.limit).expect.number().min(0).default(0).qed(); + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); if (offsetErr) return rej('invalid offset'); // Lookup post -- cgit v1.2.3-freya From d6af0bb78ba2cd179161139b7ae20655e69a98c1 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 05:52:12 +0900 Subject: wip --- src/api/endpoints/posts/likes.js | 76 ---------------------------------------- src/api/endpoints/posts/likes.ts | 62 ++++++++++++++++++++++++++++++++ src/api/it.ts | 24 +++++++++++++ 3 files changed, 86 insertions(+), 76 deletions(-) delete mode 100644 src/api/endpoints/posts/likes.js create mode 100644 src/api/endpoints/posts/likes.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/likes.js b/src/api/endpoints/posts/likes.js deleted file mode 100644 index 67898218cf..0000000000 --- a/src/api/endpoints/posts/likes.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Post from '../../models/post'; -import Like from '../../models/like'; -import serialize from '../../serializers/user'; - -/** - * Show a likes of a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => -{ - // Get 'post_id' parameter - const postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // 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; - } - - // Get 'sort' parameter - let sort = params.sort || 'desc'; - - // Lookup post - const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) - }); - - if (post === null) { - return rej('post not found'); - } - - // Issue query - const likes = await Like - .find({ - post_id: post._id, - deleted_at: { $exists: false } - }, { - limit: limit, - skip: offset, - sort: { - _id: sort == 'asc' ? 1 : -1 - } - }); - - // Serialize - res(await Promise.all(likes.map(async like => - await serialize(like.user_id, user)))); -}); diff --git a/src/api/endpoints/posts/likes.ts b/src/api/endpoints/posts/likes.ts new file mode 100644 index 0000000000..5c18679d7c --- /dev/null +++ b/src/api/endpoints/posts/likes.ts @@ -0,0 +1,62 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import Post from '../../models/post'; +import Like from '../../models/like'; +import serialize from '../../serializers/user'; + +/** + * Show a likes of a post + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'post_id' parameter + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id'); + + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit'); + + // Get 'offset' parameter + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset'); + + // Get 'sort' parameter + const [sort] = it(params.sort).expect.string().or('desc asc').default('desc').qed(); + let sort = params.sort || 'desc'; + + // Lookup post + const post = await Post.findOne({ + _id: new mongo.ObjectID(postId) + }); + + if (post === null) { + return rej('post not found'); + } + + // Issue query + const likes = await Like + .find({ + post_id: post._id, + deleted_at: { $exists: false } + }, { + limit: limit, + skip: offset, + sort: { + _id: sort == 'asc' ? 1 : -1 + } + }); + + // Serialize + res(await Promise.all(likes.map(async like => + await serialize(like.user_id, user)))); +}); diff --git a/src/api/it.ts b/src/api/it.ts index 5ca8d7dcae..2e6a7a770d 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -266,6 +266,30 @@ class StringQuery extends QueryCore { validate(validator: Validator) { return super.validate(validator); } + + /** + * このインスタンスの文字列が、与えられたパターン内の文字列のどれかと一致するか検証します + * どれとも一致しない場合エラーにします + * @param pattern 文字列の配列またはスペースで区切られた文字列 + */ + or(pattern: string | string[]) { + if (this.error || this.value === null) return this; + if (typeof pattern == 'string') pattern = pattern.split(' '); + const match = pattern.some(x => x === this.value); + if (!match) this.error = new Error('not-match-pattern'); + return this; + } + + /** + * このインスタンスの文字列が、与えられた正規表現と一致するか検証します + * 一致しない場合エラーにします + * @param pattern 正規表現 + */ + match(pattern: RegExp) { + if (this.error || this.value === null) return this; + if (!pattern.test(this.value)) this.error = new Error('not-match-pattern'); + return this; + } } class ArrayQuery extends QueryCore { -- cgit v1.2.3-freya From 9d3dff88056dac8eb00e62fedf438b197f99c256 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 06:29:49 +0900 Subject: wip --- src/api/endpoints/posts/likes.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/likes.ts b/src/api/endpoints/posts/likes.ts index 5c18679d7c..e44013c246 100644 --- a/src/api/endpoints/posts/likes.ts +++ b/src/api/endpoints/posts/likes.ts @@ -31,12 +31,12 @@ module.exports = (params, user) => if (offsetErr) return rej('invalid offset'); // Get 'sort' parameter - const [sort] = it(params.sort).expect.string().or('desc asc').default('desc').qed(); - let sort = params.sort || 'desc'; + const [sort, sortError] = it(params.sort).expect.string().or('desc asc').default('desc').qed(); + if (sortError) return rej('invalid sort'); // Lookup post const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { -- cgit v1.2.3-freya From d3c4cd1c433d2077628d6aba0fb3d053c94ddaa1 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 06:37:09 +0900 Subject: wip --- src/api/endpoints/posts/mentions.js | 84 ------------------------------------- src/api/endpoints/posts/mentions.ts | 82 ++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 84 deletions(-) delete mode 100644 src/api/endpoints/posts/mentions.js create mode 100644 src/api/endpoints/posts/mentions.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/mentions.js b/src/api/endpoints/posts/mentions.js deleted file mode 100644 index 5a3d72aab8..0000000000 --- a/src/api/endpoints/posts/mentions.js +++ /dev/null @@ -1,84 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Post from '../../models/post'; -import getFriends from '../../common/get-friends'; -import serialize from '../../serializers/post'; - -/** - * Get mentions of myself - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => -{ - // Get 'following' parameter - const following = params.following; - - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } - - const since = params.since_id || null; - const max = params.max_id || null; - - // Check if both of since_id and max_id is specified - if (since !== null && max !== null) { - return rej('cannot set since_id and max_id'); - } - - // Construct query - const query = { - mentions: user._id - }; - - const sort = { - _id: -1 - }; - - if (following) { - const followingIds = await getFriends(user._id); - - query.user_id = { - $in: followingIds - }; - } - - if (since) { - sort._id = 1; - query._id = { - $gt: new mongo.ObjectID(since) - }; - } else if (max) { - query._id = { - $lt: new mongo.ObjectID(max) - }; - } - - // Issue query - const mentions = await Post - .find(query, { - limit: limit, - sort: sort - }); - - // Serialize - res(await Promise.all(mentions.map(async mention => - await serialize(mention, user) - ))); -}); diff --git a/src/api/endpoints/posts/mentions.ts b/src/api/endpoints/posts/mentions.ts new file mode 100644 index 0000000000..59802c558a --- /dev/null +++ b/src/api/endpoints/posts/mentions.ts @@ -0,0 +1,82 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import Post from '../../models/post'; +import getFriends from '../../common/get-friends'; +import serialize from '../../serializers/post'; + +/** + * Get mentions of myself + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'following' parameter + const [following, followingError] = + it(params.following).expect.boolean().default(false).qed(); + if (followingError) return rej('invalid following param'); + + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); + + // Get 'max_id' parameter + const [maxId, maxIdErr] = it(params.max_id).expect.id().qed(); + if (maxIdErr) return rej('invalid max_id param'); + + // Check if both of since_id and max_id is specified + if (sinceId !== null && maxId !== null) { + return rej('cannot set since_id and max_id'); + } + + // Construct query + const query = { + mentions: user._id + } as any; + + const sort = { + _id: -1 + }; + + if (following) { + const followingIds = await getFriends(user._id); + + query.user_id = { + $in: followingIds + }; + } + + if (sinceId) { + sort._id = 1; + query._id = { + $gt: sinceId + }; + } else if (maxId) { + query._id = { + $lt: maxId + }; + } + + // Issue query + const mentions = await Post + .find(query, { + limit: limit, + sort: sort + }); + + // Serialize + res(await Promise.all(mentions.map(async mention => + await serialize(mention, user) + ))); +}); -- cgit v1.2.3-freya From 6e181ee0f1ca2ecd0fdf3a78654607ef112f2a6a Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 06:48:26 +0900 Subject: wip --- src/api/endpoints/posts/context.ts | 6 +- src/api/endpoints/posts/likes.ts | 8 +-- src/api/endpoints/posts/replies.js | 72 ------------------- src/api/endpoints/posts/replies.ts | 58 +++++++++++++++ src/api/endpoints/posts/reposts.js | 84 ---------------------- src/api/endpoints/posts/reposts.ts | 78 ++++++++++++++++++++ src/api/endpoints/posts/search.js | 137 ------------------------------------ src/api/endpoints/posts/search.ts | 123 ++++++++++++++++++++++++++++++++ src/api/endpoints/posts/show.js | 44 ------------ src/api/endpoints/posts/show.ts | 37 ++++++++++ src/api/endpoints/posts/timeline.js | 77 -------------------- src/api/endpoints/posts/timeline.ts | 73 +++++++++++++++++++ 12 files changed, 376 insertions(+), 421 deletions(-) delete mode 100644 src/api/endpoints/posts/replies.js create mode 100644 src/api/endpoints/posts/replies.ts delete mode 100644 src/api/endpoints/posts/reposts.js create mode 100644 src/api/endpoints/posts/reposts.ts delete mode 100644 src/api/endpoints/posts/search.js create mode 100644 src/api/endpoints/posts/search.ts delete mode 100644 src/api/endpoints/posts/show.js create mode 100644 src/api/endpoints/posts/show.ts delete mode 100644 src/api/endpoints/posts/timeline.js create mode 100644 src/api/endpoints/posts/timeline.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/context.ts b/src/api/endpoints/posts/context.ts index 53fc4737e5..5b0a56f356 100644 --- a/src/api/endpoints/posts/context.ts +++ b/src/api/endpoints/posts/context.ts @@ -19,15 +19,15 @@ module.exports = (params, user) => { // Get 'post_id' parameter const [postId, postIdErr] = it(params.post_id, 'id', true); - if (postIdErr) return rej('invalid post_id'); + if (postIdErr) return rej('invalid post_id param'); // Get 'limit' parameter const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); - if (limitErr) return rej('invalid limit'); + if (limitErr) return rej('invalid limit param'); // Get 'offset' parameter const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); - if (offsetErr) return rej('invalid offset'); + if (offsetErr) return rej('invalid offset param'); // Lookup post const post = await Post.findOne({ diff --git a/src/api/endpoints/posts/likes.ts b/src/api/endpoints/posts/likes.ts index e44013c246..f299de7492 100644 --- a/src/api/endpoints/posts/likes.ts +++ b/src/api/endpoints/posts/likes.ts @@ -20,19 +20,19 @@ module.exports = (params, user) => { // Get 'post_id' parameter const [postId, postIdErr] = it(params.post_id, 'id', true); - if (postIdErr) return rej('invalid post_id'); + if (postIdErr) return rej('invalid post_id param'); // Get 'limit' parameter const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); - if (limitErr) return rej('invalid limit'); + if (limitErr) return rej('invalid limit param'); // Get 'offset' parameter const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); - if (offsetErr) return rej('invalid offset'); + if (offsetErr) return rej('invalid offset param'); // Get 'sort' parameter const [sort, sortError] = it(params.sort).expect.string().or('desc asc').default('desc').qed(); - if (sortError) return rej('invalid sort'); + if (sortError) return rej('invalid sort param'); // Lookup post const post = await Post.findOne({ diff --git a/src/api/endpoints/posts/replies.js b/src/api/endpoints/posts/replies.js deleted file mode 100644 index cbbb5dc312..0000000000 --- a/src/api/endpoints/posts/replies.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Post from '../../models/post'; -import serialize from '../../serializers/post'; - -/** - * Show a replies of a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => -{ - // Get 'post_id' parameter - const postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // 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; - } - - // Get 'sort' parameter - let sort = params.sort || 'desc'; - - // Lookup post - const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) - }); - - if (post === null) { - return rej('post not found', 'POST_NOT_FOUND'); - } - - // Issue query - const replies = await Post - .find({ reply_to_id: post._id }, { - limit: limit, - skip: offset, - sort: { - _id: sort == 'asc' ? 1 : -1 - } - }); - - // Serialize - res(await Promise.all(replies.map(async post => - await serialize(post, user)))); -}); diff --git a/src/api/endpoints/posts/replies.ts b/src/api/endpoints/posts/replies.ts new file mode 100644 index 0000000000..3f448d1632 --- /dev/null +++ b/src/api/endpoints/posts/replies.ts @@ -0,0 +1,58 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import Post from '../../models/post'; +import serialize from '../../serializers/post'; + +/** + * Show a replies of a post + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'post_id' parameter + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); + + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'offset' parameter + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); + + // Get 'sort' parameter + const [sort, sortError] = it(params.sort).expect.string().or('desc asc').default('desc').qed(); + if (sortError) return rej('invalid sort param'); + + // Lookup post + const post = await Post.findOne({ + _id: postId + }); + + if (post === null) { + return rej('post not found'); + } + + // Issue query + const replies = await Post + .find({ reply_to_id: post._id }, { + limit: limit, + skip: offset, + sort: { + _id: sort == 'asc' ? 1 : -1 + } + }); + + // Serialize + res(await Promise.all(replies.map(async post => + await serialize(post, user)))); +}); diff --git a/src/api/endpoints/posts/reposts.js b/src/api/endpoints/posts/reposts.js deleted file mode 100644 index 0ffe44cb16..0000000000 --- a/src/api/endpoints/posts/reposts.js +++ /dev/null @@ -1,84 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Post from '../../models/post'; -import serialize from '../../serializers/post'; - -/** - * Show a reposts of a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => -{ - // Get 'post_id' parameter - const postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } - - const since = params.since_id || null; - const max = params.max_id || null; - - // Check if both of since_id and max_id is specified - if (since !== null && max !== null) { - return rej('cannot set since_id and max_id'); - } - - // Lookup post - const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) - }); - - if (post === null) { - return rej('post not found', 'POST_NOT_FOUND'); - } - - // Construct query - const sort = { - _id: -1 - }; - const query = { - repost_id: post._id - }; - if (since !== null) { - sort._id = 1; - query._id = { - $gt: new mongo.ObjectID(since) - }; - } else if (max !== null) { - query._id = { - $lt: new mongo.ObjectID(max) - }; - } - - // Issue query - const reposts = await Post - .find(query, { - limit: limit, - sort: sort - }); - - // Serialize - res(await Promise.all(reposts.map(async post => - await serialize(post, user)))); -}); diff --git a/src/api/endpoints/posts/reposts.ts b/src/api/endpoints/posts/reposts.ts new file mode 100644 index 0000000000..d8410b322b --- /dev/null +++ b/src/api/endpoints/posts/reposts.ts @@ -0,0 +1,78 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import Post from '../../models/post'; +import serialize from '../../serializers/post'; + +/** + * Show a reposts of a post + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'post_id' parameter + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); + + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); + + // Get 'max_id' parameter + const [maxId, maxIdErr] = it(params.max_id).expect.id().qed(); + if (maxIdErr) return rej('invalid max_id param'); + + // Check if both of since_id and max_id is specified + if (sinceId !== null && maxId !== null) { + return rej('cannot set since_id and max_id'); + } + + // Lookup post + const post = await Post.findOne({ + _id: postId + }); + + if (post === null) { + return rej('post not found'); + } + + // Construct query + const sort = { + _id: -1 + }; + const query = { + repost_id: post._id + } as any; + if (sinceId) { + sort._id = 1; + query._id = { + $gt: sinceId + }; + } else if (maxId) { + query._id = { + $lt: maxId + }; + } + + // Issue query + const reposts = await Post + .find(query, { + limit: limit, + sort: sort + }); + + // Serialize + res(await Promise.all(reposts.map(async post => + await serialize(post, user)))); +}); diff --git a/src/api/endpoints/posts/search.js b/src/api/endpoints/posts/search.js deleted file mode 100644 index bc06340fda..0000000000 --- a/src/api/endpoints/posts/search.js +++ /dev/null @@ -1,137 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -const escapeRegexp = require('escape-regexp'); -import Post from '../../models/post'; -import serialize from '../../serializers/post'; -import config from '../../../conf'; - -/** - * Search a post - * - * @param {any} params - * @param {any} me - * @return {Promise} - */ -module.exports = (params, me) => - new Promise(async (res, rej) => -{ - // Get 'query' parameter - let query = params.query; - if (query === undefined || query === null || query.trim() === '') { - return rej('query is required'); - } - - // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } - - // Get 'max' parameter - let max = params.max; - if (max !== undefined && max !== null) { - max = parseInt(max, 10); - - // From 1 to 30 - if (!(1 <= max && max <= 30)) { - return rej('invalid max range'); - } - } else { - max = 10; - } - - // If Elasticsearch is available, search by it - // If not, search by MongoDB - (config.elasticsearch.enable ? byElasticsearch : byNative) - (res, rej, me, query, offset, max); -}); - -// Search by MongoDB -async function byNative(res, rej, me, query, offset, max) { - const escapedQuery = escapeRegexp(query); - - // Search posts - const posts = await Post - .find({ - text: new RegExp(escapedQuery) - }, { - sort: { - _id: -1 - }, - limit: max, - skip: offset - }); - - // Serialize - res(await Promise.all(posts.map(async post => - await serialize(post, me)))); -} - -// Search by Elasticsearch -async function byElasticsearch(res, rej, me, query, offset, max) { - const es = require('../../db/elasticsearch'); - - es.search({ - index: 'misskey', - type: 'post', - body: { - size: max, - from: offset, - query: { - simple_query_string: { - fields: ['text'], - query: query, - default_operator: 'and' - } - }, - sort: [ - { _doc: 'desc' } - ], - highlight: { - pre_tags: [''], - post_tags: [''], - encoder: 'html', - fields: { - text: {} - } - } - } - }, async (error, response) => { - if (error) { - console.error(error); - return res(500); - } - - if (response.hits.total === 0) { - return res([]); - } - - const hits = response.hits.hits.map(hit => new mongo.ObjectID(hit._id)); - - // Fetch found posts - const posts = await Post - .find({ - _id: { - $in: hits - } - }, { - sort: { - _id: -1 - } - }); - - posts.map(post => { - post._highlight = response.hits.hits.filter(hit => post._id.equals(hit._id))[0].highlight.text[0]; - }); - - // Serialize - res(await Promise.all(posts.map(async post => - await serialize(post, me)))); - }); -} diff --git a/src/api/endpoints/posts/search.ts b/src/api/endpoints/posts/search.ts new file mode 100644 index 0000000000..1d02f6775d --- /dev/null +++ b/src/api/endpoints/posts/search.ts @@ -0,0 +1,123 @@ +'use strict'; + +/** + * Module dependencies + */ +import * as mongo from 'mongodb'; +import it from '../../it'; +const escapeRegexp = require('escape-regexp'); +import Post from '../../models/post'; +import serialize from '../../serializers/post'; +import config from '../../../conf'; + +/** + * Search a post + * + * @param {any} params + * @param {any} me + * @return {Promise} + */ +module.exports = (params, me) => + new Promise(async (res, rej) => +{ + // Get 'query' parameter + const [query, queryError] = it(params.query).expect.string().required().trim().validate(x => x != '').qed(); + if (queryError) return rej('invalid query param'); + + // Get 'offset' parameter + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); + + // Get 'max' parameter + const [max, maxErr] = it(params.max).expect.number().range(1, 30).default(10).qed(); + if (maxErr) return rej('invalid max param'); + + // If Elasticsearch is available, search by it + // If not, search by MongoDB + (config.elasticsearch.enable ? byElasticsearch : byNative) + (res, rej, me, query, offset, max); +}); + +// Search by MongoDB +async function byNative(res, rej, me, query, offset, max) { + const escapedQuery = escapeRegexp(query); + + // Search posts + const posts = await Post + .find({ + text: new RegExp(escapedQuery) + }, { + sort: { + _id: -1 + }, + limit: max, + skip: offset + }); + + // Serialize + res(await Promise.all(posts.map(async post => + await serialize(post, me)))); +} + +// Search by Elasticsearch +async function byElasticsearch(res, rej, me, query, offset, max) { + const es = require('../../db/elasticsearch'); + + es.search({ + index: 'misskey', + type: 'post', + body: { + size: max, + from: offset, + query: { + simple_query_string: { + fields: ['text'], + query: query, + default_operator: 'and' + } + }, + sort: [ + { _doc: 'desc' } + ], + highlight: { + pre_tags: [''], + post_tags: [''], + encoder: 'html', + fields: { + text: {} + } + } + } + }, async (error, response) => { + if (error) { + console.error(error); + return res(500); + } + + if (response.hits.total === 0) { + return res([]); + } + + const hits = response.hits.hits.map(hit => new mongo.ObjectID(hit._id)); + + // Fetch found posts + const posts = await Post + .find({ + _id: { + $in: hits + } + }, { + sort: { + _id: -1 + } + }); + + posts.map(post => { + post._highlight = response.hits.hits.filter(hit => post._id.equals(hit._id))[0].highlight.text[0]; + }); + + // Serialize + res(await Promise.all(posts.map(async post => + await serialize(post, me)))); + }); +} diff --git a/src/api/endpoints/posts/show.js b/src/api/endpoints/posts/show.js deleted file mode 100644 index 4938199cdb..0000000000 --- a/src/api/endpoints/posts/show.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Post from '../../models/post'; -import serialize from '../../serializers/post'; - -/** - * Show a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => -{ - // Get 'post_id' parameter - const postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Validate id - if (!mongo.ObjectID.isValid(postId)) { - return rej('incorrect post_id'); - } - - // Get post - const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) - }); - - if (post === null) { - return rej('post not found'); - } - - // Serialize - res(await serialize(post, user, { - detail: true - })); -}); diff --git a/src/api/endpoints/posts/show.ts b/src/api/endpoints/posts/show.ts new file mode 100644 index 0000000000..712ef1e160 --- /dev/null +++ b/src/api/endpoints/posts/show.ts @@ -0,0 +1,37 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import Post from '../../models/post'; +import serialize from '../../serializers/post'; + +/** + * Show a post + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'post_id' parameter + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); + + // Get post + const post = await Post.findOne({ + _id: postId + }); + + if (post === null) { + return rej('post not found'); + } + + // Serialize + res(await serialize(post, user, { + detail: true + })); +}); diff --git a/src/api/endpoints/posts/timeline.js b/src/api/endpoints/posts/timeline.js deleted file mode 100644 index 48f7c26940..0000000000 --- a/src/api/endpoints/posts/timeline.js +++ /dev/null @@ -1,77 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Post from '../../models/post'; -import getFriends from '../../common/get-friends'; -import serialize from '../../serializers/post'; - -/** - * Get timeline of myself - * - * @param {any} params - * @param {any} user - * @param {any} app - * @return {Promise} - */ -module.exports = (params, user, app) => - new Promise(async (res, rej) => -{ - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } - - const since = params.since_id || null; - const max = params.max_id || null; - - // Check if both of since_id and max_id is specified - if (since !== null && max !== null) { - return rej('cannot set since_id and max_id'); - } - - // ID list of the user itself and other users who the user follows - const followingIds = await getFriends(user._id); - - // Construct query - const sort = { - _id: -1 - }; - const query = { - user_id: { - $in: followingIds - } - }; - if (since !== null) { - sort._id = 1; - query._id = { - $gt: new mongo.ObjectID(since) - }; - } else if (max !== null) { - query._id = { - $lt: new mongo.ObjectID(max) - }; - } - - // Issue query - const timeline = await Post - .find(query, { - limit: limit, - sort: sort - }); - - // Serialize - res(await Promise.all(timeline.map(async post => - await serialize(post, user) - ))); -}); diff --git a/src/api/endpoints/posts/timeline.ts b/src/api/endpoints/posts/timeline.ts new file mode 100644 index 0000000000..5744084932 --- /dev/null +++ b/src/api/endpoints/posts/timeline.ts @@ -0,0 +1,73 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import Post from '../../models/post'; +import getFriends from '../../common/get-friends'; +import serialize from '../../serializers/post'; + +/** + * Get timeline of myself + * + * @param {any} params + * @param {any} user + * @param {any} app + * @return {Promise} + */ +module.exports = (params, user, app) => + new Promise(async (res, rej) => +{ + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); + + // Get 'max_id' parameter + const [maxId, maxIdErr] = it(params.max_id).expect.id().qed(); + if (maxIdErr) return rej('invalid max_id param'); + + // Check if both of since_id and max_id is specified + if (sinceId !== null && maxId !== null) { + return rej('cannot set since_id and max_id'); + } + + // ID list of the user itself and other users who the user follows + const followingIds = await getFriends(user._id); + + // Construct query + const sort = { + _id: -1 + }; + const query = { + user_id: { + $in: followingIds + } + } as any; + if (sinceId) { + sort._id = 1; + query._id = { + $gt: sinceId + }; + } else if (maxId) { + query._id = { + $lt: maxId + }; + } + + // Issue query + const timeline = await Post + .find(query, { + limit: limit, + sort: sort + }); + + // Serialize + res(await Promise.all(timeline.map(async post => + await serialize(post, user) + ))); +}); -- cgit v1.2.3-freya From 583b64331b4d3d36f642801c847109b8634df1d9 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 08:00:10 +0900 Subject: wip --- src/api/endpoints/posts/favorites/create.js | 53 --------------- src/api/endpoints/posts/favorites/create.ts | 51 ++++++++++++++ src/api/endpoints/posts/favorites/delete.js | 51 -------------- src/api/endpoints/posts/favorites/delete.ts | 49 ++++++++++++++ src/api/endpoints/posts/likes/create.js | 92 ------------------------- src/api/endpoints/posts/likes/create.ts | 85 +++++++++++++++++++++++ src/api/endpoints/posts/likes/delete.js | 84 ----------------------- src/api/endpoints/posts/likes/delete.ts | 77 +++++++++++++++++++++ src/api/endpoints/posts/polls/vote.js | 100 ---------------------------- src/api/endpoints/posts/polls/vote.ts | 88 ++++++++++++++++++++++++ src/api/endpoints/username/available.js | 41 ------------ src/api/endpoints/username/available.ts | 35 ++++++++++ 12 files changed, 385 insertions(+), 421 deletions(-) delete mode 100644 src/api/endpoints/posts/favorites/create.js create mode 100644 src/api/endpoints/posts/favorites/create.ts delete mode 100644 src/api/endpoints/posts/favorites/delete.js create mode 100644 src/api/endpoints/posts/favorites/delete.ts delete mode 100644 src/api/endpoints/posts/likes/create.js create mode 100644 src/api/endpoints/posts/likes/create.ts delete mode 100644 src/api/endpoints/posts/likes/delete.js create mode 100644 src/api/endpoints/posts/likes/delete.ts delete mode 100644 src/api/endpoints/posts/polls/vote.js create mode 100644 src/api/endpoints/posts/polls/vote.ts delete mode 100644 src/api/endpoints/username/available.js create mode 100644 src/api/endpoints/username/available.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/posts/favorites/create.js b/src/api/endpoints/posts/favorites/create.js deleted file mode 100644 index 7ee7c0d3fb..0000000000 --- a/src/api/endpoints/posts/favorites/create.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Favorite from '../../models/favorite'; -import Post from '../../models/post'; - -/** - * Favorite a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => { - // Get 'post_id' parameter - let postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Get favoritee - const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) - }); - - if (post === null) { - return rej('post not found'); - } - - // if already favorited - const exist = await Favorite.findOne({ - post_id: post._id, - user_id: user._id - }); - - if (exist !== null) { - return rej('already favorited'); - } - - // Create favorite - await Favorite.insert({ - created_at: new Date(), - post_id: post._id, - user_id: user._id - }); - - // Send response - res(); - }); diff --git a/src/api/endpoints/posts/favorites/create.ts b/src/api/endpoints/posts/favorites/create.ts new file mode 100644 index 0000000000..5be338593c --- /dev/null +++ b/src/api/endpoints/posts/favorites/create.ts @@ -0,0 +1,51 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../../it'; +import Favorite from '../../../models/favorite'; +import Post from '../../../models/post'; + +/** + * Favorite a post + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => { + // Get 'post_id' parameter + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); + + // Get favoritee + const post = await Post.findOne({ + _id: new mongo.ObjectID(postId) + }); + + if (post === null) { + return rej('post not found'); + } + + // if already favorited + const exist = await Favorite.findOne({ + post_id: post._id, + user_id: user._id + }); + + if (exist !== null) { + return rej('already favorited'); + } + + // Create favorite + await Favorite.insert({ + created_at: new Date(), + post_id: post._id, + user_id: user._id + }); + + // Send response + res(); + }); diff --git a/src/api/endpoints/posts/favorites/delete.js b/src/api/endpoints/posts/favorites/delete.js deleted file mode 100644 index 4b36b9bde3..0000000000 --- a/src/api/endpoints/posts/favorites/delete.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Favorite from '../../models/favorite'; -import Post from '../../models/post'; - -/** - * Unfavorite a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => { - // Get 'post_id' parameter - let postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Get favoritee - const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) - }); - - if (post === null) { - return rej('post not found'); - } - - // if already favorited - const exist = await Favorite.findOne({ - post_id: post._id, - user_id: user._id - }); - - if (exist === null) { - return rej('already not favorited'); - } - - // Delete favorite - await Favorite.deleteOne({ - _id: exist._id - }); - - // Send response - res(); - }); diff --git a/src/api/endpoints/posts/favorites/delete.ts b/src/api/endpoints/posts/favorites/delete.ts new file mode 100644 index 0000000000..4dfd761589 --- /dev/null +++ b/src/api/endpoints/posts/favorites/delete.ts @@ -0,0 +1,49 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../../it'; +import Favorite from '../../../models/favorite'; +import Post from '../../../models/post'; + +/** + * Unfavorite a post + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => { + // Get 'post_id' parameter + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); + + // Get favoritee + const post = await Post.findOne({ + _id: new mongo.ObjectID(postId) + }); + + if (post === null) { + return rej('post not found'); + } + + // if already favorited + const exist = await Favorite.findOne({ + post_id: post._id, + user_id: user._id + }); + + if (exist === null) { + return rej('already not favorited'); + } + + // Delete favorite + await Favorite.deleteOne({ + _id: exist._id + }); + + // Send response + res(); + }); diff --git a/src/api/endpoints/posts/likes/create.js b/src/api/endpoints/posts/likes/create.js deleted file mode 100644 index 3b2c778a03..0000000000 --- a/src/api/endpoints/posts/likes/create.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Like from '../../../models/like'; -import Post from '../../../models/post'; -import User from '../../../models/user'; -import notify from '../../../common/notify'; - -/** - * Like a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => { - // Get 'post_id' parameter - let postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Validate id - if (!mongo.ObjectID.isValid(postId)) { - return rej('incorrect post_id'); - } - - // Get likee - const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) - }); - - if (post === null) { - return rej('post not found'); - } - - // Myself - if (post.user_id.equals(user._id)) { - return rej('-need-translate-'); - } - - // if already liked - const exist = await Like.findOne({ - post_id: post._id, - user_id: user._id, - deleted_at: { $exists: false } - }); - - if (exist !== null) { - return rej('already liked'); - } - - // Create like - await Like.insert({ - created_at: new Date(), - post_id: post._id, - user_id: user._id - }); - - // Send response - res(); - - // Increment likes count - Post.update({ _id: post._id }, { - $inc: { - likes_count: 1 - } - }); - - // Increment user likes count - User.update({ _id: user._id }, { - $inc: { - likes_count: 1 - } - }); - - // Increment user liked count - User.update({ _id: post.user_id }, { - $inc: { - liked_count: 1 - } - }); - - // Notify - notify(post.user_id, user._id, 'like', { - post_id: post._id - }); - }); diff --git a/src/api/endpoints/posts/likes/create.ts b/src/api/endpoints/posts/likes/create.ts new file mode 100644 index 0000000000..0ae417e239 --- /dev/null +++ b/src/api/endpoints/posts/likes/create.ts @@ -0,0 +1,85 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../../it'; +import Like from '../../../models/like'; +import Post from '../../../models/post'; +import User from '../../../models/user'; +import notify from '../../../common/notify'; + +/** + * Like a post + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => { + // Get 'post_id' parameter + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); + + // Get likee + const post = await Post.findOne({ + _id: postId + }); + + if (post === null) { + return rej('post not found'); + } + + // Myself + if (post.user_id.equals(user._id)) { + return rej('-need-translate-'); + } + + // if already liked + const exist = await Like.findOne({ + post_id: post._id, + user_id: user._id, + deleted_at: { $exists: false } + }); + + if (exist !== null) { + return rej('already liked'); + } + + // Create like + await Like.insert({ + created_at: new Date(), + post_id: post._id, + user_id: user._id + }); + + // Send response + res(); + + // Increment likes count + Post.update({ _id: post._id }, { + $inc: { + likes_count: 1 + } + }); + + // Increment user likes count + User.update({ _id: user._id }, { + $inc: { + likes_count: 1 + } + }); + + // Increment user liked count + User.update({ _id: post.user_id }, { + $inc: { + liked_count: 1 + } + }); + + // Notify + notify(post.user_id, user._id, 'like', { + post_id: post._id + }); + }); diff --git a/src/api/endpoints/posts/likes/delete.js b/src/api/endpoints/posts/likes/delete.js deleted file mode 100644 index 1dd0f5b29a..0000000000 --- a/src/api/endpoints/posts/likes/delete.js +++ /dev/null @@ -1,84 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Like from '../../../models/like'; -import Post from '../../../models/post'; -import User from '../../../models/user'; -// import event from '../../../event'; - -/** - * Unlike a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => { - // Get 'post_id' parameter - let postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Validate id - if (!mongo.ObjectID.isValid(postId)) { - return rej('incorrect post_id'); - } - - // Get likee - const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) - }); - - if (post === null) { - return rej('post not found'); - } - - // if already liked - const exist = await Like.findOne({ - post_id: post._id, - user_id: user._id, - deleted_at: { $exists: false } - }); - - if (exist === null) { - return rej('already not liked'); - } - - // Delete like - await Like.update({ - _id: exist._id - }, { - $set: { - deleted_at: new Date() - } - }); - - // Send response - res(); - - // Decrement likes count - Post.update({ _id: post._id }, { - $inc: { - likes_count: -1 - } - }); - - // Decrement user likes count - User.update({ _id: user._id }, { - $inc: { - likes_count: -1 - } - }); - - // Decrement user liked count - User.update({ _id: post.user_id }, { - $inc: { - liked_count: -1 - } - }); - }); diff --git a/src/api/endpoints/posts/likes/delete.ts b/src/api/endpoints/posts/likes/delete.ts new file mode 100644 index 0000000000..2b642c107f --- /dev/null +++ b/src/api/endpoints/posts/likes/delete.ts @@ -0,0 +1,77 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../../it'; +import Like from '../../../models/like'; +import Post from '../../../models/post'; +import User from '../../../models/user'; +// import event from '../../../event'; + +/** + * Unlike a post + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => { + // Get 'post_id' parameter + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); + + // Get likee + const post = await Post.findOne({ + _id: postId + }); + + if (post === null) { + return rej('post not found'); + } + + // if already liked + const exist = await Like.findOne({ + post_id: post._id, + user_id: user._id, + deleted_at: { $exists: false } + }); + + if (exist === null) { + return rej('already not liked'); + } + + // Delete like + await Like.update({ + _id: exist._id + }, { + $set: { + deleted_at: new Date() + } + }); + + // Send response + res(); + + // Decrement likes count + Post.update({ _id: post._id }, { + $inc: { + likes_count: -1 + } + }); + + // Decrement user likes count + User.update({ _id: user._id }, { + $inc: { + likes_count: -1 + } + }); + + // Decrement user liked count + User.update({ _id: post.user_id }, { + $inc: { + liked_count: -1 + } + }); + }); diff --git a/src/api/endpoints/posts/polls/vote.js b/src/api/endpoints/posts/polls/vote.js deleted file mode 100644 index 9f9a5171a0..0000000000 --- a/src/api/endpoints/posts/polls/vote.js +++ /dev/null @@ -1,100 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Vote from '../../../models/poll-vote'; -import Post from '../../../models/post'; -import notify from '../../../common/notify'; - -/** - * Vote poll of a post - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => { - // Get 'post_id' parameter - const postId = params.post_id; - if (postId === undefined || postId === null) { - return rej('post_id is required'); - } - - // Validate id - if (!mongo.ObjectID.isValid(postId)) { - return rej('incorrect post_id'); - } - - // Get votee - const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) - }); - - if (post === null) { - return rej('post not found'); - } - - if (post.poll == null) { - return rej('poll not found'); - } - - // Get 'choice' parameter - const choice = params.choice; - if (choice == null) { - return rej('choice is required'); - } - - // Validate choice - if (!post.poll.choices.some(x => x.id == choice)) { - return rej('invalid choice'); - } - - // if already voted - const exist = await Vote.findOne({ - post_id: post._id, - user_id: user._id - }); - - if (exist !== null) { - return rej('already voted'); - } - - // Create vote - await Vote.insert({ - created_at: new Date(), - post_id: post._id, - user_id: user._id, - choice: choice - }); - - // Send response - res(); - - const inc = {}; - inc[`poll.choices.${findWithAttr(post.poll.choices, 'id', choice)}.votes`] = 1; - - console.log(inc); - - // Increment likes count - Post.update({ _id: post._id }, { - $inc: inc - }); - - // Notify - notify(post.user_id, user._id, 'poll_vote', { - post_id: post._id, - choice: choice - }); - }); - -function findWithAttr(array, attr, value) { - for (let i = 0; i < array.length; i += 1) { - if (array[i][attr] === value) { - return i; - } - } - return -1; -} diff --git a/src/api/endpoints/posts/polls/vote.ts b/src/api/endpoints/posts/polls/vote.ts new file mode 100644 index 0000000000..d0caf7da95 --- /dev/null +++ b/src/api/endpoints/posts/polls/vote.ts @@ -0,0 +1,88 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../../it'; +import Vote from '../../../models/poll-vote'; +import Post from '../../../models/post'; +import notify from '../../../common/notify'; + +/** + * Vote poll of a post + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => { + // Get 'post_id' parameter + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); + + // Get votee + const post = await Post.findOne({ + _id: postId + }); + + if (post === null) { + return rej('post not found'); + } + + if (post.poll == null) { + return rej('poll not found'); + } + + // Get 'choice' parameter + const [choice, choiceError] = + it(params.choice).expect.string() + .required() + .validate(c => post.poll.choices.some(x => x.id == c)) + .qed(); + if (choiceError) return rej('invalid choice param'); + + // if already voted + const exist = await Vote.findOne({ + post_id: post._id, + user_id: user._id + }); + + if (exist !== null) { + return rej('already voted'); + } + + // Create vote + await Vote.insert({ + created_at: new Date(), + post_id: post._id, + user_id: user._id, + choice: choice + }); + + // Send response + res(); + + const inc = {}; + inc[`poll.choices.${findWithAttr(post.poll.choices, 'id', choice)}.votes`] = 1; + + // Increment likes count + Post.update({ _id: post._id }, { + $inc: inc + }); + + // Notify + notify(post.user_id, user._id, 'poll_vote', { + post_id: post._id, + choice: choice + }); + }); + +function findWithAttr(array, attr, value) { + for (let i = 0; i < array.length; i += 1) { + if (array[i][attr] === value) { + return i; + } + } + return -1; +} diff --git a/src/api/endpoints/username/available.js b/src/api/endpoints/username/available.js deleted file mode 100644 index 8f4d8cf280..0000000000 --- a/src/api/endpoints/username/available.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import User from '../../models/user'; -import { validateUsername } from '../../models/user'; - -/** - * Check available username - * - * @param {any} params - * @return {Promise} - */ -module.exports = async (params) => - new Promise(async (res, rej) => -{ - // Get 'username' parameter - const username = params.username; - if (username == null || username == '') { - return rej('username-is-required'); - } - - // Validate username - if (!validateUsername(username)) { - return rej('invalid-username'); - } - - // Get exist - const exist = await User - .count({ - username_lower: username.toLowerCase() - }, { - limit: 1 - }); - - // Reply - res({ - available: exist === 0 - }); -}); diff --git a/src/api/endpoints/username/available.ts b/src/api/endpoints/username/available.ts new file mode 100644 index 0000000000..9a85644b69 --- /dev/null +++ b/src/api/endpoints/username/available.ts @@ -0,0 +1,35 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import User from '../../models/user'; +import { validateUsername } from '../../models/user'; + +/** + * Check available username + * + * @param {any} params + * @return {Promise} + */ +module.exports = async (params) => + new Promise(async (res, rej) => +{ + // Get 'username' parameter + const [username, usernameError] = it(params.username).expect.string().required().trim().validate(validateUsername).qed(); + if (usernameError) return rej('invalid username param'); + + // Get exist + const exist = await User + .count({ + username_lower: username.toLowerCase() + }, { + limit: 1 + }); + + // Reply + res({ + available: exist === 0 + }); +}); -- cgit v1.2.3-freya From 67f9c158d71c497f3f3889e10fa1587a9a038381 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 08:06:34 +0900 Subject: wip --- src/api/endpoints/drive.js | 40 ------------- src/api/endpoints/drive.ts | 40 +++++++++++++ src/api/endpoints/i.js | 25 --------- src/api/endpoints/i.ts | 25 +++++++++ src/api/endpoints/meta.js | 51 ----------------- src/api/endpoints/meta.ts | 51 +++++++++++++++++ src/api/endpoints/posts.js | 87 ----------------------------- src/api/endpoints/posts.ts | 76 +++++++++++++++++++++++++ src/api/endpoints/posts/favorites/create.ts | 2 +- src/api/endpoints/posts/favorites/delete.ts | 2 +- src/api/endpoints/users.js | 65 --------------------- src/api/endpoints/users.ts | 62 ++++++++++++++++++++ 12 files changed, 256 insertions(+), 270 deletions(-) delete mode 100644 src/api/endpoints/drive.js create mode 100644 src/api/endpoints/drive.ts delete mode 100644 src/api/endpoints/i.js create mode 100644 src/api/endpoints/i.ts delete mode 100644 src/api/endpoints/meta.js create mode 100644 src/api/endpoints/meta.ts delete mode 100644 src/api/endpoints/posts.js create mode 100644 src/api/endpoints/posts.ts delete mode 100644 src/api/endpoints/users.js create mode 100644 src/api/endpoints/users.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/drive.js b/src/api/endpoints/drive.js deleted file mode 100644 index d73de67f44..0000000000 --- a/src/api/endpoints/drive.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import DriveFile from '../models/drive-file'; - -/** - * Get drive information - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => { - // Calculate drive usage - const usage = ((await DriveFile - .aggregate([ - { $match: { user_id: user._id } }, - { - $project: { - datasize: true - } - }, - { - $group: { - _id: null, - usage: { $sum: '$datasize' } - } - } - ]))[0] || { - usage: 0 - }).usage; - - res({ - capacity: user.drive_capacity, - usage: usage - }); - }); diff --git a/src/api/endpoints/drive.ts b/src/api/endpoints/drive.ts new file mode 100644 index 0000000000..d73de67f44 --- /dev/null +++ b/src/api/endpoints/drive.ts @@ -0,0 +1,40 @@ +'use strict'; + +/** + * Module dependencies + */ +import DriveFile from '../models/drive-file'; + +/** + * Get drive information + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => { + // Calculate drive usage + const usage = ((await DriveFile + .aggregate([ + { $match: { user_id: user._id } }, + { + $project: { + datasize: true + } + }, + { + $group: { + _id: null, + usage: { $sum: '$datasize' } + } + } + ]))[0] || { + usage: 0 + }).usage; + + res({ + capacity: user.drive_capacity, + usage: usage + }); + }); diff --git a/src/api/endpoints/i.js b/src/api/endpoints/i.js deleted file mode 100644 index df8c0d0e00..0000000000 --- a/src/api/endpoints/i.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import serialize from '../serializers/user'; - -/** - * Show myself - * - * @param {any} params - * @param {any} user - * @param {any} app - * @param {Boolean} isSecure - * @return {Promise} - */ -module.exports = (params, user, _, isSecure) => - new Promise(async (res, rej) => -{ - // Serialize - res(await serialize(user, user, { - detail: true, - includeSecrets: isSecure - })); -}); diff --git a/src/api/endpoints/i.ts b/src/api/endpoints/i.ts new file mode 100644 index 0000000000..df8c0d0e00 --- /dev/null +++ b/src/api/endpoints/i.ts @@ -0,0 +1,25 @@ +'use strict'; + +/** + * Module dependencies + */ +import serialize from '../serializers/user'; + +/** + * Show myself + * + * @param {any} params + * @param {any} user + * @param {any} app + * @param {Boolean} isSecure + * @return {Promise} + */ +module.exports = (params, user, _, isSecure) => + new Promise(async (res, rej) => +{ + // Serialize + res(await serialize(user, user, { + detail: true, + includeSecrets: isSecure + })); +}); diff --git a/src/api/endpoints/meta.js b/src/api/endpoints/meta.js deleted file mode 100644 index 421ec01d0a..0000000000 --- a/src/api/endpoints/meta.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import prominence from 'prominence'; -import git from 'git-last-commit'; - -/** - * @swagger - * /meta: - * post: - * summary: Show the misskey's information - * responses: - * 200: - * description: Success - * schema: - * type: object - * properties: - * maintainer: - * description: maintainer's name - * type: string - * commit: - * description: latest commit's hash - * type: string - * secure: - * description: whether the server supports secure protocols - * type: boolean - * - * default: - * description: Failed - * schema: - * $ref: "#/definitions/Error" - */ - -/** - * Show core info - * - * @param {any} params - * @return {Promise} - */ -module.exports = (params) => - new Promise(async (res, rej) => { - const commit = await prominence(git).getLastCommit(); - - res({ - maintainer: config.maintainer, - commit: commit.shortHash, - secure: config.https.enable - }); - }); diff --git a/src/api/endpoints/meta.ts b/src/api/endpoints/meta.ts new file mode 100644 index 0000000000..421ec01d0a --- /dev/null +++ b/src/api/endpoints/meta.ts @@ -0,0 +1,51 @@ +'use strict'; + +/** + * Module dependencies + */ +import prominence from 'prominence'; +import git from 'git-last-commit'; + +/** + * @swagger + * /meta: + * post: + * summary: Show the misskey's information + * responses: + * 200: + * description: Success + * schema: + * type: object + * properties: + * maintainer: + * description: maintainer's name + * type: string + * commit: + * description: latest commit's hash + * type: string + * secure: + * description: whether the server supports secure protocols + * type: boolean + * + * default: + * description: Failed + * schema: + * $ref: "#/definitions/Error" + */ + +/** + * Show core info + * + * @param {any} params + * @return {Promise} + */ +module.exports = (params) => + new Promise(async (res, rej) => { + const commit = await prominence(git).getLastCommit(); + + res({ + maintainer: config.maintainer, + commit: commit.shortHash, + secure: config.https.enable + }); + }); diff --git a/src/api/endpoints/posts.js b/src/api/endpoints/posts.js deleted file mode 100644 index 42294a39c8..0000000000 --- a/src/api/endpoints/posts.js +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import Post from '../models/post'; -import serialize from '../serializers/post'; - -/** - * Lists all posts - * - * @param {any} params - * @return {Promise} - */ -module.exports = (params) => - new Promise(async (res, rej) => { - // Get 'include_replies' parameter - let includeReplies = params.include_replies; - if (includeReplies === true) { - includeReplies = true; - } else { - includeReplies = false; - } - - // Get 'include_reposts' parameter - let includeReposts = params.include_reposts; - if (includeReposts === true) { - includeReposts = true; - } else { - includeReposts = false; - } - - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } - - const since = params.since_id || null; - const max = params.max_id || null; - - // Check if both of since_id and max_id is specified - if (since !== null && max !== null) { - return rej('cannot set since_id and max_id'); - } - - // Construct query - const sort = { - _id: -1 - }; - const query = {}; - if (since !== null) { - sort._id = 1; - query._id = { - $gt: new mongo.ObjectID(since) - }; - } else if (max !== null) { - query._id = { - $lt: new mongo.ObjectID(max) - }; - } - - if (!includeReplies) { - query.reply_to_id = null; - } - - if (!includeReposts) { - query.repost_id = null; - } - - // Issue query - const posts = await Post - .find(query, { - limit: limit, - sort: sort - }); - - // Serialize - res(await Promise.all(posts.map(async post => await serialize(post)))); - }); diff --git a/src/api/endpoints/posts.ts b/src/api/endpoints/posts.ts new file mode 100644 index 0000000000..458f7d3ded --- /dev/null +++ b/src/api/endpoints/posts.ts @@ -0,0 +1,76 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../it'; +import Post from '../models/post'; +import serialize from '../serializers/post'; + +/** + * Lists all posts + * + * @param {any} params + * @return {Promise} + */ +module.exports = (params) => + new Promise(async (res, rej) => { + // Get 'include_replies' parameter + const [includeReplies, includeRepliesErr] = it(params.include_replies).expect.boolean().default(true).qed(); + if (includeRepliesErr) return rej('invalid include_replies param'); + + // Get 'include_reposts' parameter + const [includeReposts, includeRepostsErr] = it(params.include_reposts).expect.boolean().default(true).qed(); + if (includeRepostsErr) return rej('invalid include_reposts param'); + + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); + + // Get 'max_id' parameter + const [maxId, maxIdErr] = it(params.max_id).expect.id().qed(); + if (maxIdErr) return rej('invalid max_id param'); + + // Check if both of since_id and max_id is specified + if (sinceId !== null && maxId !== null) { + return rej('cannot set since_id and max_id'); + } + + // Construct query + const sort = { + _id: -1 + }; + const query = {} as any; + if (sinceId) { + sort._id = 1; + query._id = { + $gt: sinceId + }; + } else if (maxId) { + query._id = { + $lt: maxId + }; + } + + if (!includeReplies) { + query.reply_to_id = null; + } + + if (!includeReposts) { + query.repost_id = null; + } + + // Issue query + const posts = await Post + .find(query, { + limit: limit, + sort: sort + }); + + // Serialize + res(await Promise.all(posts.map(async post => await serialize(post)))); + }); diff --git a/src/api/endpoints/posts/favorites/create.ts b/src/api/endpoints/posts/favorites/create.ts index 5be338593c..45a347ebb3 100644 --- a/src/api/endpoints/posts/favorites/create.ts +++ b/src/api/endpoints/posts/favorites/create.ts @@ -22,7 +22,7 @@ module.exports = (params, user) => // Get favoritee const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { diff --git a/src/api/endpoints/posts/favorites/delete.ts b/src/api/endpoints/posts/favorites/delete.ts index 4dfd761589..df11215903 100644 --- a/src/api/endpoints/posts/favorites/delete.ts +++ b/src/api/endpoints/posts/favorites/delete.ts @@ -22,7 +22,7 @@ module.exports = (params, user) => // Get favoritee const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { diff --git a/src/api/endpoints/users.js b/src/api/endpoints/users.js deleted file mode 100644 index 63e28caa46..0000000000 --- a/src/api/endpoints/users.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import User from '../models/user'; -import serialize from '../serializers/user'; - -/** - * Lists all users - * - * @param {any} params - * @param {any} me - * @return {Promise} - */ -module.exports = (params, me) => - new Promise(async (res, rej) => { - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } - - const since = params.since_id || null; - const max = params.max_id || null; - - // Check if both of since_id and max_id is specified - if (since !== null && max !== null) { - return rej('cannot set since_id and max_id'); - } - - // Construct query - const sort = { - _id: -1 - }; - const query = {}; - if (since !== null) { - sort._id = 1; - query._id = { - $gt: new mongo.ObjectID(since) - }; - } else if (max !== null) { - query._id = { - $lt: new mongo.ObjectID(max) - }; - } - - // Issue query - const users = await User - .find(query, { - limit: limit, - sort: sort - }); - - // Serialize - res(await Promise.all(users.map(async user => - await serialize(user, me)))); - }); diff --git a/src/api/endpoints/users.ts b/src/api/endpoints/users.ts new file mode 100644 index 0000000000..74c4754fed --- /dev/null +++ b/src/api/endpoints/users.ts @@ -0,0 +1,62 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../it'; +import User from '../models/user'; +import serialize from '../serializers/user'; + +/** + * Lists all users + * + * @param {any} params + * @param {any} me + * @return {Promise} + */ +module.exports = (params, me) => + new Promise(async (res, rej) => { + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); + + // Get 'max_id' parameter + const [maxId, maxIdErr] = it(params.max_id).expect.id().qed(); + if (maxIdErr) return rej('invalid max_id param'); + + // Check if both of since_id and max_id is specified + if (sinceId !== null && maxId !== null) { + return rej('cannot set since_id and max_id'); + } + + // Construct query + const sort = { + _id: -1 + }; + const query = {} as any; + if (sinceId) { + sort._id = 1; + query._id = { + $gt: sinceId + }; + } else if (maxId) { + query._id = { + $lt: maxId + }; + } + + // Issue query + const users = await User + .find(query, { + limit: limit, + sort: sort + }); + + // Serialize + res(await Promise.all(users.map(async user => + await serialize(user, me)))); + }); -- cgit v1.2.3-freya From dc45055f2ffcea2369f12d104999746220b22c90 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 08:56:07 +0900 Subject: wip --- src/api/endpoints/i/appdata/get.js | 53 --------------- src/api/endpoints/i/appdata/get.ts | 53 +++++++++++++++ src/api/endpoints/i/appdata/set.js | 61 ----------------- src/api/endpoints/i/appdata/set.ts | 61 +++++++++++++++++ src/api/endpoints/i/authorized_apps.js | 59 ---------------- src/api/endpoints/i/authorized_apps.ts | 47 +++++++++++++ src/api/endpoints/i/favorites.js | 59 ---------------- src/api/endpoints/i/favorites.ts | 48 +++++++++++++ src/api/endpoints/i/notifications.js | 117 -------------------------------- src/api/endpoints/i/notifications.ts | 111 ++++++++++++++++++++++++++++++ src/api/endpoints/i/signin_history.js | 70 ------------------- src/api/endpoints/i/signin_history.ts | 66 ++++++++++++++++++ src/api/endpoints/i/update.js | 119 --------------------------------- src/api/endpoints/i/update.ts | 110 ++++++++++++++++++++++++++++++ src/api/endpoints/posts/create.ts | 19 +++--- src/api/it.ts | 78 ++++++++++----------- 16 files changed, 539 insertions(+), 592 deletions(-) delete mode 100644 src/api/endpoints/i/appdata/get.js create mode 100644 src/api/endpoints/i/appdata/get.ts delete mode 100644 src/api/endpoints/i/appdata/set.js create mode 100644 src/api/endpoints/i/appdata/set.ts delete mode 100644 src/api/endpoints/i/authorized_apps.js create mode 100644 src/api/endpoints/i/authorized_apps.ts delete mode 100644 src/api/endpoints/i/favorites.js create mode 100644 src/api/endpoints/i/favorites.ts delete mode 100644 src/api/endpoints/i/notifications.js create mode 100644 src/api/endpoints/i/notifications.ts delete mode 100644 src/api/endpoints/i/signin_history.js create mode 100644 src/api/endpoints/i/signin_history.ts delete mode 100644 src/api/endpoints/i/update.js create mode 100644 src/api/endpoints/i/update.ts (limited to 'src/api/endpoints/posts') diff --git a/src/api/endpoints/i/appdata/get.js b/src/api/endpoints/i/appdata/get.js deleted file mode 100644 index 7f1bdf0713..0000000000 --- a/src/api/endpoints/i/appdata/get.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import Appdata from '../../../models/appdata'; - -/** - * Get app data - * - * @param {any} params - * @param {any} user - * @param {any} app - * @param {Boolean} isSecure - * @return {Promise} - */ -module.exports = (params, user, app, isSecure) => - new Promise(async (res, rej) => -{ - // Get 'key' parameter - let key = params.key; - if (key === undefined) { - key = null; - } - - if (isSecure) { - if (!user.data) { - return res(); - } - if (key !== null) { - const data = {}; - data[key] = user.data[key]; - res(data); - } else { - res(user.data); - } - } else { - const select = {}; - if (key !== null) { - select['data.' + key] = true; - } - const appdata = await Appdata.findOne({ - app_id: app._id, - user_id: user._id - }, select); - - if (appdata) { - res(appdata.data); - } else { - res(); - } - } -}); diff --git a/src/api/endpoints/i/appdata/get.ts b/src/api/endpoints/i/appdata/get.ts new file mode 100644 index 0000000000..7f1bdf0713 --- /dev/null +++ b/src/api/endpoints/i/appdata/get.ts @@ -0,0 +1,53 @@ +'use strict'; + +/** + * Module dependencies + */ +import Appdata from '../../../models/appdata'; + +/** + * Get app data + * + * @param {any} params + * @param {any} user + * @param {any} app + * @param {Boolean} isSecure + * @return {Promise} + */ +module.exports = (params, user, app, isSecure) => + new Promise(async (res, rej) => +{ + // Get 'key' parameter + let key = params.key; + if (key === undefined) { + key = null; + } + + if (isSecure) { + if (!user.data) { + return res(); + } + if (key !== null) { + const data = {}; + data[key] = user.data[key]; + res(data); + } else { + res(user.data); + } + } else { + const select = {}; + if (key !== null) { + select['data.' + key] = true; + } + const appdata = await Appdata.findOne({ + app_id: app._id, + user_id: user._id + }, select); + + if (appdata) { + res(appdata.data); + } else { + res(); + } + } +}); diff --git a/src/api/endpoints/i/appdata/set.js b/src/api/endpoints/i/appdata/set.js deleted file mode 100644 index 57001f4e8b..0000000000 --- a/src/api/endpoints/i/appdata/set.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import Appdata from '../../../models/appdata'; -import User from '../../../models/user'; -import serialize from '../../../serializers/user'; -import event from '../../../event'; - -/** - * Set app data - * - * @param {any} params - * @param {any} user - * @param {any} app - * @param {Boolean} isSecure - * @return {Promise} - */ -module.exports = (params, user, app, isSecure) => - new Promise(async (res, rej) => -{ - const data = params.data; - if (data == null) { - return rej('data is required'); - } - - if (isSecure) { - const _user = await User.findOneAndUpdate(user._id, { - $set: { - data: Object.assign(user.data || {}, JSON.parse(data)) - } - }); - res(204); - - // Publish i updated event - event(user._id, 'i_updated', await serialize(_user, user, { - detail: true, - includeSecrets: true - })); - } else { - const appdata = await Appdata.findOne({ - app_id: app._id, - user_id: user._id - }); - await Appdata.update({ - app_id: app._id, - user_id: user._id - }, Object.assign({ - app_id: app._id, - user_id: user._id - }, { - $set: { - data: Object.assign((appdata || {}).data || {}, JSON.parse(data)) - } - }), { - upsert: true - }); - res(204); - } -}); diff --git a/src/api/endpoints/i/appdata/set.ts b/src/api/endpoints/i/appdata/set.ts new file mode 100644 index 0000000000..57001f4e8b --- /dev/null +++ b/src/api/endpoints/i/appdata/set.ts @@ -0,0 +1,61 @@ +'use strict'; + +/** + * Module dependencies + */ +import Appdata from '../../../models/appdata'; +import User from '../../../models/user'; +import serialize from '../../../serializers/user'; +import event from '../../../event'; + +/** + * Set app data + * + * @param {any} params + * @param {any} user + * @param {any} app + * @param {Boolean} isSecure + * @return {Promise} + */ +module.exports = (params, user, app, isSecure) => + new Promise(async (res, rej) => +{ + const data = params.data; + if (data == null) { + return rej('data is required'); + } + + if (isSecure) { + const _user = await User.findOneAndUpdate(user._id, { + $set: { + data: Object.assign(user.data || {}, JSON.parse(data)) + } + }); + res(204); + + // Publish i updated event + event(user._id, 'i_updated', await serialize(_user, user, { + detail: true, + includeSecrets: true + })); + } else { + const appdata = await Appdata.findOne({ + app_id: app._id, + user_id: user._id + }); + await Appdata.update({ + app_id: app._id, + user_id: user._id + }, Object.assign({ + app_id: app._id, + user_id: user._id + }, { + $set: { + data: Object.assign((appdata || {}).data || {}, JSON.parse(data)) + } + }), { + upsert: true + }); + res(204); + } +}); diff --git a/src/api/endpoints/i/authorized_apps.js b/src/api/endpoints/i/authorized_apps.js deleted file mode 100644 index 3c0cf75057..0000000000 --- a/src/api/endpoints/i/authorized_apps.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import AccessToken from '../../models/access-token'; -import serialize from '../../serializers/app'; - -/** - * Get authorized apps of my account - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => -{ - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // 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; - } - - // Get 'sort' parameter - let sort = params.sort || 'desc'; - - // Get tokens - const tokens = await AccessToken - .find({ - user_id: user._id - }, { - limit: limit, - skip: offset, - sort: { - _id: sort == 'asc' ? 1 : -1 - } - }); - - // Serialize - res(await Promise.all(tokens.map(async token => - await serialize(token.app_id)))); -}); diff --git a/src/api/endpoints/i/authorized_apps.ts b/src/api/endpoints/i/authorized_apps.ts new file mode 100644 index 0000000000..fb56a107e7 --- /dev/null +++ b/src/api/endpoints/i/authorized_apps.ts @@ -0,0 +1,47 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import AccessToken from '../../models/access-token'; +import serialize from '../../serializers/app'; + +/** + * Get authorized apps of my account + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'offset' parameter + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); + + // Get 'sort' parameter + const [sort, sortError] = it(params.sort).expect.string().or('desc asc').default('desc').qed(); + if (sortError) return rej('invalid sort param'); + + // Get tokens + const tokens = await AccessToken + .find({ + user_id: user._id + }, { + limit: limit, + skip: offset, + sort: { + _id: sort == 'asc' ? 1 : -1 + } + }); + + // Serialize + res(await Promise.all(tokens.map(async token => + await serialize(token.app_id)))); +}); diff --git a/src/api/endpoints/i/favorites.js b/src/api/endpoints/i/favorites.js deleted file mode 100644 index 28e402e366..0000000000 --- a/src/api/endpoints/i/favorites.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Favorite from '../../models/favorite'; -import serialize from '../../serializers/post'; - -/** - * Get followers of a user - * - * @param {any} params - * @return {Promise} - */ -module.exports = (params) => - new Promise(async (res, rej) => -{ - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // 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; - } - - // Get 'sort' parameter - let sort = params.sort || 'desc'; - - // Get favorites - const favorites = await Favorites - .find({ - user_id: user._id - }, { - limit: limit, - skip: offset, - sort: { - _id: sort == 'asc' ? 1 : -1 - } - }); - - // Serialize - res(await Promise.all(favorites.map(async favorite => - await serialize(favorite.post) - ))); -}); diff --git a/src/api/endpoints/i/favorites.ts b/src/api/endpoints/i/favorites.ts new file mode 100644 index 0000000000..c04d318379 --- /dev/null +++ b/src/api/endpoints/i/favorites.ts @@ -0,0 +1,48 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import Favorite from '../../models/favorite'; +import serialize from '../../serializers/post'; + +/** + * Get followers of a user + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'offset' parameter + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); + + // Get 'sort' parameter + const [sort, sortError] = it(params.sort).expect.string().or('desc asc').default('desc').qed(); + if (sortError) return rej('invalid sort param'); + + // Get favorites + const favorites = await Favorite + .find({ + user_id: user._id + }, { + limit: limit, + skip: offset, + sort: { + _id: sort == 'asc' ? 1 : -1 + } + }); + + // Serialize + res(await Promise.all(favorites.map(async favorite => + await serialize(favorite.post) + ))); +}); diff --git a/src/api/endpoints/i/notifications.js b/src/api/endpoints/i/notifications.js deleted file mode 100644 index d5174439e2..0000000000 --- a/src/api/endpoints/i/notifications.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Notification from '../../models/notification'; -import serialize from '../../serializers/notification'; -import getFriends from '../../common/get-friends'; - -/** - * Get notifications - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => -{ - // Get 'following' parameter - const following = params.following; - - // Get 'mark_as_read' parameter - let markAsRead = params.mark_as_read; - if (markAsRead == null) { - markAsRead = true; - } - - // Get 'type' parameter - let type = params.type; - if (type !== undefined && type !== null) { - type = type.split(',').map(x => x.trim()); - } - - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } - - const since = params.since_id || null; - const max = params.max_id || null; - - // Check if both of since_id and max_id is specified - if (since !== null && max !== null) { - return rej('cannot set since_id and max_id'); - } - - const query = { - notifiee_id: user._id - }; - - const sort = { - _id: -1 - }; - - if (following) { - // ID list of the user itself and other users who the user follows - const followingIds = await getFriends(user._id); - - query.notifier_id = { - $in: followingIds - }; - } - - if (type) { - query.type = { - $in: type - }; - } - - if (since !== null) { - sort._id = 1; - query._id = { - $gt: new mongo.ObjectID(since) - }; - } else if (max !== null) { - query._id = { - $lt: new mongo.ObjectID(max) - }; - } - - // Issue query - const notifications = await Notification - .find(query, { - limit: limit, - sort: sort - }); - - // Serialize - res(await Promise.all(notifications.map(async notification => - await serialize(notification)))); - - // Mark as read all - if (notifications.length > 0 && markAsRead) { - const ids = notifications - .filter(x => x.is_read == false) - .map(x => x._id); - - // Update documents - await Notification.update({ - _id: { $in: ids } - }, { - $set: { is_read: true } - }, { - multi: true - }); - } -}); diff --git a/src/api/endpoints/i/notifications.ts b/src/api/endpoints/i/notifications.ts new file mode 100644 index 0000000000..21537ea799 --- /dev/null +++ b/src/api/endpoints/i/notifications.ts @@ -0,0 +1,111 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import Notification from '../../models/notification'; +import serialize from '../../serializers/notification'; +import getFriends from '../../common/get-friends'; + +/** + * Get notifications + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'following' parameter + const [following, followingError] = + it(params.following).expect.boolean().default(false).qed(); + if (followingError) return rej('invalid following param'); + + // Get 'mark_as_read' parameter + const [markAsRead, markAsReadErr] = it(params.mark_as_read).expect.boolean().default(true).qed(); + if (markAsReadErr) return rej('invalid mark_as_read param'); + + // Get 'type' parameter + const [type, typeErr] = it(params.type).expect.array().unique().allString().qed(); + if (typeErr) return rej('invalid type param'); + + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); + + // Get 'max_id' parameter + const [maxId, maxIdErr] = it(params.max_id).expect.id().qed(); + if (maxIdErr) return rej('invalid max_id param'); + + // Check if both of since_id and max_id is specified + if (sinceId !== null && maxId !== null) { + return rej('cannot set since_id and max_id'); + } + + const query = { + notifiee_id: user._id + } as any; + + const sort = { + _id: -1 + }; + + if (following) { + // ID list of the user itself and other users who the user follows + const followingIds = await getFriends(user._id); + + query.notifier_id = { + $in: followingIds + }; + } + + if (type) { + query.type = { + $in: type + }; + } + + if (sinceId) { + sort._id = 1; + query._id = { + $gt: sinceId + }; + } else if (maxId) { + query._id = { + $lt: maxId + }; + } + + // Issue query + const notifications = await Notification + .find(query, { + limit: limit, + sort: sort + }); + + // Serialize + res(await Promise.all(notifications.map(async notification => + await serialize(notification)))); + + // Mark as read all + if (notifications.length > 0 && markAsRead) { + const ids = notifications + .filter(x => x.is_read == false) + .map(x => x._id); + + // Update documents + await Notification.update({ + _id: { $in: ids } + }, { + $set: { is_read: true } + }, { + multi: true + }); + } +}); diff --git a/src/api/endpoints/i/signin_history.js b/src/api/endpoints/i/signin_history.js deleted file mode 100644 index ede821e3cf..0000000000 --- a/src/api/endpoints/i/signin_history.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import Signin from '../../models/signin'; -import serialize from '../../serializers/signin'; - -/** - * Get signin history of my account - * - * @param {any} params - * @param {any} user - * @return {Promise} - */ -module.exports = (params, user) => - new Promise(async (res, rej) => -{ - // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); - - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } - - const since = params.since_id || null; - const max = params.max_id || null; - - // Check if both of since_id and max_id is specified - if (since !== null && max !== null) { - return rej('cannot set since_id and max_id'); - } - - const query = { - user_id: user._id - }; - - const sort = { - _id: -1 - }; - - if (since !== null) { - sort._id = 1; - query._id = { - $gt: new mongo.ObjectID(since) - }; - } else if (max !== null) { - query._id = { - $lt: new mongo.ObjectID(max) - }; - } - - // Issue query - const history = await Signin - .find(query, { - limit: limit, - sort: sort - }); - - // Serialize - res(await Promise.all(history.map(async record => - await serialize(record)))); -}); diff --git a/src/api/endpoints/i/signin_history.ts b/src/api/endpoints/i/signin_history.ts new file mode 100644 index 0000000000..db36438bfe --- /dev/null +++ b/src/api/endpoints/i/signin_history.ts @@ -0,0 +1,66 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import Signin from '../../models/signin'; +import serialize from '../../serializers/signin'; + +/** + * Get signin history of my account + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'limit' parameter + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); + + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); + + // Get 'max_id' parameter + const [maxId, maxIdErr] = it(params.max_id).expect.id().qed(); + if (maxIdErr) return rej('invalid max_id param'); + + // Check if both of since_id and max_id is specified + if (sinceId !== null && maxId !== null) { + return rej('cannot set since_id and max_id'); + } + + const query = { + user_id: user._id + } as any; + + const sort = { + _id: -1 + }; + + if (sinceId) { + sort._id = 1; + query._id = { + $gt: sinceId + }; + } else if (maxId) { + query._id = { + $lt: maxId + }; + } + + // Issue query + const history = await Signin + .find(query, { + limit: limit, + sort: sort + }); + + // Serialize + res(await Promise.all(history.map(async record => + await serialize(record)))); +}); diff --git a/src/api/endpoints/i/update.js b/src/api/endpoints/i/update.js deleted file mode 100644 index 4abb4fcb7b..0000000000 --- a/src/api/endpoints/i/update.js +++ /dev/null @@ -1,119 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ -import * as mongo from 'mongodb'; -import User from '../../models/user'; -import { isValidName, isValidBirthday } from '../../models/user'; -import serialize from '../../serializers/user'; -import event from '../../event'; -import config from '../../../conf'; - -/** - * Update myself - * - * @param {any} params - * @param {any} user - * @param {any} _ - * @param {boolean} isSecure - * @return {Promise} - */ -module.exports = async (params, user, _, isSecure) => - new Promise(async (res, rej) => -{ - // Get 'name' parameter - const name = params.name; - if (name !== undefined && name !== null) { - if (typeof name != 'string') { - return rej('name must be a string'); - } - - if (!isValidName(name)) { - return rej('invalid name'); - } - - user.name = name; - } - - // Get 'description' parameter - const description = params.description; - if (description !== undefined && description !== null) { - if (description.length > 500) { - return rej('too long description'); - } - - user.description = description; - } - - // Get 'location' parameter - const location = params.location; - if (location !== undefined && location !== null) { - if (location.length > 50) { - return rej('too long location'); - } - - user.profile.location = location; - } - - // Get 'birthday' parameter - const birthday = params.birthday; - if (birthday != null) { - if (!isValidBirthday(birthday)) { - return rej('invalid birthday'); - } - - user.profile.birthday = birthday; - } else { - user.profile.birthday = null; - } - - // Get 'avatar_id' parameter - const avatar = params.avatar_id; - if (avatar !== undefined && avatar !== null) { - user.avatar_id = new mongo.ObjectID(avatar); - } - - // Get 'banner_id' parameter - const banner = params.banner_id; - if (banner !== undefined && banner !== null) { - user.banner_id = new mongo.ObjectID(banner); - } - - await User.update(user._id, { - $set: { - name: user.name, - description: user.description, - avatar_id: user.avatar_id, - banner_id: user.banner_id, - profile: user.profile - } - }); - - // Serialize - const iObj = await serialize(user, user, { - detail: true, - includeSecrets: isSecure - }); - - // Send response - res(iObj); - - // Publish i updated event - event(user._id, 'i_updated', iObj); - - // Update search index - if (config.elasticsearch.enable) { - const es = require('../../../db/elasticsearch'); - - es.index({ - index: 'misskey', - type: 'user', - id: user._id.toString(), - body: { - name: user.name, - bio: user.bio - } - }); - } -}); diff --git a/src/api/endpoints/i/update.ts b/src/api/endpoints/i/update.ts new file mode 100644 index 0000000000..1e46315ceb --- /dev/null +++ b/src/api/endpoints/i/update.ts @@ -0,0 +1,110 @@ +'use strict'; + +/** + * Module dependencies + */ +import it from '../../it'; +import User from '../../models/user'; +import { isValidName, isValidBirthday } from '../../models/user'; +import serialize from '../../serializers/user'; +import event from '../../event'; +import config from '../../../conf'; + +/** + * Update myself + * + * @param {any} params + * @param {any} user + * @param {any} _ + * @param {boolean} isSecure + * @return {Promise} + */ +module.exports = async (params, user, _, isSecure) => + new Promise(async (res, rej) => +{ + // Get 'name' parameter + const [name, nameErr] = it(params.name).expect.string().validate(isValidName).qed(); + if (nameErr) return rej('invalid name param'); + user.name = name; + + // Get 'description' parameter + const description = params.description; + if (description !== undefined && description !== null) { + if (description.length > 500) { + return rej('too long description'); + } + + user.description = description; + } + + // Get 'location' parameter + const location = params.location; + if (location !== undefined && location !== null) { + if (location.length > 50) { + return rej('too long location'); + } + + user.profile.location = location; + } + + // Get 'birthday' parameter + const birthday = params.birthday; + if (birthday != null) { + if (!isValidBirthday(birthday)) { + return rej('invalid birthday'); + } + + user.profile.birthday = birthday; + } else { + user.profile.birthday = null; + } + + // Get 'avatar_id' parameter + const avatar = params.avatar_id; + if (avatar !== undefined && avatar !== null) { + user.avatar_id = new mongo.ObjectID(avatar); + } + + // Get 'banner_id' parameter + const banner = params.banner_id; + if (banner !== undefined && banner !== null) { + user.banner_id = new mongo.ObjectID(banner); + } + + await User.update(user._id, { + $set: { + name: user.name, + description: user.description, + avatar_id: user.avatar_id, + banner_id: user.banner_id, + profile: user.profile + } + }); + + // Serialize + const iObj = await serialize(user, user, { + detail: true, + includeSecrets: isSecure + }); + + // Send response + res(iObj); + + // Publish i updated event + event(user._id, 'i_updated', iObj); + + // Update search index + if (config.elasticsearch.enable) { + const es = require('../../../db/elasticsearch'); + + es.index({ + index: 'misskey', + type: 'user', + id: user._id.toString(), + body: { + name: user.name, + bio: user.bio + } + }); + } +}); diff --git a/src/api/endpoints/posts/create.ts b/src/api/endpoints/posts/create.ts index 686c3a67d0..3dc121305c 100644 --- a/src/api/endpoints/posts/create.ts +++ b/src/api/endpoints/posts/create.ts @@ -131,21 +131,18 @@ module.exports = (params, user, app) => let poll = null; if (_poll !== null) { - const [pollChoices, pollChoicesErr] = it(params.poll, 'set', false, [ - choices => { - const shouldReject = choices.some(choice => { + const [pollChoices, pollChoicesErr] = + it(params.poll).expect.array() + .unique() + .allString() + .range(1, 10) + .validate(choices => !choices.some(choice => { if (typeof choice != 'string') return true; if (choice.trim().length == 0) return true; if (choice.trim().length > 50) return true; return false; - }); - return shouldReject ? new Error('invalid poll choices') : true; - }, - // 選択肢がひとつならエラー - choices => choices.length == 1 ? new Error('poll choices must be ひとつ以上') : true, - // 選択肢が多すぎてもエラー - choices => choices.length > 10 ? new Error('many poll choices') : true, - ]); + })) + .qed(); if (pollChoicesErr) return rej('invalid poll choices'); _poll.choices = pollChoices.map((choice, i) => ({ diff --git a/src/api/it.ts b/src/api/it.ts index 039f879957..b08612c709 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -48,23 +48,27 @@ class QueryCore implements Query { value: any; error: Error; - constructor() { - this.value = null; + constructor(value: any) { + this.value = value; this.error = null; } + get isEmpty() { + return this.value === undefined || this.value === null; + } + /** - * このインスタンスの値が null、またはエラーが存在しているなどして、処理をスキップするべきか否か + * このインスタンスの値が空、またはエラーが存在しているなどして、処理をスキップするべきか否か */ get shouldSkip() { - return this.error !== null || this.value === null; + return this.error !== null || this.isEmpty; } /** - * このインスタンスの値が undefined または null の場合エラーにします + * このインスタンスの値が空の場合エラーにします */ required() { - if (this.error === null && this.value === null) { + if (this.error === null && this.isEmpty) { this.error = new Error('required'); } return this; @@ -74,7 +78,7 @@ class QueryCore implements Query { * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します */ default(value: any) { - if (this.value === null) { + if (this.isEmpty) { this.value = value; } return this; @@ -109,13 +113,9 @@ class BooleanQuery extends QueryCore { error: Error; constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (typeof value != 'boolean') { + super(value); + if (!this.isEmpty && typeof value != 'boolean') { this.error = new Error('must-be-a-boolean'); - } else { - this.value = value; } } @@ -155,13 +155,9 @@ class NumberQuery extends QueryCore { error: Error; constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (!Number.isFinite(value)) { + super(value); + if (!this.isEmpty && !Number.isFinite(value)) { this.error = new Error('must-be-a-number'); - } else { - this.value = value; } } @@ -238,13 +234,9 @@ class StringQuery extends QueryCore { error: Error; constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (typeof value != 'string') { + super(value); + if (!this.isEmpty && typeof value != 'string') { this.error = new Error('must-be-a-string'); - } else { - this.value = value; } } @@ -327,13 +319,9 @@ class ArrayQuery extends QueryCore { error: Error; constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (!Array.isArray(value)) { + super(value); + if (!this.isEmpty && !Array.isArray(value)) { this.error = new Error('must-be-an-array'); - } else { - this.value = value; } } @@ -361,6 +349,18 @@ class ArrayQuery extends QueryCore { return this; } + /** + * このインスタンスの配列内の要素すべてが文字列であるか検証します + * ひとつでも文字列以外の要素が存在する場合エラーにします + */ + allString() { + if (this.shouldSkip) return this; + if (this.value.some(x => typeof x != 'string')) { + this.error = new Error('dirty-array'); + } + return this; + } + /** * このインスタンスの値が undefined または null の場合エラーにします */ @@ -397,13 +397,9 @@ class IdQuery extends QueryCore { error: Error; constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (typeof value != 'string' || !mongo.ObjectID.isValid(value)) { + super(value); + if (!this.isEmpty && (typeof value != 'string' || !mongo.ObjectID.isValid(value))) { this.error = new Error('must-be-an-id'); - } else { - this.value = new mongo.ObjectID(value); } } @@ -443,13 +439,9 @@ class ObjectQuery extends QueryCore { error: Error; constructor(value) { - super(); - if (value === undefined || value === null) { - this.value = null; - } else if (typeof value != 'object') { + super(value); + if (!this.isEmpty && typeof value != 'object') { this.error = new Error('must-be-an-object'); - } else { - this.value = value; } } -- cgit v1.2.3-freya