From 73deef0ca7038f9a88f9cb36e6c1b17c354a3a35 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 01:06:16 +0900 Subject: [PATCH 01/43] wip --- src/api/validator.ts | 53 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/api/validator.ts diff --git a/src/api/validator.ts b/src/api/validator.ts new file mode 100644 index 0000000000..d75fe6420b --- /dev/null +++ b/src/api/validator.ts @@ -0,0 +1,53 @@ +import * as mongo from 'mongodb'; + +type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'object'; + +export default (value: any, isRequired: boolean, type: Type): [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-an-boolean']; + } + break; + + case 'array': + if (!Array.isArray(value)) { + return [null, 'must-be-an-array']; + } + break; + + case 'object': + if (typeof value != 'object') { + return [null, 'must-be-an-onject']; + } + break; + } + + return [value, null]; +}; From 6256a8bdfc009aca0d737a4c7b1e45f6450b6db4 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 01:11:30 +0900 Subject: [PATCH 02/43] Custom validator support --- src/api/validator.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/api/validator.ts b/src/api/validator.ts index d75fe6420b..2562535c02 100644 --- a/src/api/validator.ts +++ b/src/api/validator.ts @@ -2,7 +2,7 @@ import * as mongo from 'mongodb'; type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'object'; -export default (value: any, isRequired: boolean, type: Type): [T, string] => { +export default (value: any, isRequired: boolean, type: Type, validator?: (any) => boolean): [T, string] => { if (value === undefined || value === null) { if (isRequired) { return [null, 'is-required'] @@ -49,5 +49,11 @@ export default (value: any, isRequired: boolean, type: Type): [T, string] => break; } + if (validator) { + if (!validator(value)) { + return [null, 'invalid-format']; + } + } + return [value, null]; }; From a53edc96bec3503517daa24837def5d3ecd82624 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 03:16:39 +0900 Subject: [PATCH 03/43] wip --- src/api/endpoints/posts/create.js | 40 ++++++++++--------------------- src/api/models/post.ts | 4 ++++ src/api/validator.ts | 26 ++++++++++++++++---- 3 files changed, 39 insertions(+), 31 deletions(-) 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'); } diff --git a/src/api/models/post.ts b/src/api/models/post.ts index ab29187251..baab63f991 100644 --- a/src/api/models/post.ts +++ b/src/api/models/post.ts @@ -1,3 +1,7 @@ import db from '../../db/mongodb'; export default db.get('posts') as any; // fuck type definition + +export function isValidText(text: string): boolean { + return text.length <= 1000 && text.trim() != ''; +} diff --git a/src/api/validator.ts b/src/api/validator.ts index 2562535c02..830786a18d 100644 --- a/src/api/validator.ts +++ b/src/api/validator.ts @@ -2,7 +2,15 @@ import * as mongo from 'mongodb'; type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'object'; -export default (value: any, isRequired: boolean, type: Type, validator?: (any) => boolean): [T, string] => { +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: 'object', isRequired?: boolean, validator?: Validator): [Object, string]; +function validate(value: any, type: Type, isRequired?: boolean, validator?: Validator): [T, string] { if (value === undefined || value === null) { if (isRequired) { return [null, 'is-required'] @@ -49,11 +57,21 @@ export default (value: any, isRequired: boolean, type: Type, validator?: (any break; } + if (type == 'id') value = new mongo.ObjectID(value); + if (validator) { - if (!validator(value)) { - return [null, 'invalid-format']; + 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; From fd0ce15b1b08abc72f3b45de90d6a47657440983 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 05:11:37 +0900 Subject: [PATCH 04/43] wip --- src/api/endpoints/posts/create.js | 153 ++++++++++-------------------- 1 file changed, 48 insertions(+), 105 deletions(-) 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'); - } + const [_poll, pollErr] = validate(params.poll, 'object'); + if (pollErr) return rej('invalid poll'); - // 選択肢が配列でなかったらエラー - if (!Array.isArray(poll.choices)) { - return rej('poll choices must be an array'); - } + 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'); - // 選択肢が空の配列でエラー - 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) => ({ + _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'); } From 17c8969fd2ff51096fcde8d0ae272ca67202f55d Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 05:12:59 +0900 Subject: [PATCH 05/43] fix --- src/api/endpoints/posts/create.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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'); } From b3455bf1cb30beb46859345c482e6585845ca388 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 05:24:20 +0900 Subject: [PATCH 06/43] 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 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; From f3f5869f5214085637276b077ece739eac2e5dff Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 05:31:30 +0900 Subject: [PATCH 07/43] Add 'set' type --- src/api/endpoints/posts/create.js | 9 +++------ src/api/validator.ts | 12 +++++++++++- 2 files changed, 14 insertions(+), 7 deletions(-) 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']; From d009286b51456643ab311a0c30ffc95a24c48d76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?syuilo=E2=AD=90=EF=B8=8F?= Date: Thu, 2 Mar 2017 06:25:05 +0900 Subject: [PATCH 08/43] typo --- src/api/validator.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/validator.ts b/src/api/validator.ts index 3c426054e8..bc50da3a37 100644 --- a/src/api/validator.ts +++ b/src/api/validator.ts @@ -42,7 +42,7 @@ function validate(value: any, type: Type, isRequired?: boolean, validator?: V case 'boolean': if (typeof value != 'boolean') { - return [null, 'must-be-an-boolean']; + return [null, 'must-be-a-boolean']; } break; @@ -62,7 +62,7 @@ function validate(value: any, type: Type, isRequired?: boolean, validator?: V case 'object': if (typeof value != 'object') { - return [null, 'must-be-an-onject']; + return [null, 'must-be-an-object']; } break; } From 168039e68299029b11161b53f90cc103788c0cd3 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 15:25:27 +0900 Subject: [PATCH 09/43] :v: --- .../endpoints/posts/{create.js => create.ts} | 23 ++++++++++--------- src/api/validator.ts | 4 ++-- 2 files changed, 14 insertions(+), 13 deletions(-) rename src/api/endpoints/posts/{create.js => create.ts} (94%) diff --git a/src/api/endpoints/posts/create.js b/src/api/endpoints/posts/create.ts similarity index 94% rename from src/api/endpoints/posts/create.js rename to src/api/endpoints/posts/create.ts index eadc886c5c..0ecce4e9ad 100644 --- a/src/api/endpoints/posts/create.js +++ b/src/api/endpoints/posts/create.ts @@ -5,12 +5,12 @@ */ import validate from '../../validator'; import parse from '../../../common/text'; -import { Post, isValidText } from '../../models/post'; +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 createFile from '../../common/add-file-to-drive'; import notify from '../../common/notify'; import event from '../../event'; import config from '../../../conf'; @@ -139,6 +139,7 @@ module.exports = (params, user, app) => 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; }, @@ -167,7 +168,7 @@ module.exports = (params, user, app) => 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, + reply_to_id: inReplyToPost ? inReplyToPost._id : undefined, repost_id: repost ? repost._id : undefined, poll: poll ? poll : undefined, text: text, @@ -225,21 +226,21 @@ module.exports = (params, user, app) => }); // If has in reply to post - if (replyTo) { + if (inReplyToPost) { // Increment replies count - Post.update({ _id: replyTo._id }, { + Post.update({ _id: inReplyToPost._id }, { $inc: { replies_count: 1 } }); // 自分自身へのリプライでない限りは通知を作成 - notify(replyTo.user_id, user._id, 'reply', { + notify(inReplyToPost.user_id, user._id, 'reply', { post_id: post._id }); // Add mention - addMention(replyTo.user_id, 'reply'); + addMention(inReplyToPost.user_id, 'reply'); } // If it is repost @@ -284,7 +285,7 @@ module.exports = (params, user, app) => if (text) { // Analyze const tokens = parse(text); - +/* // Extract a hashtags const hashtags = tokens .filter(t => t.type == 'hashtag') @@ -293,8 +294,8 @@ module.exports = (params, user, app) => .filter((v, i, s) => s.indexOf(v) == i); // ハッシュタグをデータベースに登録 - //registerHashtags(user, hashtags); - + registerHashtags(user, hashtags); +*/ // Extract an '@' mentions const atMentions = tokens .filter(t => t.type == 'mention') @@ -315,7 +316,7 @@ module.exports = (params, user, app) => if (mentionee == null) return; // 既に言及されたユーザーに対する返信や引用repostの場合も無視 - if (replyTo && replyTo.user_id.equals(mentionee._id)) return; + if (inReplyToPost && inReplyToPost.user_id.equals(mentionee._id)) return; if (repost && repost.user_id.equals(mentionee._id)) return; // Add mention 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) { From 7f4db37ff43e4a6efb4241cf84e328bbd3369b1b Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 17:07:34 +0900 Subject: [PATCH 10/43] wip --- src/api/validator2.ts | 99 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 src/api/validator2.ts diff --git a/src/api/validator2.ts b/src/api/validator2.ts new file mode 100644 index 0000000000..057875f80b --- /dev/null +++ b/src/api/validator2.ts @@ -0,0 +1,99 @@ +import * as mongo from 'mongodb'; +import hasDuplicates from '../common/has-duplicates'; + +type CustomValidator = (value: T) => boolean | string; + +interface Validator { + get: () => [any, string]; + + required: () => Validator; + + validate: (validator: CustomValidator) => Validator; +} + +class ValidatorCore implements Validator { + value: any; + error: string; + + required() { + if (this.error === null && this.value === null) { + this.error = 'required'; + } + return this; + } + + get(): [any, string] { + return [this.value, this.error]; + } + + validate(validator: any) { + 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; + } +} + +class NumberValidator extends ValidatorCore { + 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; + } + } + + 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(); + } + + validate(validator: CustomValidator) { + return super.validate(validator); + } +} + +const it = (value) => { + return { + must: { + be: { + a: { + string: 0, + number: () => new NumberValidator(value), + boolean: 0, + set: 0 + }, + an: { + id: 0, + array: 0, + object: 0 + } + } + } + }; +}; + +export default it; + +const [n, e] = it(42).must.be.a.number().required().range(10, 70).validate(x => x != 21).get(); From f3d5c07ada08a089969176cdb7b7bfc3f0132fda Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 17:08:09 +0900 Subject: [PATCH 11/43] wip --- src/api/endpoints/posts/{context.js => context.ts} | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) rename src/api/endpoints/posts/{context.js => context.ts} (81%) diff --git a/src/api/endpoints/posts/context.js b/src/api/endpoints/posts/context.ts similarity index 81% rename from src/api/endpoints/posts/context.js rename to src/api/endpoints/posts/context.ts index b843044642..673da0fab8 100644 --- a/src/api/endpoints/posts/context.js +++ b/src/api/endpoints/posts/context.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import validate from '../../validator'; import Post from '../../models/post'; import serialize from '../../serializers/post'; @@ -18,16 +18,14 @@ 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'); - } + const [postId, postIdErr] = validate(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id'); // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); + 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'); From b1195e5bfd9839f6ae3d8d375c948c8d0d5f7f20 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 17:14:46 +0900 Subject: [PATCH 12/43] Fix bug --- src/api/validator2.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/api/validator2.ts b/src/api/validator2.ts index 057875f80b..a1c5ba164b 100644 --- a/src/api/validator2.ts +++ b/src/api/validator2.ts @@ -15,6 +15,11 @@ class ValidatorCore implements Validator { value: any; error: string; + constructor() { + this.value = null; + this.error = null; + } + required() { if (this.error === null && this.value === null) { this.error = 'required'; From 85f43b49cffc645019e23e996f3ce85413d5b25f Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 17:16:55 +0900 Subject: [PATCH 13/43] =?UTF-8?q?=E3=81=84=E3=81=84=E6=84=9F=E3=81=98?= =?UTF-8?q?=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/validator2.ts | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/src/api/validator2.ts b/src/api/validator2.ts index a1c5ba164b..923f102e42 100644 --- a/src/api/validator2.ts +++ b/src/api/validator2.ts @@ -79,25 +79,23 @@ class NumberValidator extends ValidatorCore { } } -const it = (value) => { - return { - must: { - be: { - a: { - string: 0, - number: () => new NumberValidator(value), - boolean: 0, - set: 0 - }, - an: { - id: 0, - array: 0, - object: 0 - } +const it = (value: any) => ({ + must: { + be: { + a: { + string: 0, + number: () => new NumberValidator(value), + boolean: 0, + set: 0 + }, + an: { + id: 0, + array: 0, + object: 0 } } - }; -}; + } +}); export default it; From a26de4fda5fea8a0aab1fa803bbda2821ce116fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?syuilo=E2=AD=90=EF=B8=8F?= Date: Thu, 2 Mar 2017 17:22:18 +0900 Subject: [PATCH 14/43] =?UTF-8?q?=E3=81=84=E3=81=84=E6=84=9F=E3=81=98?= =?UTF-8?q?=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/validator2.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/validator2.ts b/src/api/validator2.ts index 923f102e42..ed58f445d3 100644 --- a/src/api/validator2.ts +++ b/src/api/validator2.ts @@ -31,7 +31,7 @@ class ValidatorCore implements Validator { return [this.value, this.error]; } - validate(validator: any) { + validate(validator: CustomValidator) { if (this.error || this.value === null) return this; const result = validator(this.value); if (result === false) { From f6c4f13b5773da3316a483f8bd5d7ae0c7f993db Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 20:51:32 +0900 Subject: [PATCH 15/43] wip --- src/api/validator2.ts | 313 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 298 insertions(+), 15 deletions(-) diff --git a/src/api/validator2.ts b/src/api/validator2.ts index ed58f445d3..04dff59aac 100644 --- a/src/api/validator2.ts +++ b/src/api/validator2.ts @@ -1,17 +1,20 @@ import * as mongo from 'mongodb'; import hasDuplicates from '../common/has-duplicates'; -type CustomValidator = (value: T) => boolean | string; +type Validator = (value: T) => boolean | string; +type Modifier = (value: T) => T; -interface Validator { +interface Fuctory { get: () => [any, string]; - required: () => Validator; + required: () => Fuctory; - validate: (validator: CustomValidator) => Validator; + validate: (validator: Validator) => Fuctory; + + modify: (modifier: Modifier) => Fuctory; } -class ValidatorCore implements Validator { +class FuctoryCore implements Fuctory { value: any; error: string; @@ -20,6 +23,9 @@ class ValidatorCore implements Validator { this.error = null; } + /** + * この値が undefined または null の場合エラーにします + */ required() { if (this.error === null && this.value === null) { this.error = 'required'; @@ -27,11 +33,19 @@ class ValidatorCore implements Validator { return this; } + /** + * このインスタンスの値およびエラーを取得します + */ get(): [any, string] { return [this.value, this.error]; } - validate(validator: CustomValidator) { + /** + * このインスタンスの値に対して妥当性を検証します + * バリデータが false または(エラーを表す)文字列を返した場合エラーにします + * @param validator バリデータ + */ + validate(validator: Validator) { if (this.error || this.value === null) return this; const result = validator(this.value); if (result === false) { @@ -41,9 +55,59 @@ class ValidatorCore implements Validator { } 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 NumberValidator extends ValidatorCore { +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; @@ -58,6 +122,11 @@ class NumberValidator extends ValidatorCore { } } + /** + * 値が指定された範囲内にない場合エラーにします + * @param min 下限 + * @param max 上限 + */ range(min: number, max: number) { if (this.error || this.value === null) return this; if (this.value < min || this.value > max) { @@ -70,28 +139,242 @@ class NumberValidator extends ValidatorCore { return super.required(); } + /** + * このインスタンスの値およびエラーを取得します + */ get(): [number, string] { return super.get(); } - validate(validator: CustomValidator) { + /** + * このインスタンスの値に対して妥当性を検証します + * バリデータが 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: 0, - number: () => new NumberValidator(value), - boolean: 0, - set: 0 + string: () => new StringFuctory(value), + number: () => new NumberFuctory(value), + boolean: () => new BooleanFuctory(value) }, an: { - id: 0, - array: 0, - object: 0 + id: () => new IdFuctory(value), + array: () => new ArrayFuctory(value), + object: () => new ObjectFuctory(value) } } } From 789deecfe96a32adfd98ebede749380f81520402 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 2 Mar 2017 21:54:46 +0900 Subject: [PATCH 16/43] 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 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(); From 2fee8fbba36376651161249964e1a3eca0f3d573 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 02:10:27 +0900 Subject: [PATCH 17/43] wip --- src/api/endpoints/posts/create.ts | 8 +- src/api/it.ts | 203 +++++++++--------------------- 2 files changed, 64 insertions(+), 147 deletions(-) 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] - } - } +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); + + let factory: Factory = 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; + 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]; + return factory; } -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; +export default x; From c94de44f2726ba59cfb5d02751abdda5d0b9dca1 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 02:12:32 +0900 Subject: [PATCH 18/43] Fix bug --- src/api/endpoints/posts/create.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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'); From d5e5419dfc14bbb8a1329c2028134b0999883258 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 02:42:17 +0900 Subject: [PATCH 19/43] wip --- src/api/endpoints/posts/context.ts | 27 +++------- src/api/it.ts | 83 ++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 20 deletions(-) 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); + } + /** * このインスタンスの値およびエラーを取得します */ From 21c50d42eb09313ea6f7cb932932be65c7d670e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?syuilo=E2=AD=90=EF=B8=8F?= Date: Fri, 3 Mar 2017 03:03:14 +0900 Subject: [PATCH 20/43] typo --- src/api/it.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/it.ts b/src/api/it.ts index ec42547488..76a3c5e91e 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -10,7 +10,7 @@ type Validator = (value: T) => boolean | Error; interface Factory { /** - * qedはQ.E.D.でもあり'QueryENd'の略でもある + * qedはQ.E.D.でもあり'QueryEnD'の略でもある */ qed: () => [any, Error]; From c128d2d1a3433bc3aa334a88491dd84a4bf8afdc Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 05:33:47 +0900 Subject: [PATCH 21/43] better name --- src/api/it.ts | 92 +++++++++++++++++++++++++-------------------------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/src/api/it.ts b/src/api/it.ts index 76a3c5e91e..5ca8d7dcae 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -8,20 +8,20 @@ import hasDuplicates from '../common/has-duplicates'; type Validator = (value: T) => boolean | Error; -interface Factory { +interface Query { /** * qedはQ.E.D.でもあり'QueryEnD'の略でもある */ qed: () => [any, Error]; - required: () => Factory; + required: () => Query; - default: (value: any) => Factory; + default: (value: any) => Query; - validate: (validator: Validator) => Factory; + validate: (validator: Validator) => Query; } -class FactoryCore implements Factory { +class QueryCore implements Query { value: any; error: Error; @@ -74,7 +74,7 @@ class FactoryCore implements Factory { } } -class BooleanFactory extends FactoryCore { +class BooleanQuery extends QueryCore { value: boolean; error: Error; @@ -120,7 +120,7 @@ class BooleanFactory extends FactoryCore { } } -class NumberFactory extends FactoryCore { +class NumberQuery extends QueryCore { value: number; error: Error; @@ -203,7 +203,7 @@ class NumberFactory extends FactoryCore { } } -class StringFactory extends FactoryCore { +class StringQuery extends QueryCore { value: string; error: Error; @@ -268,7 +268,7 @@ class StringFactory extends FactoryCore { } } -class ArrayFactory extends FactoryCore { +class ArrayQuery extends QueryCore { value: any[]; error: Error; @@ -338,7 +338,7 @@ class ArrayFactory extends FactoryCore { } } -class IdFactory extends FactoryCore { +class IdQuery extends QueryCore { value: mongo.ObjectID; error: Error; @@ -384,7 +384,7 @@ class IdFactory extends FactoryCore { } } -class ObjectFactory extends FactoryCore { +class ObjectQuery extends QueryCore { value: any; error: Error; @@ -434,24 +434,24 @@ type It = { must: { be: { a: { - string: () => StringFactory; - number: () => NumberFactory; - boolean: () => BooleanFactory; + string: () => StringQuery; + number: () => NumberQuery; + boolean: () => BooleanQuery; }; an: { - id: () => IdFactory; - array: () => ArrayFactory; - object: () => ObjectFactory; + id: () => IdQuery; + array: () => ArrayQuery; + object: () => ObjectQuery; }; }; }; expect: { - string: () => StringFactory; - number: () => NumberFactory; - boolean: () => BooleanFactory; - id: () => IdFactory; - array: () => ArrayFactory; - object: () => ObjectFactory; + string: () => StringQuery; + number: () => NumberQuery; + boolean: () => BooleanQuery; + id: () => IdQuery; + array: () => ArrayQuery; + object: () => ObjectQuery; }; }; @@ -459,24 +459,24 @@ const it = (value: any) => ({ must: { be: { a: { - string: () => new StringFactory(value), - number: () => new NumberFactory(value), - boolean: () => new BooleanFactory(value) + string: () => new StringQuery(value), + number: () => new NumberQuery(value), + boolean: () => new BooleanQuery(value) }, an: { - id: () => new IdFactory(value), - array: () => new ArrayFactory(value), - object: () => new ObjectFactory(value) + id: () => new IdQuery(value), + array: () => new ArrayQuery(value), + object: () => new ObjectQuery(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) + string: () => new StringQuery(value), + number: () => new NumberQuery(value), + boolean: () => new BooleanQuery(value), + id: () => new IdQuery(value), + array: () => new ArrayQuery(value), + object: () => new ObjectQuery(value) } }); @@ -493,26 +493,26 @@ function x(value: any, type: 'object', isRequired?: boolean, validator?: Validat function x(value: any, type?: Type, isRequired?: boolean, validator?: Validator | Validator[]): any { if (typeof type === 'undefined') return it(value); - let factory: Factory = null; + let q: Query = null; 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; + case 'id': q = it(value).expect.id(); break; + case 'string': q = it(value).expect.string(); break; + case 'number': q = it(value).expect.number(); break; + case 'boolean': q = it(value).expect.boolean(); break; + case 'array': q = it(value).expect.array(); break; + case 'set': q = it(value).expect.array().unique(); break; + case 'object': q = it(value).expect.object(); break; } - if (isRequired) factory = factory.required(); + if (isRequired) q = q.required(); if (validator) { (Array.isArray(validator) ? validator : [validator]) - .forEach(v => factory = factory.validate(v)); + .forEach(v => q = q.validate(v)); } - return factory; + return q; } export default x; From 8985d55b1bf34d81b553f77005d4bb5a856b6aef Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 05:33:59 +0900 Subject: [PATCH 22/43] fix --- src/api/endpoints/posts/context.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From d6af0bb78ba2cd179161139b7ae20655e69a98c1 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 05:52:12 +0900 Subject: [PATCH 23/43] wip --- .../endpoints/posts/{likes.js => likes.ts} | 30 +++++-------------- src/api/it.ts | 24 +++++++++++++++ 2 files changed, 32 insertions(+), 22 deletions(-) rename src/api/endpoints/posts/{likes.js => likes.ts} (64%) diff --git a/src/api/endpoints/posts/likes.js b/src/api/endpoints/posts/likes.ts similarity index 64% rename from src/api/endpoints/posts/likes.js rename to src/api/endpoints/posts/likes.ts index 67898218cf..5c18679d7c 100644 --- a/src/api/endpoints/posts/likes.js +++ b/src/api/endpoints/posts/likes.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Post from '../../models/post'; import Like from '../../models/like'; import serialize from '../../serializers/user'; @@ -19,33 +19,19 @@ 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'); - } + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id'); // 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 [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit'); // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } + 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 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 { From ffac713181978dafd1c92462338de405a3ef5360 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 06:11:11 +0900 Subject: [PATCH 24/43] Add usage doc --- src/api/it.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/api/it.ts b/src/api/it.ts index 2e6a7a770d..3d803e71e4 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -3,6 +3,29 @@ * 楽しいバリデーション */ +/** + * Usage Examples + * + * const [val, err] = it(x).must.be.a.string().or('asc desc').default('desc').qed(); + * → xは文字列でなければならず、'asc'または'desc'でなければならない。省略された場合のデフォルトは'desc'とする。 + * + * const [val, err] = it(x).must.be.a.number().required().range(0, 100).qed(); + * → xは数値でなければならず、かつ0~100の範囲内でなければならない。この値は省略することはできない。 + * + * const [val, err] = it(x).must.be.an.array().unique().required().validate(x => x[0] != 'strawberry pasta').qed(); + * → xは配列でなければならず、かつ中身が重複していてはならない。この値を省略することはできない。そして配列の最初の要素が'strawberry pasta'という文字列であってはならない。 + * + * ~糖衣構文~ + * const [val, err] = it(x).must.be.a.string().required().qed(); + * は + * const [val, err] = it(x, 'string', true); + * と書けます + * + * ~BDD風記法~ + * must.be.a(n) の代わりに expect とも書けます: + * const [val, err] = it(x).expect.string().required().qed(); + */ + import * as mongo from 'mongodb'; import hasDuplicates from '../common/has-duplicates'; From 9d3dff88056dac8eb00e62fedf438b197f99c256 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 06:29:49 +0900 Subject: [PATCH 25/43] wip --- src/api/endpoints/posts/likes.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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) { From d3c4cd1c433d2077628d6aba0fb3d053c94ddaa1 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 06:37:09 +0900 Subject: [PATCH 26/43] wip --- .../posts/{mentions.js => mentions.ts} | 38 +++++++++---------- 1 file changed, 18 insertions(+), 20 deletions(-) rename src/api/endpoints/posts/{mentions.js => mentions.ts} (57%) diff --git a/src/api/endpoints/posts/mentions.js b/src/api/endpoints/posts/mentions.ts similarity index 57% rename from src/api/endpoints/posts/mentions.js rename to src/api/endpoints/posts/mentions.ts index 5a3d72aab8..59802c558a 100644 --- a/src/api/endpoints/posts/mentions.js +++ b/src/api/endpoints/posts/mentions.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Post from '../../models/post'; import getFriends from '../../common/get-friends'; import serialize from '../../serializers/post'; @@ -19,33 +19,31 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'following' parameter - const following = params.following; + const [following, followingError] = + it(params.following).expect.boolean().default(false).qed(); + if (followingError) return rej('invalid following param'); // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + 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 @@ -59,14 +57,14 @@ module.exports = (params, user) => }; } - if (since) { + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } From 6e181ee0f1ca2ecd0fdf3a78654607ef112f2a6a Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 06:48:26 +0900 Subject: [PATCH 27/43] wip --- src/api/endpoints/posts/context.ts | 6 +-- src/api/endpoints/posts/likes.ts | 8 ++-- .../posts/{replies.js => replies.ts} | 36 +++++---------- .../posts/{reposts.js => reposts.ts} | 44 ++++++++----------- .../endpoints/posts/{search.js => search.ts} | 28 +++--------- src/api/endpoints/posts/{show.js => show.ts} | 15 ++----- .../posts/{timeline.js => timeline.ts} | 34 +++++++------- 7 files changed, 63 insertions(+), 108 deletions(-) rename src/api/endpoints/posts/{replies.js => replies.ts} (54%) rename src/api/endpoints/posts/{reposts.js => reposts.ts} (54%) rename src/api/endpoints/posts/{search.js => search.ts} (81%) rename src/api/endpoints/posts/{show.js => show.ts} (64%) rename src/api/endpoints/posts/{timeline.js => timeline.ts} (63%) 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.ts similarity index 54% rename from src/api/endpoints/posts/replies.js rename to src/api/endpoints/posts/replies.ts index cbbb5dc312..3f448d1632 100644 --- a/src/api/endpoints/posts/replies.js +++ b/src/api/endpoints/posts/replies.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Post from '../../models/post'; import serialize from '../../serializers/post'; @@ -18,42 +18,28 @@ 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'); - } + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); // 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 [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); // Get 'sort' parameter - 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 param'); // 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'); } // Issue query diff --git a/src/api/endpoints/posts/reposts.js b/src/api/endpoints/posts/reposts.ts similarity index 54% rename from src/api/endpoints/posts/reposts.js rename to src/api/endpoints/posts/reposts.ts index 0ffe44cb16..d8410b322b 100644 --- a/src/api/endpoints/posts/reposts.js +++ b/src/api/endpoints/posts/reposts.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Post from '../../models/post'; import serialize from '../../serializers/post'; @@ -18,39 +18,33 @@ 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'); - } + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + if (sinceId !== null && maxId !== null) { return rej('cannot set since_id and max_id'); } // 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'); } // Construct query @@ -59,15 +53,15 @@ module.exports = (params, user) => }; const query = { repost_id: post._id - }; - if (since !== null) { + } as any; + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } diff --git a/src/api/endpoints/posts/search.js b/src/api/endpoints/posts/search.ts similarity index 81% rename from src/api/endpoints/posts/search.js rename to src/api/endpoints/posts/search.ts index bc06340fda..1d02f6775d 100644 --- a/src/api/endpoints/posts/search.js +++ b/src/api/endpoints/posts/search.ts @@ -4,6 +4,7 @@ * 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'; @@ -20,31 +21,16 @@ 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'); - } + const [query, queryError] = it(params.query).expect.string().required().trim().validate(x => x != '').qed(); + if (queryError) return rej('invalid query param'); // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); // 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; - } + 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 diff --git a/src/api/endpoints/posts/show.js b/src/api/endpoints/posts/show.ts similarity index 64% rename from src/api/endpoints/posts/show.js rename to src/api/endpoints/posts/show.ts index 4938199cdb..712ef1e160 100644 --- a/src/api/endpoints/posts/show.js +++ b/src/api/endpoints/posts/show.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Post from '../../models/post'; import serialize from '../../serializers/post'; @@ -18,19 +18,12 @@ 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'); - } + 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: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { diff --git a/src/api/endpoints/posts/timeline.js b/src/api/endpoints/posts/timeline.ts similarity index 63% rename from src/api/endpoints/posts/timeline.js rename to src/api/endpoints/posts/timeline.ts index 48f7c26940..5744084932 100644 --- a/src/api/endpoints/posts/timeline.js +++ b/src/api/endpoints/posts/timeline.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Post from '../../models/post'; import getFriends from '../../common/get-friends'; import serialize from '../../serializers/post'; @@ -20,23 +20,19 @@ 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); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + if (sinceId !== null && maxId !== null) { return rej('cannot set since_id and max_id'); } @@ -51,15 +47,15 @@ module.exports = (params, user, app) => user_id: { $in: followingIds } - }; - if (since !== null) { + } as any; + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } From 2e4e599c01975f959a56d0eb4b81e3c8475953f3 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 07:27:47 +0900 Subject: [PATCH 28/43] Refactor --- src/api/it.ts | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/api/it.ts b/src/api/it.ts index 3d803e71e4..f4b28531d6 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -5,22 +5,22 @@ /** * Usage Examples - * + * * const [val, err] = it(x).must.be.a.string().or('asc desc').default('desc').qed(); * → xは文字列でなければならず、'asc'または'desc'でなければならない。省略された場合のデフォルトは'desc'とする。 - * + * * const [val, err] = it(x).must.be.a.number().required().range(0, 100).qed(); * → xは数値でなければならず、かつ0~100の範囲内でなければならない。この値は省略することはできない。 - * + * * const [val, err] = it(x).must.be.an.array().unique().required().validate(x => x[0] != 'strawberry pasta').qed(); * → xは配列でなければならず、かつ中身が重複していてはならない。この値を省略することはできない。そして配列の最初の要素が'strawberry pasta'という文字列であってはならない。 - * + * * ~糖衣構文~ * const [val, err] = it(x).must.be.a.string().required().qed(); * は * const [val, err] = it(x, 'string', true); * と書けます - * + * * ~BDD風記法~ * must.be.a(n) の代わりに expect とも書けます: * const [val, err] = it(x).expect.string().required().qed(); @@ -53,6 +53,13 @@ class QueryCore implements Query { this.error = null; } + /** + * このインスタンスの値が null、またはエラーが存在しているなどして、処理をスキップするべきか否か + */ + get shouldSkip() { + return this.error !== null || this.value === null; + } + /** * このインスタンスの値が undefined または null の場合エラーにします */ @@ -86,7 +93,7 @@ class QueryCore implements Query { * @param validator バリデータ */ validate(validator: Validator) { - if (this.error || this.value === null) return this; + if (this.shouldSkip) return this; const result = validator(this.value); if (result === false) { this.error = new Error('invalid-format'); @@ -164,7 +171,7 @@ class NumberQuery extends QueryCore { * @param max 上限 */ range(min: number, max: number) { - if (this.error || this.value === null) return this; + if (this.shouldSkip) return this; if (this.value < min || this.value > max) { this.error = new Error('invalid-range'); } @@ -176,7 +183,7 @@ class NumberQuery extends QueryCore { * @param value 下限 */ min(value: number) { - if (this.error || this.value === null) return this; + if (this.shouldSkip) return this; if (this.value < value) { this.error = new Error('invalid-range'); } @@ -188,7 +195,7 @@ class NumberQuery extends QueryCore { * @param value 上限 */ max(value: number) { - if (this.error || this.value === null) return this; + if (this.shouldSkip) return this; if (this.value > value) { this.error = new Error('invalid-range'); } @@ -247,7 +254,7 @@ class StringQuery extends QueryCore { * @param max 上限 */ range(min: number, max: number) { - if (this.error || this.value === null) return this; + if (this.shouldSkip) return this; if (this.value.length < min || this.value.length > max) { this.error = new Error('invalid-range'); } @@ -255,7 +262,7 @@ class StringQuery extends QueryCore { } trim() { - if (this.error || this.value === null) return this; + if (this.shouldSkip) return this; this.value = this.value.trim(); return this; } @@ -296,7 +303,7 @@ class StringQuery extends QueryCore { * @param pattern 文字列の配列またはスペースで区切られた文字列 */ or(pattern: string | string[]) { - if (this.error || this.value === null) return this; + if (this.shouldSkip) 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'); @@ -309,7 +316,7 @@ class StringQuery extends QueryCore { * @param pattern 正規表現 */ match(pattern: RegExp) { - if (this.error || this.value === null) return this; + if (this.shouldSkip) return this; if (!pattern.test(this.value)) this.error = new Error('not-match-pattern'); return this; } @@ -334,7 +341,7 @@ class ArrayQuery extends QueryCore { * 配列の値がユニークでない場合(=重複した項目がある場合)エラーにします */ unique() { - if (this.error || this.value === null) return this; + if (this.shouldSkip) return this; if (hasDuplicates(this.value)) { this.error = new Error('must-be-unique'); } @@ -347,7 +354,7 @@ class ArrayQuery extends QueryCore { * @param max 上限 */ range(min: number, max: number) { - if (this.error || this.value === null) return this; + if (this.shouldSkip) return this; if (this.value.length < min || this.value.length > max) { this.error = new Error('invalid-range'); } From 0926d5b6da68be6c9375addbd3cec8545185dea7 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 07:47:14 +0900 Subject: [PATCH 29/43] wip --- .../users/{followers.js => followers.ts} | 33 ++++------ .../users/{following.js => following.ts} | 33 ++++------ .../endpoints/users/{posts.js => posts.ts} | 64 ++++++++----------- .../{recommendation.js => recommendation.ts} | 22 ++----- .../endpoints/users/{search.js => search.ts} | 28 ++------ ...h_by_username.js => search_by_username.ts} | 40 +++--------- src/api/endpoints/users/{show.js => show.ts} | 21 ++---- 7 files changed, 78 insertions(+), 163 deletions(-) rename src/api/endpoints/users/{followers.js => followers.ts} (72%) rename src/api/endpoints/users/{following.js => following.ts} (72%) rename src/api/endpoints/users/{posts.js => posts.ts} (52%) rename src/api/endpoints/users/{recommendation.js => recommendation.ts} (68%) rename src/api/endpoints/users/{search.js => search.ts} (79%) rename src/api/endpoints/users/{search_by_username.js => search_by_username.ts} (50%) rename src/api/endpoints/users/{show.js => show.ts} (64%) diff --git a/src/api/endpoints/users/followers.js b/src/api/endpoints/users/followers.ts similarity index 72% rename from src/api/endpoints/users/followers.js rename to src/api/endpoints/users/followers.ts index 598c3b6bcf..011a1c70ce 100644 --- a/src/api/endpoints/users/followers.js +++ b/src/api/endpoints/users/followers.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import User from '../../models/user'; import Following from '../../models/following'; import serialize from '../../serializers/user'; @@ -20,33 +20,24 @@ module.exports = (params, me) => new Promise(async (res, rej) => { // Get 'user_id' parameter - const userId = params.user_id; - if (userId === undefined || userId === null) { - return rej('user_id is required'); - } + const [userId, userIdErr] = it(params.user_id, 'id', true); + if (userIdErr) return rej('invalid user_id param'); // Get 'iknow' parameter - const iknow = params.iknow; + const [iknow, iknowErr] = it(params.iknow).expect.boolean().default(false).qed(); + if (iknowErr) return rej('invalid iknow param'); // 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 [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); // Get 'cursor' parameter - const cursor = params.cursor || null; + const [cursor, cursorErr] = it(params.cursor).expect.id().default(null).qed(); + if (cursorErr) return rej('invalid cursor param'); // Lookup user const user = await User.findOne({ - _id: new mongo.ObjectID(userId) + _id: userId }, { fields: { _id: true @@ -61,7 +52,7 @@ module.exports = (params, me) => const query = { followee_id: user._id, deleted_at: { $exists: false } - }; + } as any; // ログインしていてかつ iknow フラグがあるとき if (me && iknow) { @@ -76,7 +67,7 @@ module.exports = (params, me) => // カーソルが指定されている場合 if (cursor) { query._id = { - $lt: new mongo.ObjectID(cursor) + $lt: cursor }; } diff --git a/src/api/endpoints/users/following.js b/src/api/endpoints/users/following.ts similarity index 72% rename from src/api/endpoints/users/following.js rename to src/api/endpoints/users/following.ts index 36868d6d5c..df5c058354 100644 --- a/src/api/endpoints/users/following.js +++ b/src/api/endpoints/users/following.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import User from '../../models/user'; import Following from '../../models/following'; import serialize from '../../serializers/user'; @@ -20,33 +20,24 @@ module.exports = (params, me) => new Promise(async (res, rej) => { // Get 'user_id' parameter - const userId = params.user_id; - if (userId === undefined || userId === null) { - return rej('user_id is required'); - } + const [userId, userIdErr] = it(params.user_id, 'id', true); + if (userIdErr) return rej('invalid user_id param'); // Get 'iknow' parameter - const iknow = params.iknow; + const [iknow, iknowErr] = it(params.iknow).expect.boolean().default(false).qed(); + if (iknowErr) return rej('invalid iknow param'); // 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 [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); // Get 'cursor' parameter - const cursor = params.cursor || null; + const [cursor, cursorErr] = it(params.cursor).expect.id().default(null).qed(); + if (cursorErr) return rej('invalid cursor param'); // Lookup user const user = await User.findOne({ - _id: new mongo.ObjectID(userId) + _id: userId }, { fields: { _id: true @@ -61,7 +52,7 @@ module.exports = (params, me) => const query = { follower_id: user._id, deleted_at: { $exists: false } - }; + } as any; // ログインしていてかつ iknow フラグがあるとき if (me && iknow) { @@ -76,7 +67,7 @@ module.exports = (params, me) => // カーソルが指定されている場合 if (cursor) { query._id = { - $lt: new mongo.ObjectID(cursor) + $lt: cursor }; } diff --git a/src/api/endpoints/users/posts.js b/src/api/endpoints/users/posts.ts similarity index 52% rename from src/api/endpoints/users/posts.js rename to src/api/endpoints/users/posts.ts index d358c4b4dd..526ed1ee1b 100644 --- a/src/api/endpoints/users/posts.js +++ b/src/api/endpoints/users/posts.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Post from '../../models/post'; import User from '../../models/user'; import serialize from '../../serializers/post'; @@ -19,56 +19,44 @@ module.exports = (params, me) => new Promise(async (res, rej) => { // Get 'user_id' parameter - let userId = params.user_id; - if (userId === undefined || userId === null || userId === '') { - userId = null; - } + const [userId, userIdErr] = it(params.user_id, 'id'); + if (userIdErr) return rej('invalid user_id param'); // Get 'username' parameter - let username = params.username; - if (username === undefined || username === null || username === '') { - username = null; - } + const [username, usernameErr] = it(params.username, 'string'); + if (usernameErr) return rej('invalid username param'); if (userId === null && username === null) { return rej('user_id or username is required'); } - // Get 'with_replies' parameter - let withReplies = params.with_replies; - if (withReplies == null) { - withReplies = true; - } + // 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 'with_media' parameter - let withMedia = params.with_media; - if (withMedia == null) { - withMedia = false; - } + const [withMedia, withMediaErr] = it(params.with_media).expect.boolean().default(false).qed(); + if (withMediaErr) return rej('invalid with_media param'); // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + if (sinceId !== null && maxId !== null) { return rej('cannot set since_id and max_id'); } const q = userId != null - ? { _id: new mongo.ObjectID(userId) } + ? { _id: userId } : { username_lower: username.toLowerCase() } ; // Lookup user @@ -88,19 +76,19 @@ module.exports = (params, me) => }; const query = { user_id: user._id - }; - if (since !== null) { + } as any; + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } - if (!withReplies) { + if (!includeReplies) { query.reply_to_id = null; } diff --git a/src/api/endpoints/users/recommendation.js b/src/api/endpoints/users/recommendation.ts similarity index 68% rename from src/api/endpoints/users/recommendation.js rename to src/api/endpoints/users/recommendation.ts index 0045683a5a..c37ae4c978 100644 --- a/src/api/endpoints/users/recommendation.js +++ b/src/api/endpoints/users/recommendation.ts @@ -3,6 +3,7 @@ /** * Module dependencies */ +import it from '../../it'; import User from '../../models/user'; import serialize from '../../serializers/user'; import getFriends from '../../common/get-friends'; @@ -18,25 +19,12 @@ 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 [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); // ID list of the user itself and other users who the user follows const followingIds = await getFriends(me._id); diff --git a/src/api/endpoints/users/search.js b/src/api/endpoints/users/search.ts similarity index 79% rename from src/api/endpoints/users/search.js rename to src/api/endpoints/users/search.ts index b1f4537328..3fb08b0a35 100644 --- a/src/api/endpoints/users/search.js +++ b/src/api/endpoints/users/search.ts @@ -4,6 +4,7 @@ * Module dependencies */ import * as mongo from 'mongodb'; +import it from '../../it'; import User from '../../models/user'; import serialize from '../../serializers/user'; import config from '../../../conf'; @@ -20,31 +21,16 @@ 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'); - } + const [query, queryError] = it(params.query).expect.string().required().trim().validate(x => x != '').qed(); + if (queryError) return rej('invalid query param'); // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); // 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; - } + 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 diff --git a/src/api/endpoints/users/search_by_username.js b/src/api/endpoints/users/search_by_username.ts similarity index 50% rename from src/api/endpoints/users/search_by_username.js rename to src/api/endpoints/users/search_by_username.ts index 7fe6f34092..540c48e7ce 100644 --- a/src/api/endpoints/users/search_by_username.js +++ b/src/api/endpoints/users/search_by_username.ts @@ -3,8 +3,9 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import User from '../../models/user'; +import { validateUsername } from '../../models/user'; import serialize from '../../serializers/user'; /** @@ -18,37 +19,16 @@ 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'); - } - - query = query.trim(); - - if (!/^[a-zA-Z0-9-]+$/.test(query)) { - return rej('invalid query'); - } - - // 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 [query, queryError] = it(params.query).expect.string().required().trim().validate(validateUsername).qed(); + if (queryError) return rej('invalid query param'); // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset 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'); const users = await User .find({ diff --git a/src/api/endpoints/users/show.js b/src/api/endpoints/users/show.ts similarity index 64% rename from src/api/endpoints/users/show.js rename to src/api/endpoints/users/show.ts index 0eaba221cc..cae4ac0b7f 100644 --- a/src/api/endpoints/users/show.js +++ b/src/api/endpoints/users/show.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import User from '../../models/user'; import serialize from '../../serializers/user'; @@ -18,28 +18,19 @@ module.exports = (params, me) => new Promise(async (res, rej) => { // Get 'user_id' parameter - let userId = params.user_id; - if (userId === undefined || userId === null || userId === '') { - userId = null; - } + const [userId, userIdErr] = it(params.user_id, 'id'); + if (userIdErr) return rej('invalid user_id param'); // Get 'username' parameter - let username = params.username; - if (username === undefined || username === null || username === '') { - username = null; - } + const [username, usernameErr] = it(params.username, 'string'); + if (usernameErr) return rej('invalid username param'); if (userId === null && username === null) { return rej('user_id or username is required'); } - // Validate id - if (userId && !mongo.ObjectID.isValid(userId)) { - return rej('incorrect user_id'); - } - const q = userId != null - ? { _id: new mongo.ObjectID(userId) } + ? { _id: userId } : { username_lower: username.toLowerCase() } ; // Lookup user From 583b64331b4d3d36f642801c847109b8634df1d9 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 08:00:10 +0900 Subject: [PATCH 30/43] wip --- .../posts/favorites/{create.js => create.ts} | 12 +++---- .../posts/favorites/{delete.js => delete.ts} | 12 +++---- .../posts/likes/{create.js => create.ts} | 15 +++------ .../posts/likes/{delete.js => delete.ts} | 15 +++------ .../posts/polls/{vote.js => vote.ts} | 32 ++++++------------- .../username/{available.js => available.ts} | 12 ++----- 6 files changed, 31 insertions(+), 67 deletions(-) rename src/api/endpoints/posts/favorites/{create.js => create.ts} (75%) rename src/api/endpoints/posts/favorites/{delete.js => delete.ts} (74%) rename src/api/endpoints/posts/likes/{create.js => create.ts} (82%) rename src/api/endpoints/posts/likes/{delete.js => delete.ts} (80%) rename src/api/endpoints/posts/polls/{vote.js => vote.ts} (72%) rename src/api/endpoints/username/{available.js => available.ts} (69%) diff --git a/src/api/endpoints/posts/favorites/create.js b/src/api/endpoints/posts/favorites/create.ts similarity index 75% rename from src/api/endpoints/posts/favorites/create.js rename to src/api/endpoints/posts/favorites/create.ts index 7ee7c0d3fb..5be338593c 100644 --- a/src/api/endpoints/posts/favorites/create.js +++ b/src/api/endpoints/posts/favorites/create.ts @@ -3,9 +3,9 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; -import Favorite from '../../models/favorite'; -import Post from '../../models/post'; +import it from '../../../it'; +import Favorite from '../../../models/favorite'; +import Post from '../../../models/post'; /** * Favorite a post @@ -17,10 +17,8 @@ import Post from '../../models/post'; 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'); - } + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); // Get favoritee const post = await Post.findOne({ diff --git a/src/api/endpoints/posts/favorites/delete.js b/src/api/endpoints/posts/favorites/delete.ts similarity index 74% rename from src/api/endpoints/posts/favorites/delete.js rename to src/api/endpoints/posts/favorites/delete.ts index 4b36b9bde3..4dfd761589 100644 --- a/src/api/endpoints/posts/favorites/delete.js +++ b/src/api/endpoints/posts/favorites/delete.ts @@ -3,9 +3,9 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; -import Favorite from '../../models/favorite'; -import Post from '../../models/post'; +import it from '../../../it'; +import Favorite from '../../../models/favorite'; +import Post from '../../../models/post'; /** * Unfavorite a post @@ -17,10 +17,8 @@ import Post from '../../models/post'; 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'); - } + const [postId, postIdErr] = it(params.post_id, 'id', true); + if (postIdErr) return rej('invalid post_id param'); // Get favoritee const post = await Post.findOne({ diff --git a/src/api/endpoints/posts/likes/create.js b/src/api/endpoints/posts/likes/create.ts similarity index 82% rename from src/api/endpoints/posts/likes/create.js rename to src/api/endpoints/posts/likes/create.ts index 3b2c778a03..0ae417e239 100644 --- a/src/api/endpoints/posts/likes/create.js +++ b/src/api/endpoints/posts/likes/create.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import Like from '../../../models/like'; import Post from '../../../models/post'; import User from '../../../models/user'; @@ -19,19 +19,12 @@ import notify from '../../../common/notify'; 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'); - } + 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: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { diff --git a/src/api/endpoints/posts/likes/delete.js b/src/api/endpoints/posts/likes/delete.ts similarity index 80% rename from src/api/endpoints/posts/likes/delete.js rename to src/api/endpoints/posts/likes/delete.ts index 1dd0f5b29a..2b642c107f 100644 --- a/src/api/endpoints/posts/likes/delete.js +++ b/src/api/endpoints/posts/likes/delete.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import Like from '../../../models/like'; import Post from '../../../models/post'; import User from '../../../models/user'; @@ -19,19 +19,12 @@ import User from '../../../models/user'; 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'); - } + 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: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { diff --git a/src/api/endpoints/posts/polls/vote.js b/src/api/endpoints/posts/polls/vote.ts similarity index 72% rename from src/api/endpoints/posts/polls/vote.js rename to src/api/endpoints/posts/polls/vote.ts index 9f9a5171a0..d0caf7da95 100644 --- a/src/api/endpoints/posts/polls/vote.js +++ b/src/api/endpoints/posts/polls/vote.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import Vote from '../../../models/poll-vote'; import Post from '../../../models/post'; import notify from '../../../common/notify'; @@ -18,19 +18,12 @@ import notify from '../../../common/notify'; 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'); - } + 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: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { @@ -42,15 +35,12 @@ module.exports = (params, user) => } // 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'); - } + 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({ @@ -76,8 +66,6 @@ module.exports = (params, user) => 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 diff --git a/src/api/endpoints/username/available.js b/src/api/endpoints/username/available.ts similarity index 69% rename from src/api/endpoints/username/available.js rename to src/api/endpoints/username/available.ts index 8f4d8cf280..9a85644b69 100644 --- a/src/api/endpoints/username/available.js +++ b/src/api/endpoints/username/available.ts @@ -3,6 +3,7 @@ /** * Module dependencies */ +import it from '../../it'; import User from '../../models/user'; import { validateUsername } from '../../models/user'; @@ -16,15 +17,8 @@ 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'); - } + 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 From 67f9c158d71c497f3f3889e10fa1587a9a038381 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 08:06:34 +0900 Subject: [PATCH 31/43] wip --- src/api/endpoints/{drive.js => drive.ts} | 0 src/api/endpoints/{i.js => i.ts} | 0 src/api/endpoints/{meta.js => meta.ts} | 0 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 => users.ts} | 33 ++++---- 8 files changed, 93 insertions(+), 107 deletions(-) rename src/api/endpoints/{drive.js => drive.ts} (100%) rename src/api/endpoints/{i.js => i.ts} (100%) rename src/api/endpoints/{meta.js => meta.ts} (100%) delete mode 100644 src/api/endpoints/posts.js create mode 100644 src/api/endpoints/posts.ts rename src/api/endpoints/{users.js => users.ts} (55%) diff --git a/src/api/endpoints/drive.js b/src/api/endpoints/drive.ts similarity index 100% rename from src/api/endpoints/drive.js rename to src/api/endpoints/drive.ts diff --git a/src/api/endpoints/i.js b/src/api/endpoints/i.ts similarity index 100% rename from src/api/endpoints/i.js rename to src/api/endpoints/i.ts diff --git a/src/api/endpoints/meta.js b/src/api/endpoints/meta.ts similarity index 100% rename from src/api/endpoints/meta.js rename to src/api/endpoints/meta.ts 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.ts similarity index 55% rename from src/api/endpoints/users.js rename to src/api/endpoints/users.ts index 63e28caa46..74c4754fed 100644 --- a/src/api/endpoints/users.js +++ b/src/api/endpoints/users.ts @@ -3,6 +3,7 @@ /** * Module dependencies */ +import it from '../it'; import User from '../models/user'; import serialize from '../serializers/user'; @@ -16,23 +17,19 @@ import serialize from '../serializers/user'; 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); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + if (sinceId !== null && maxId !== null) { return rej('cannot set since_id and max_id'); } @@ -40,15 +37,15 @@ module.exports = (params, me) => const sort = { _id: -1 }; - const query = {}; - if (since !== null) { + const query = {} as any; + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } From 2a9cba25a89b5cf2394a22696ee0fb67140076a9 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 08:24:48 +0900 Subject: [PATCH 32/43] wip --- .../messaging/{history.js => history.ts} | 15 +--- .../messaging/{messages.js => messages.ts} | 65 ++++++++--------- .../messages/{create.js => create.ts} | 72 +++++++------------ .../messaging/{unread.js => unread.ts} | 0 src/api/endpoints/my/{apps.js => apps.ts} | 23 ++---- .../{mark_as_read.js => mark_as_read.ts} | 17 ++--- src/api/it.ts | 4 +- src/api/models/messaging-message.ts | 5 ++ src/api/serializers/messaging-message.ts | 2 +- 9 files changed, 77 insertions(+), 126 deletions(-) rename src/api/endpoints/messaging/{history.js => history.ts} (69%) rename src/api/endpoints/messaging/{messages.js => messages.ts} (64%) rename src/api/endpoints/messaging/messages/{create.js => create.ts} (72%) rename src/api/endpoints/messaging/{unread.js => unread.ts} (100%) rename src/api/endpoints/my/{apps.js => apps.ts} (60%) rename src/api/endpoints/notifications/{mark_as_read.js => mark_as_read.ts} (65%) diff --git a/src/api/endpoints/messaging/history.js b/src/api/endpoints/messaging/history.ts similarity index 69% rename from src/api/endpoints/messaging/history.js rename to src/api/endpoints/messaging/history.ts index 60c34a6a41..07ad6e0f22 100644 --- a/src/api/endpoints/messaging/history.js +++ b/src/api/endpoints/messaging/history.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import History from '../../models/messaging-history'; import serialize from '../../serializers/messaging-message'; @@ -18,17 +18,8 @@ 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 [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); // Get history const history = await History diff --git a/src/api/endpoints/messaging/messages.js b/src/api/endpoints/messaging/messages.ts similarity index 64% rename from src/api/endpoints/messaging/messages.js rename to src/api/endpoints/messaging/messages.ts index eaaf38c398..81562efbcc 100644 --- a/src/api/endpoints/messaging/messages.js +++ b/src/api/endpoints/messaging/messages.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Message from '../../models/messaging-message'; import User from '../../models/user'; import serialize from '../../serializers/messaging-message'; @@ -21,47 +21,40 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'user_id' parameter - let recipient = params.user_id; - if (recipient !== undefined && recipient !== null) { - recipient = await User.findOne({ - _id: new mongo.ObjectID(recipient) - }, { - fields: { - _id: true - } - }); + const [recipientId, recipientIdErr] = it(params.user_id).expect.id().required().qed(); + if (recipientIdErr) return rej('invalid user_id param'); - if (recipient === null) { - return rej('user not found'); + // Fetch recipient + const recipient = await User.findOne({ + _id: recipientId + }, { + fields: { + _id: true } - } else { - return rej('user_id is required'); + }); + + if (recipient === null) { + return rej('user not found'); } // Get 'mark_as_read' parameter - let markAsRead = params.mark_as_read; - if (markAsRead == null) { - markAsRead = true; - } + const [markAsRead, markAsReadErr] = it(params.mark_as_read).expect.boolean().default(true).qed(); + if (markAsReadErr) return rej('invalid mark_as_read param'); // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + if (sinceId !== null && maxId !== null) { return rej('cannot set since_id and max_id'); } @@ -73,20 +66,20 @@ module.exports = (params, user) => user_id: recipient._id, recipient_id: user._id }] - }; + } as any; const sort = { _id: -1 }; - if (since !== null) { + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } diff --git a/src/api/endpoints/messaging/messages/create.js b/src/api/endpoints/messaging/messages/create.ts similarity index 72% rename from src/api/endpoints/messaging/messages/create.js rename to src/api/endpoints/messaging/messages/create.ts index a88cc39ee8..dbe7f617fa 100644 --- a/src/api/endpoints/messaging/messages/create.js +++ b/src/api/endpoints/messaging/messages/create.ts @@ -3,8 +3,9 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import Message from '../../../models/messaging-message'; +import { isValidText } from '../../../models/messaging-message'; import History from '../../../models/messaging-history'; import User from '../../../models/user'; import DriveFile from '../../../models/drive-file'; @@ -13,11 +14,6 @@ import publishUserStream from '../../../event'; import { publishMessagingStream } from '../../../event'; import config from '../../../../conf'; -/** - * 最大文字数 - */ -const maxTextLength = 500; - /** * Create a message * @@ -29,55 +25,39 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'user_id' parameter - let recipient = params.user_id; - if (recipient !== undefined && recipient !== null) { - if (typeof recipient != 'string') { - return rej('user_id must be a string'); - } + const [recipientId, recipientIdErr] = it(params.user_id).expect.id().required().qed(); + if (recipientIdErr) return rej('invalid user_id param'); - // Validate id - if (!mongo.ObjectID.isValid(recipient)) { - return rej('incorrect user_id'); - } + // Myself + if (recipientId.equals(user._id)) { + return rej('cannot send message to myself'); + } - // Myself - if (new mongo.ObjectID(recipient).equals(user._id)) { - return rej('cannot send message to myself'); + // Fetch recipient + const recipient = await User.findOne({ + _id: recipientId + }, { + fields: { + _id: true } + }); - recipient = await User.findOne({ - _id: new mongo.ObjectID(recipient) - }, { - fields: { - _id: true - } - }); - - if (recipient === null) { - return rej('user not found'); - } - } else { - return rej('user_id is required'); + if (recipient === null) { + return rej('user not found'); } // Get 'text' parameter - let text = params.text; - if (text !== undefined && text !== null) { - 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] = it(params.text).expect.string().validate(isValidText).qed(); + if (textErr) return rej('invalid text'); // Get 'file_id' parameter - let file = params.file_id; - if (file !== undefined && file !== null) { + const [fileId, fileIdErr] = it(params.file_id).expect.id().qed(); + if (fileIdErr) return rej('invalid file_id param'); + + let file = null; + if (fileId !== null) { file = await DriveFile.findOne({ - _id: new mongo.ObjectID(file), + _id: fileId, user_id: user._id }, { data: false @@ -86,8 +66,6 @@ module.exports = (params, user) => if (file === null) { return rej('file not found'); } - } else { - file = null; } // テキストが無いかつ添付ファイルも無かったらエラー diff --git a/src/api/endpoints/messaging/unread.js b/src/api/endpoints/messaging/unread.ts similarity index 100% rename from src/api/endpoints/messaging/unread.js rename to src/api/endpoints/messaging/unread.ts diff --git a/src/api/endpoints/my/apps.js b/src/api/endpoints/my/apps.ts similarity index 60% rename from src/api/endpoints/my/apps.js rename to src/api/endpoints/my/apps.ts index 1f45a1a27f..2466a47ce4 100644 --- a/src/api/endpoints/my/apps.js +++ b/src/api/endpoints/my/apps.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import App from '../../models/app'; import serialize from '../../serializers/app'; @@ -18,25 +18,12 @@ 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 [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); const query = { user_id: user._id diff --git a/src/api/endpoints/notifications/mark_as_read.js b/src/api/endpoints/notifications/mark_as_read.ts similarity index 65% rename from src/api/endpoints/notifications/mark_as_read.js rename to src/api/endpoints/notifications/mark_as_read.ts index 9c8a5ee64b..6e75927cfa 100644 --- a/src/api/endpoints/notifications/mark_as_read.js +++ b/src/api/endpoints/notifications/mark_as_read.ts @@ -3,10 +3,10 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; -import Notification from '../../../models/notification'; -import serialize from '../../../serializers/notification'; -import event from '../../../event'; +import it from '../../it'; +import Notification from '../../models/notification'; +import serialize from '../../serializers/notification'; +import event from '../../event'; /** * Mark as read a notification @@ -17,16 +17,13 @@ import event from '../../../event'; */ module.exports = (params, user) => new Promise(async (res, rej) => { - const notificationId = params.notification; - - if (notificationId === undefined || notificationId === null) { - return rej('notification is required'); - } + const [notificationId, notificationIdErr] = it(params.notification_id).expect.id().required().qed(); + if (notificationIdErr) return rej('invalid notification_id param'); // Get notification const notification = await Notification .findOne({ - _id: new mongo.ObjectID(notificationId), + _id: notificationId, i: user._id }); diff --git a/src/api/it.ts b/src/api/it.ts index f4b28531d6..039f879957 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -424,7 +424,7 @@ class IdQuery extends QueryCore { /** * このインスタンスの値およびエラーを取得します */ - qed(): [any[], Error] { + qed(): [mongo.ObjectID, Error] { return super.qed(); } @@ -433,7 +433,7 @@ class IdQuery extends QueryCore { * バリデータが false またはエラーを返した場合エラーにします * @param validator バリデータ */ - validate(validator: Validator) { + validate(validator: Validator) { return super.validate(validator); } } diff --git a/src/api/models/messaging-message.ts b/src/api/models/messaging-message.ts index cad6823cb8..50955d7fb0 100644 --- a/src/api/models/messaging-message.ts +++ b/src/api/models/messaging-message.ts @@ -1,3 +1,8 @@ import db from '../../db/mongodb'; export default db.get('messaging_messages') as any; // fuck type definition + +export function isValidText(text: string): boolean { + return text.length <= 1000 && text.trim() != ''; +} + diff --git a/src/api/serializers/messaging-message.ts b/src/api/serializers/messaging-message.ts index 4a4c8fc5b4..da63f8b99e 100644 --- a/src/api/serializers/messaging-message.ts +++ b/src/api/serializers/messaging-message.ts @@ -19,7 +19,7 @@ import deepcopy = require('deepcopy'); */ export default ( message: any, - me: any, + me?: any, options?: { populateRecipient: boolean } From dc45055f2ffcea2369f12d104999746220b22c90 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 08:56:07 +0900 Subject: [PATCH 33/43] wip --- .../endpoints/i/appdata/{get.js => get.ts} | 0 .../endpoints/i/appdata/{set.js => set.ts} | 0 ...{authorized_apps.js => authorized_apps.ts} | 26 ++---- .../i/{favorites.js => favorites.ts} | 31 +++---- .../i/{notifications.js => notifications.ts} | 50 +++++------ .../{signin_history.js => signin_history.ts} | 34 ++++---- src/api/endpoints/i/{update.js => update.ts} | 17 +--- src/api/endpoints/posts/create.ts | 19 ++--- src/api/it.ts | 84 +++++++++---------- 9 files changed, 104 insertions(+), 157 deletions(-) rename src/api/endpoints/i/appdata/{get.js => get.ts} (100%) rename src/api/endpoints/i/appdata/{set.js => set.ts} (100%) rename src/api/endpoints/i/{authorized_apps.js => authorized_apps.ts} (60%) rename src/api/endpoints/i/{favorites.js => favorites.ts} (52%) rename src/api/endpoints/i/{notifications.js => notifications.ts} (59%) rename src/api/endpoints/i/{signin_history.js => signin_history.ts} (57%) rename src/api/endpoints/i/{update.js => update.ts} (89%) diff --git a/src/api/endpoints/i/appdata/get.js b/src/api/endpoints/i/appdata/get.ts similarity index 100% rename from src/api/endpoints/i/appdata/get.js rename to src/api/endpoints/i/appdata/get.ts diff --git a/src/api/endpoints/i/appdata/set.js b/src/api/endpoints/i/appdata/set.ts similarity index 100% rename from src/api/endpoints/i/appdata/set.js rename to src/api/endpoints/i/appdata/set.ts diff --git a/src/api/endpoints/i/authorized_apps.js b/src/api/endpoints/i/authorized_apps.ts similarity index 60% rename from src/api/endpoints/i/authorized_apps.js rename to src/api/endpoints/i/authorized_apps.ts index 3c0cf75057..fb56a107e7 100644 --- a/src/api/endpoints/i/authorized_apps.js +++ b/src/api/endpoints/i/authorized_apps.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import AccessToken from '../../models/access-token'; import serialize from '../../serializers/app'; @@ -18,28 +18,16 @@ 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 [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); // Get 'sort' parameter - 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 param'); // Get tokens const tokens = await AccessToken diff --git a/src/api/endpoints/i/favorites.js b/src/api/endpoints/i/favorites.ts similarity index 52% rename from src/api/endpoints/i/favorites.js rename to src/api/endpoints/i/favorites.ts index 28e402e366..c04d318379 100644 --- a/src/api/endpoints/i/favorites.js +++ b/src/api/endpoints/i/favorites.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Favorite from '../../models/favorite'; import serialize from '../../serializers/post'; @@ -11,37 +11,26 @@ import serialize from '../../serializers/post'; * Get followers of a user * * @param {any} params + * @param {any} user * @return {Promise} */ -module.exports = (params) => +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 [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); // Get 'offset' parameter - let offset = params.offset; - if (offset !== undefined && offset !== null) { - offset = parseInt(offset, 10); - } else { - offset = 0; - } + const [offset, offsetErr] = it(params.offset).expect.number().min(0).default(0).qed(); + if (offsetErr) return rej('invalid offset param'); // Get 'sort' parameter - 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 param'); // Get favorites - const favorites = await Favorites + const favorites = await Favorite .find({ user_id: user._id }, { diff --git a/src/api/endpoints/i/notifications.js b/src/api/endpoints/i/notifications.ts similarity index 59% rename from src/api/endpoints/i/notifications.js rename to src/api/endpoints/i/notifications.ts index d5174439e2..21537ea799 100644 --- a/src/api/endpoints/i/notifications.js +++ b/src/api/endpoints/i/notifications.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Notification from '../../models/notification'; import serialize from '../../serializers/notification'; import getFriends from '../../common/get-friends'; @@ -19,44 +19,38 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'following' parameter - const following = params.following; + const [following, followingError] = + it(params.following).expect.boolean().default(false).qed(); + if (followingError) return rej('invalid following param'); // Get 'mark_as_read' parameter - let markAsRead = params.mark_as_read; - if (markAsRead == null) { - markAsRead = true; - } + 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 - let type = params.type; - if (type !== undefined && type !== null) { - type = type.split(',').map(x => x.trim()); - } + const [type, typeErr] = it(params.type).expect.array().unique().allString().qed(); + if (typeErr) return rej('invalid type param'); // Get 'limit' parameter - let limit = params.limit; - if (limit !== undefined && limit !== null) { - limit = parseInt(limit, 10); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + 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 @@ -77,14 +71,14 @@ module.exports = (params, user) => }; } - if (since !== null) { + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } diff --git a/src/api/endpoints/i/signin_history.js b/src/api/endpoints/i/signin_history.ts similarity index 57% rename from src/api/endpoints/i/signin_history.js rename to src/api/endpoints/i/signin_history.ts index ede821e3cf..db36438bfe 100644 --- a/src/api/endpoints/i/signin_history.js +++ b/src/api/endpoints/i/signin_history.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import Signin from '../../models/signin'; import serialize from '../../serializers/signin'; @@ -18,42 +18,38 @@ 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); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + 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 (since !== null) { + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } diff --git a/src/api/endpoints/i/update.js b/src/api/endpoints/i/update.ts similarity index 89% rename from src/api/endpoints/i/update.js rename to src/api/endpoints/i/update.ts index 4abb4fcb7b..1e46315ceb 100644 --- a/src/api/endpoints/i/update.js +++ b/src/api/endpoints/i/update.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import User from '../../models/user'; import { isValidName, isValidBirthday } from '../../models/user'; import serialize from '../../serializers/user'; @@ -23,18 +23,9 @@ 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; - } + 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; 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; } - /** - * このインスタンスの値が null、またはエラーが存在しているなどして、処理をスキップするべきか否か - */ - get shouldSkip() { - return this.error !== null || this.value === null; + get isEmpty() { + return this.value === undefined || this.value === null; } /** - * このインスタンスの値が undefined または null の場合エラーにします + * このインスタンスの値が空、またはエラーが存在しているなどして、処理をスキップするべきか否か + */ + get shouldSkip() { + return this.error !== null || this.isEmpty; + } + + /** + * このインスタンスの値が空の場合エラーにします */ 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; } } From 665bcda0a7cbf37d5691d48838da85e2f308babc Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 09:15:38 +0900 Subject: [PATCH 34/43] wip --- src/api/endpoints/i/update.ts | 4 +- src/api/it.ts | 78 ++++++++++++++--------------------- 2 files changed, 34 insertions(+), 48 deletions(-) diff --git a/src/api/endpoints/i/update.ts b/src/api/endpoints/i/update.ts index 1e46315ceb..aeda0a4527 100644 --- a/src/api/endpoints/i/update.ts +++ b/src/api/endpoints/i/update.ts @@ -23,9 +23,9 @@ 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(); + const [name, nameErr] = it(params.name).expect.string().notNull().validate(isValidName).qed(); if (nameErr) return rej('invalid name param'); - user.name = name; + if (name) user.name = name; // Get 'description' parameter const description = params.description; diff --git a/src/api/it.ts b/src/api/it.ts index b08612c709..14f6063b24 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -53,8 +53,16 @@ class QueryCore implements Query { this.error = null; } + get isUndefined() { + return this.value === undefined; + } + + get isNull() { + return this.value === null; + } + get isEmpty() { - return this.value === undefined || this.value === null; + return this.isUndefined || this.isNull; } /** @@ -65,7 +73,7 @@ class QueryCore implements Query { } /** - * このインスタンスの値が空の場合エラーにします + * このインスタンスの値が空のときにエラーにします */ required() { if (this.error === null && this.isEmpty) { @@ -75,10 +83,30 @@ class QueryCore implements Query { } /** - * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します + * このインスタンスの値が設定されていない(=undefined)場合エラーにします + */ + notUndefined() { + if (this.error === null && this.isUndefined) { + this.error = new Error('required'); + } + return this; + } + + /** + * このインスタンスの値が null のときにエラーにします + */ + notNull() { + if (this.error === null && this.isNull) { + this.error = new Error('required'); + } + return this; + } + + /** + * このインスタンスの値が設定されていない(=undefined)ときにデフォルトで設定する値を設定します */ default(value: any) { - if (this.isEmpty) { + if (this.isUndefined) { this.value = value; } return this; @@ -119,13 +147,6 @@ class BooleanQuery extends QueryCore { } } - /** - * このインスタンスの値が undefined または null の場合エラーにします - */ - required() { - return super.required(); - } - /** * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します */ @@ -198,13 +219,6 @@ class NumberQuery extends QueryCore { return this; } - /** - * このインスタンスの値が undefined または null の場合エラーにします - */ - required() { - return super.required(); - } - /** * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します */ @@ -259,13 +273,6 @@ class StringQuery extends QueryCore { return this; } - /** - * このインスタンスの値が undefined または null の場合エラーにします - */ - required() { - return super.required(); - } - /** * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します */ @@ -361,13 +368,6 @@ class ArrayQuery extends QueryCore { return this; } - /** - * このインスタンスの値が undefined または null の場合エラーにします - */ - required() { - return super.required(); - } - /** * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します */ @@ -403,13 +403,6 @@ class IdQuery extends QueryCore { } } - /** - * このインスタンスの値が undefined または null の場合エラーにします - */ - required() { - return super.required(); - } - /** * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します */ @@ -445,13 +438,6 @@ class ObjectQuery extends QueryCore { } } - /** - * このインスタンスの値が undefined または null の場合エラーにします - */ - required() { - return super.required(); - } - /** * このインスタンスの値が設定されていないときにデフォルトで設定する値を設定します */ From 42ed35bfc95147c89cb0dc3d61d8982b2646c1ca Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 09:24:17 +0900 Subject: [PATCH 35/43] wip --- src/api/endpoints/i/update.ts | 51 +++++++++++------------------------ src/api/models/user.ts | 8 ++++++ 2 files changed, 24 insertions(+), 35 deletions(-) diff --git a/src/api/endpoints/i/update.ts b/src/api/endpoints/i/update.ts index aeda0a4527..e3b307b0b9 100644 --- a/src/api/endpoints/i/update.ts +++ b/src/api/endpoints/i/update.ts @@ -5,7 +5,7 @@ */ import it from '../../it'; import User from '../../models/user'; -import { isValidName, isValidBirthday } from '../../models/user'; +import { isValidName, isValidDescription, isValidLocation, isValidBirthday } from '../../models/user'; import serialize from '../../serializers/user'; import event from '../../event'; import config from '../../../conf'; @@ -28,48 +28,29 @@ module.exports = async (params, user, _, isSecure) => if (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; - } + const [description, descriptionErr] = it(params.description).expect.string().validate(isValidDescription).qed(); + if (descriptionErr) return rej('invalid description param'); + if (description !== undefined) 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; - } + const [location, locationErr] = it(params.location).expect.string().validate(isValidLocation).qed(); + if (locationErr) return rej('invalid location param'); + if (location !== undefined) user.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; - } + const [birthday, birthdayErr] = it(params.birthday).expect.string().validate(isValidBirthday).qed(); + if (birthdayErr) return rej('invalid birthday param'); + if (birthday !== undefined) user.birthday = birthday; // Get 'avatar_id' parameter - const avatar = params.avatar_id; - if (avatar !== undefined && avatar !== null) { - user.avatar_id = new mongo.ObjectID(avatar); - } + const [avatarId, avatarIdErr] = it(params.avatar_id).expect.id().notNull().qed(); + if (avatarIdErr) return rej('invalid avatar_id param'); + if (avatarId) user.avatar_id = avatarId; // Get 'banner_id' parameter - const banner = params.banner_id; - if (banner !== undefined && banner !== null) { - user.banner_id = new mongo.ObjectID(banner); - } + const [bannerId, bannerIdErr] = it(params.banner_id).expect.id().notNull().qed(); + if (bannerIdErr) return rej('invalid banner_id param'); + if (bannerId) user.banner_id = bannerId; await User.update(user._id, { $set: { diff --git a/src/api/models/user.ts b/src/api/models/user.ts index 5ab39d7c92..cd16459891 100644 --- a/src/api/models/user.ts +++ b/src/api/models/user.ts @@ -19,6 +19,14 @@ export function isValidName(name: string): boolean { return typeof name == 'string' && name.length < 30 && name.trim() != ''; } +export function isValidDescription(description: string): boolean { + return typeof description == 'string' && description.length < 500 && description.trim() != ''; +} + +export function isValidLocation(location: string): boolean { + return typeof location == 'string' && location.length < 50 && location.trim() != ''; +} + export function isValidBirthday(birthday: string): boolean { return typeof birthday == 'string' && /^([0-9]{4})\-([0-9]{2})-([0-9]{2})$/.test(birthday); } From 1e1800fd666fce3f06712c005bd63503672cb346 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?syuilo=E2=AD=90=EF=B8=8F?= Date: Fri, 3 Mar 2017 09:48:06 +0900 Subject: [PATCH 36/43] Update it.ts --- src/api/it.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/api/it.ts b/src/api/it.ts index 14f6063b24..21cc872a2f 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -26,6 +26,30 @@ * const [val, err] = it(x).expect.string().required().qed(); */ +/** + * null と undefined の扱い + * + * 「値がnullまたはundefined」な状態を「値が空である」と表現しています。 + * 値が空である場合、バリデータやその他の処理メソッドは呼ばれません。 + * + * 内部的にはnullとundefinedを次のように区別しています: + * null ... 値が「無い」と明示されている + * undefined ... 値を指定していない + * + * 例えばアカウントのプロフィールを更新するAPIに次のデータを含むリクエストが来たとします: + * { name: 'Alice' } + * アカウントには本来、他にも birthday といったフィールドがありますが、 + * このリクエストではそれに触れず、ただ単に name フィールドを更新することを要求しています。 + * ここで、このリクエストにおける birthday フィールドは undefined なわけですが、 + * それはnull(=birthdayを未設定にしたい)とは違うものです。 + * undefined も null も区別しないとしたら、触れていないフィールドまでリセットされることになってしまいます。 + * ですので、undefined と null は区別しています。 + * + * 値が空であってほしくない場合は .require() を、 + * 値を必ず指定しなければならない場合(値を「無し」に指定することは許可)は .notUndefined() を、 + * 値の指定をしなくてもいいけど、する場合は「無し」は許可しない場合は .notNull() を使えます。 + */ + import * as mongo from 'mongodb'; import hasDuplicates from '../common/has-duplicates'; From 3ca7a442aba27f8ccf374c9f68c1082da0b5a943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?syuilo=E2=AD=90=EF=B8=8F?= Date: Fri, 3 Mar 2017 09:56:58 +0900 Subject: [PATCH 37/43] Update it.ts --- src/api/it.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api/it.ts b/src/api/it.ts index 21cc872a2f..f540172ad3 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -15,6 +15,8 @@ * const [val, err] = it(x).must.be.an.array().unique().required().validate(x => x[0] != 'strawberry pasta').qed(); * → xは配列でなければならず、かつ中身が重複していてはならない。この値を省略することはできない。そして配列の最初の要素が'strawberry pasta'という文字列であってはならない。 * + * ・意味的に矛盾するので、required と default は併用できません。 + * * ~糖衣構文~ * const [val, err] = it(x).must.be.a.string().required().qed(); * は From e0c44abd4a0b034474badeadf4d03b81d8a59ed9 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 10:24:56 +0900 Subject: [PATCH 38/43] =?UTF-8?q?=E3=81=84=E3=81=84=E6=84=9F=E3=81=98?= =?UTF-8?q?=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/endpoints/i/update.ts | 8 ++-- src/api/it.ts | 71 ++++++++++++++++++++++++++--------- 2 files changed, 58 insertions(+), 21 deletions(-) diff --git a/src/api/endpoints/i/update.ts b/src/api/endpoints/i/update.ts index e3b307b0b9..a5f1538610 100644 --- a/src/api/endpoints/i/update.ts +++ b/src/api/endpoints/i/update.ts @@ -23,22 +23,22 @@ module.exports = async (params, user, _, isSecure) => new Promise(async (res, rej) => { // Get 'name' parameter - const [name, nameErr] = it(params.name).expect.string().notNull().validate(isValidName).qed(); + const [name, nameErr] = it(params.name).expect.string().validate(isValidName).qed(); if (nameErr) return rej('invalid name param'); if (name) user.name = name; // Get 'description' parameter - const [description, descriptionErr] = it(params.description).expect.string().validate(isValidDescription).qed(); + const [description, descriptionErr] = it(params.description).expect.nullable.string().validate(isValidDescription).qed(); if (descriptionErr) return rej('invalid description param'); if (description !== undefined) user.description = description; // Get 'location' parameter - const [location, locationErr] = it(params.location).expect.string().validate(isValidLocation).qed(); + const [location, locationErr] = it(params.location).expect.nullable.string().validate(isValidLocation).qed(); if (locationErr) return rej('invalid location param'); if (location !== undefined) user.location = location; // Get 'birthday' parameter - const [birthday, birthdayErr] = it(params.birthday).expect.string().validate(isValidBirthday).qed(); + const [birthday, birthdayErr] = it(params.birthday).expect.nullable.string().validate(isValidBirthday).qed(); if (birthdayErr) return rej('invalid birthday param'); if (birthday !== undefined) user.birthday = birthday; diff --git a/src/api/it.ts b/src/api/it.ts index f540172ad3..845a56365c 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -74,9 +74,14 @@ class QueryCore implements Query { value: any; error: Error; - constructor(value: any) { - this.value = value; - this.error = null; + constructor(value: any, nullable: boolean = false) { + if (value === null && !nullable) { + this.value = undefined; + this.error = new Error('must-be-not-a-null'); + } else { + this.value = value; + this.error = null; + } } get isUndefined() { @@ -166,8 +171,8 @@ class BooleanQuery extends QueryCore { value: boolean; error: Error; - constructor(value) { - super(value); + constructor(value: any, nullable: boolean = false) { + super(value, nullable); if (!this.isEmpty && typeof value != 'boolean') { this.error = new Error('must-be-a-boolean'); } @@ -201,8 +206,8 @@ class NumberQuery extends QueryCore { value: number; error: Error; - constructor(value) { - super(value); + constructor(value: any, nullable: boolean = false) { + super(value, nullable); if (!this.isEmpty && !Number.isFinite(value)) { this.error = new Error('must-be-a-number'); } @@ -273,8 +278,8 @@ class StringQuery extends QueryCore { value: string; error: Error; - constructor(value) { - super(value); + constructor(value: any, nullable: boolean = false) { + super(value, nullable); if (!this.isEmpty && typeof value != 'string') { this.error = new Error('must-be-a-string'); } @@ -351,8 +356,8 @@ class ArrayQuery extends QueryCore { value: any[]; error: Error; - constructor(value) { - super(value); + constructor(value: any, nullable: boolean = false) { + super(value, nullable); if (!this.isEmpty && !Array.isArray(value)) { this.error = new Error('must-be-an-array'); } @@ -422,8 +427,8 @@ class IdQuery extends QueryCore { value: mongo.ObjectID; error: Error; - constructor(value) { - super(value); + constructor(value: any, nullable: boolean = false) { + super(value, nullable); if (!this.isEmpty && (typeof value != 'string' || !mongo.ObjectID.isValid(value))) { this.error = new Error('must-be-an-id'); } @@ -457,8 +462,8 @@ class ObjectQuery extends QueryCore { value: any; error: Error; - constructor(value) { - super(value); + constructor(value: any, nullable: boolean = false) { + super(value, nullable); if (!this.isEmpty && typeof value != 'object') { this.error = new Error('must-be-an-object'); } @@ -495,6 +500,14 @@ type It = { string: () => StringQuery; number: () => NumberQuery; boolean: () => BooleanQuery; + nullable: { + string: () => StringQuery; + number: () => NumberQuery; + boolean: () => BooleanQuery; + id: () => IdQuery; + array: () => ArrayQuery; + object: () => ObjectQuery; + }; }; an: { id: () => IdQuery; @@ -510,6 +523,14 @@ type It = { id: () => IdQuery; array: () => ArrayQuery; object: () => ObjectQuery; + nullable: { + string: () => StringQuery; + number: () => NumberQuery; + boolean: () => BooleanQuery; + id: () => IdQuery; + array: () => ArrayQuery; + object: () => ObjectQuery; + }; }; }; @@ -519,7 +540,15 @@ const it = (value: any) => ({ a: { string: () => new StringQuery(value), number: () => new NumberQuery(value), - boolean: () => new BooleanQuery(value) + boolean: () => new BooleanQuery(value), + nullable: { + string: () => new StringQuery(value, true), + number: () => new NumberQuery(value, true), + boolean: () => new BooleanQuery(value, true), + id: () => new IdQuery(value, true), + array: () => new ArrayQuery(value, true), + object: () => new ObjectQuery(value, true) + } }, an: { id: () => new IdQuery(value), @@ -534,7 +563,15 @@ const it = (value: any) => ({ boolean: () => new BooleanQuery(value), id: () => new IdQuery(value), array: () => new ArrayQuery(value), - object: () => new ObjectQuery(value) + object: () => new ObjectQuery(value), + nullable: { + string: () => new StringQuery(value, true), + number: () => new NumberQuery(value, true), + boolean: () => new BooleanQuery(value, true), + id: () => new IdQuery(value, true), + array: () => new ArrayQuery(value, true), + object: () => new ObjectQuery(value, true) + } } }); From 73ac13a274ec2eac8f909a84c23296836d833430 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 10:31:59 +0900 Subject: [PATCH 39/43] =?UTF-8?q?=E3=81=84=E3=81=84=E6=84=9F=E3=81=98?= =?UTF-8?q?=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/it.ts | 32 ++++++-------------------------- 1 file changed, 6 insertions(+), 26 deletions(-) diff --git a/src/api/it.ts b/src/api/it.ts index 845a56365c..df49985833 100644 --- a/src/api/it.ts +++ b/src/api/it.ts @@ -31,10 +31,10 @@ /** * null と undefined の扱い * - * 「値がnullまたはundefined」な状態を「値が空である」と表現しています。 + * 「値が null または undefined」な状態を「値が空である」と表現しています。 * 値が空である場合、バリデータやその他の処理メソッドは呼ばれません。 * - * 内部的にはnullとundefinedを次のように区別しています: + * 内部的には null と undefined を次のように区別しています: * null ... 値が「無い」と明示されている * undefined ... 値を指定していない * @@ -47,9 +47,9 @@ * undefined も null も区別しないとしたら、触れていないフィールドまでリセットされることになってしまいます。 * ですので、undefined と null は区別しています。 * - * 値が空であってほしくない場合は .require() を、 - * 値を必ず指定しなければならない場合(値を「無し」に指定することは許可)は .notUndefined() を、 - * 値の指定をしなくてもいいけど、する場合は「無し」は許可しない場合は .notNull() を使えます。 + * 明示的に null を許可しない限り、null はエラーになります。 + * null を許可する場合は nullable をプリフィックスします: + * const [val, err] = it(x).must.be.a.nullable.string().required().qed(); */ import * as mongo from 'mongodb'; @@ -104,35 +104,15 @@ class QueryCore implements Query { } /** - * このインスタンスの値が空のときにエラーにします + * このインスタンスの値が指定されていない(=undefined)ときにエラーにします */ required() { - if (this.error === null && this.isEmpty) { - this.error = new Error('required'); - } - return this; - } - - /** - * このインスタンスの値が設定されていない(=undefined)場合エラーにします - */ - notUndefined() { if (this.error === null && this.isUndefined) { this.error = new Error('required'); } return this; } - /** - * このインスタンスの値が null のときにエラーにします - */ - notNull() { - if (this.error === null && this.isNull) { - this.error = new Error('required'); - } - return this; - } - /** * このインスタンスの値が設定されていない(=undefined)ときにデフォルトで設定する値を設定します */ From e2461a9314026d95d5baaea864c5282eed7c5504 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 19:33:14 +0900 Subject: [PATCH 40/43] wip --- .../endpoints/drive/{files.js => files.ts} | 44 ++++++++---------- .../drive/files/{create.js => create.ts} | 14 ++---- .../drive/files/{find.js => find.ts} | 18 +++----- .../drive/files/{show.js => show.ts} | 11 ++--- .../drive/files/{update.js => update.ts} | 40 +++++----------- ...{upload_from_url.js => upload_from_url.ts} | 20 +++----- .../drive/{folders.js => folders.ts} | 44 ++++++++---------- .../drive/folders/{create.js => create.ts} | 34 ++++---------- .../drive/folders/{find.js => find.ts} | 16 ++----- .../drive/folders/{show.js => show.ts} | 10 ++-- .../drive/folders/{update.js => update.ts} | 37 ++++----------- .../endpoints/drive/{stream.js => stream.ts} | 46 ++++++++----------- .../following/{create.js => create.ts} | 15 ++---- .../following/{delete.js => delete.ts} | 15 ++---- 14 files changed, 122 insertions(+), 242 deletions(-) rename src/api/endpoints/drive/{files.js => files.ts} (53%) rename src/api/endpoints/drive/files/{create.js => create.ts} (80%) rename src/api/endpoints/drive/files/{find.js => find.ts} (65%) rename src/api/endpoints/drive/files/{show.js => show.ts} (75%) rename src/api/endpoints/drive/files/{update.js => update.ts} (67%) rename src/api/endpoints/drive/files/{upload_from_url.js => upload_from_url.ts} (66%) rename src/api/endpoints/drive/{folders.js => folders.ts} (53%) rename src/api/endpoints/drive/folders/{create.js => create.ts} (63%) rename src/api/endpoints/drive/folders/{find.js => find.ts} (67%) rename src/api/endpoints/drive/folders/{show.js => show.ts} (74%) rename src/api/endpoints/drive/folders/{update.js => update.ts} (74%) rename src/api/endpoints/drive/{stream.js => stream.ts} (52%) rename src/api/endpoints/following/{create.js => create.ts} (85%) rename src/api/endpoints/following/{delete.js => delete.ts} (83%) diff --git a/src/api/endpoints/drive/files.js b/src/api/endpoints/drive/files.ts similarity index 53% rename from src/api/endpoints/drive/files.js rename to src/api/endpoints/drive/files.ts index cbfe720266..c1441c554b 100644 --- a/src/api/endpoints/drive/files.js +++ b/src/api/endpoints/drive/files.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import DriveFile from '../../models/drive-file'; import serialize from '../../serializers/drive-file'; @@ -19,33 +19,25 @@ 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); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + if (sinceId !== null && maxId !== null) { return rej('cannot set since_id and max_id'); } // Get 'folder_id' parameter - let folder = params.folder_id; - if (folder === undefined || folder === null) { - folder = null; - } else { - folder = new mongo.ObjectID(folder); - } + const [folderId, folderIdErr] = it(params.folder_id).expect.nullable.id().default(null).qed(); + if (folderIdErr) return rej('invalid folder_id param'); // Construct query const sort = { @@ -53,16 +45,16 @@ module.exports = (params, user, app) => }; const query = { user_id: user._id, - folder_id: folder - }; - if (since !== null) { + folder_id: folderId + } as any; + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } diff --git a/src/api/endpoints/drive/files/create.js b/src/api/endpoints/drive/files/create.ts similarity index 80% rename from src/api/endpoints/drive/files/create.js rename to src/api/endpoints/drive/files/create.ts index 9690b05cfd..7efd149813 100644 --- a/src/api/endpoints/drive/files/create.js +++ b/src/api/endpoints/drive/files/create.ts @@ -4,10 +4,8 @@ * Module dependencies */ import * as fs from 'fs'; -import * as mongo from 'mongodb'; -import File from '../../../models/drive-file'; +import it from '../../../it'; import { validateFileName } from '../../../models/drive-file'; -import User from '../../../models/user'; import serialize from '../../../serializers/drive-file'; import create from '../../../common/add-file-to-drive'; @@ -45,15 +43,11 @@ module.exports = (file, params, user) => } // Get 'folder_id' parameter - let folder = params.folder_id; - if (folder === undefined || folder === null) { - folder = null; - } else { - folder = new mongo.ObjectID(folder); - } + const [folderId, folderIdErr] = it(params.folder_id).expect.nullable.id().default(null).qed(); + if (folderIdErr) return rej('invalid folder_id param'); // Create file - const driveFile = await create(user, buffer, name, null, folder); + const driveFile = await create(user, buffer, name, null, folderId); // Serialize const fileObj = await serialize(driveFile); diff --git a/src/api/endpoints/drive/files/find.js b/src/api/endpoints/drive/files/find.ts similarity index 65% rename from src/api/endpoints/drive/files/find.js rename to src/api/endpoints/drive/files/find.ts index 358767c5ed..393b8c5b98 100644 --- a/src/api/endpoints/drive/files/find.js +++ b/src/api/endpoints/drive/files/find.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import DriveFile from '../../../models/drive-file'; import serialize from '../../../serializers/drive-file'; @@ -18,25 +18,19 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'name' parameter - const name = params.name; - if (name === undefined || name === null) { - return rej('name is required'); - } + const [name, nameErr] = it(params.name).expect.string().required().qed(); + if (nameErr) return rej('invalid name param'); // Get 'folder_id' parameter - let folder = params.folder_id; - if (folder === undefined || folder === null) { - folder = null; - } else { - folder = new mongo.ObjectID(folder); - } + const [folderId, folderIdErr] = it(params.folder_id).expect.nullable.id().default(null).qed(); + if (folderIdErr) return rej('invalid folder_id param'); // Issue query const files = await DriveFile .find({ name: name, user_id: user._id, - folder_id: folder + folder_id: folderId }, { fields: { data: false diff --git a/src/api/endpoints/drive/files/show.js b/src/api/endpoints/drive/files/show.ts similarity index 75% rename from src/api/endpoints/drive/files/show.js rename to src/api/endpoints/drive/files/show.ts index 5ae98a4a7c..2024a56ca6 100644 --- a/src/api/endpoints/drive/files/show.js +++ b/src/api/endpoints/drive/files/show.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import DriveFile from '../../../models/drive-file'; import serialize from '../../../serializers/drive-file'; @@ -18,14 +18,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'file_id' parameter - const fileId = params.file_id; - if (fileId === undefined || fileId === null) { - return rej('file_id is required'); - } + const [fileId, fileIdErr] = it(params.file_id).expect.id().required().qed(); + if (fileIdErr) return rej('invalid file_id param'); + // Fetch file const file = await DriveFile .findOne({ - _id: new mongo.ObjectID(fileId), + _id: fileId, user_id: user._id }, { fields: { diff --git a/src/api/endpoints/drive/files/update.js b/src/api/endpoints/drive/files/update.ts similarity index 67% rename from src/api/endpoints/drive/files/update.js rename to src/api/endpoints/drive/files/update.ts index 8e2ff33e9d..595d501658 100644 --- a/src/api/endpoints/drive/files/update.js +++ b/src/api/endpoints/drive/files/update.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import DriveFolder from '../../../models/drive-folder'; import DriveFile from '../../../models/drive-file'; import { validateFileName } from '../../../models/drive-file'; @@ -21,19 +21,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'file_id' parameter - const fileId = params.file_id; - if (fileId === undefined || fileId === null) { - return rej('file_id is required'); - } - - // Validate id - if (!mongo.ObjectID.isValid(fileId)) { - return rej('incorrect file_id'); - } + const [fileId, fileIdErr] = it(params.file_id).expect.id().required().qed(); + if (fileIdErr) return rej('invalid file_id param'); + // Fetch file const file = await DriveFile .findOne({ - _id: new mongo.ObjectID(fileId), + _id: fileId, user_id: user._id }, { fields: { @@ -46,29 +40,19 @@ module.exports = (params, user) => } // Get 'name' parameter - let name = params.name; - if (name) { - name = name.trim(); - if (validateFileName(name)) { - file.name = name; - } else { - return rej('invalid file name'); - } - } + const [name, nameErr] = it(params.name).expect.string().validate(validateFileName).qed(); + if (nameErr) return rej('invalid name param'); + if (name) file.name = name; // Get 'folder_id' parameter - let folderId = params.folder_id; + const [folderId, folderIdErr] = it(params.folder_id).expect.nullable.id().qed(); + if (folderIdErr) return rej('invalid folder_id param'); + if (folderId !== undefined) { if (folderId === null) { file.folder_id = null; } else { - // Validate id - if (!mongo.ObjectID.isValid(folderId)) { - return rej('incorrect folder_id'); - } - - folderId = new mongo.ObjectID(folderId); - + // Fetch folder const folder = await DriveFolder .findOne({ _id: folderId, diff --git a/src/api/endpoints/drive/files/upload_from_url.js b/src/api/endpoints/drive/files/upload_from_url.ts similarity index 66% rename from src/api/endpoints/drive/files/upload_from_url.js rename to src/api/endpoints/drive/files/upload_from_url.ts index 3619a6f107..b6f4789317 100644 --- a/src/api/endpoints/drive/files/upload_from_url.js +++ b/src/api/endpoints/drive/files/upload_from_url.ts @@ -5,10 +5,8 @@ */ import * as URL from 'url'; const download = require('download'); -import * as mongo from 'mongodb'; -import File from '../../../models/drive-file'; +import it from '../../../it'; import { validateFileName } from '../../../models/drive-file'; -import User from '../../../models/user'; import serialize from '../../../serializers/drive-file'; import create from '../../../common/add-file-to-drive'; @@ -24,10 +22,8 @@ module.exports = (params, user) => { // Get 'url' parameter // TODO: Validate this url - const url = params.url; - if (url == null) { - return rej('url is required'); - } + const [url, urlErr] = it(params.url).expect.string().required().qed(); + if (urlErr) return rej('invalid url param'); let name = URL.parse(url).pathname.split('/').pop(); if (!validateFileName(name)) { @@ -35,18 +31,14 @@ module.exports = (params, user) => } // Get 'folder_id' parameter - let folder = params.folder_id; - if (folder === undefined || folder === null) { - folder = null; - } else { - folder = new mongo.ObjectID(folder); - } + const [folderId, folderIdErr] = it(params.folder_id).expect.nullable.id().default(null).qed(); + if (folderIdErr) return rej('invalid folder_id param'); // Download file const data = await download(url); // Create file - const driveFile = await create(user, data, name, null, folder); + const driveFile = await create(user, data, name, null, folderId); // Serialize const fileObj = await serialize(driveFile); diff --git a/src/api/endpoints/drive/folders.js b/src/api/endpoints/drive/folders.ts similarity index 53% rename from src/api/endpoints/drive/folders.js rename to src/api/endpoints/drive/folders.ts index 631d68769f..3f4a5bac0e 100644 --- a/src/api/endpoints/drive/folders.js +++ b/src/api/endpoints/drive/folders.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import DriveFolder from '../../models/drive-folder'; import serialize from '../../serializers/drive-folder'; @@ -19,33 +19,25 @@ 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); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + if (sinceId !== null && maxId !== null) { return rej('cannot set since_id and max_id'); } // Get 'folder_id' parameter - let folder = params.folder_id; - if (folder === undefined || folder === null) { - folder = null; - } else { - folder = new mongo.ObjectID(folder); - } + const [folderId, folderIdErr] = it(params.folder_id).expect.nullable.id().default(null).qed(); + if (folderIdErr) return rej('invalid folder_id param'); // Construct query const sort = { @@ -53,16 +45,16 @@ module.exports = (params, user, app) => }; const query = { user_id: user._id, - parent_id: folder - }; - if (since !== null) { + parent_id: folderId + } as any; + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } diff --git a/src/api/endpoints/drive/folders/create.js b/src/api/endpoints/drive/folders/create.ts similarity index 63% rename from src/api/endpoints/drive/folders/create.js rename to src/api/endpoints/drive/folders/create.ts index 9ba989c212..d327572af7 100644 --- a/src/api/endpoints/drive/folders/create.js +++ b/src/api/endpoints/drive/folders/create.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import DriveFolder from '../../../models/drive-folder'; import { isValidFolderName } from '../../../models/drive-folder'; import serialize from '../../../serializers/drive-folder'; @@ -20,33 +20,17 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'name' parameter - let name = params.name; - if (name !== undefined && name !== null) { - name = name.trim(); - if (name.length === 0) { - name = null; - } else if (!isValidFolderName(name)) { - return rej('invalid name'); - } - } else { - name = null; - } + const [name, nameErr] = it(params.name).expect.string().validate(isValidFolderName).default('無題のフォルダー').qed(); + if (nameErr) return rej('invalid name param'); - if (name == null) { - name = '無題のフォルダー'; - } - - // Get 'folder_id' parameter - let parentId = params.folder_id; - if (parentId === undefined || parentId === null) { - parentId = null; - } else { - parentId = new mongo.ObjectID(parentId); - } + // Get 'parent_id' parameter + const [parentId, parentIdErr] = it(params.parent_id).expect.nullable.id().default(null).qed(); + if (parentIdErr) return rej('invalid parent_id param'); // If the parent folder is specified let parent = null; - if (parentId !== null) { + if (parentId) { + // Fetch parent folder parent = await DriveFolder .findOne({ _id: parentId, @@ -54,7 +38,7 @@ module.exports = (params, user) => }); if (parent === null) { - return reject('parent-not-found'); + return rej('parent-not-found'); } } diff --git a/src/api/endpoints/drive/folders/find.js b/src/api/endpoints/drive/folders/find.ts similarity index 67% rename from src/api/endpoints/drive/folders/find.js rename to src/api/endpoints/drive/folders/find.ts index 802d3a7909..041e9ccb2a 100644 --- a/src/api/endpoints/drive/folders/find.js +++ b/src/api/endpoints/drive/folders/find.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import DriveFolder from '../../../models/drive-folder'; import serialize from '../../../serializers/drive-folder'; @@ -18,18 +18,12 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'name' parameter - const name = params.name; - if (name === undefined || name === null) { - return rej('name is required'); - } + const [name, nameErr] = it(params.name).expect.string().required().qed(); + if (nameErr) return rej('invalid name param'); // Get 'parent_id' parameter - let parentId = params.parent_id; - if (parentId === undefined || parentId === null) { - parentId = null; - } else { - parentId = new mongo.ObjectID(parentId); - } + const [parentId, parentIdErr] = it(params.parent_id).expect.id().qed(); + if (parentIdErr) return rej('invalid parent_id param'); // Issue query const folders = await DriveFolder diff --git a/src/api/endpoints/drive/folders/show.js b/src/api/endpoints/drive/folders/show.ts similarity index 74% rename from src/api/endpoints/drive/folders/show.js rename to src/api/endpoints/drive/folders/show.ts index 986d32cf60..3b3ed41719 100644 --- a/src/api/endpoints/drive/folders/show.js +++ b/src/api/endpoints/drive/folders/show.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import DriveFolder from '../../../models/drive-folder'; import serialize from '../../../serializers/drive-folder'; @@ -18,15 +18,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'folder_id' parameter - const folderId = params.folder_id; - if (folderId === undefined || folderId === null) { - return rej('folder_id is required'); - } + const [folderId, folderIdErr] = it(params.folder_id).expect.id().required().qed(); + if (folderIdErr) return rej('invalid folder_id param'); // Get folder const folder = await DriveFolder .findOne({ - _id: new mongo.ObjectID(folderId), + _id: folderId, user_id: user._id }); diff --git a/src/api/endpoints/drive/folders/update.js b/src/api/endpoints/drive/folders/update.ts similarity index 74% rename from src/api/endpoints/drive/folders/update.js rename to src/api/endpoints/drive/folders/update.ts index 713e17b43e..81d414354c 100644 --- a/src/api/endpoints/drive/folders/update.js +++ b/src/api/endpoints/drive/folders/update.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import DriveFolder from '../../../models/drive-folder'; import { isValidFolderName } from '../../../models/drive-folder'; import serialize from '../../../serializers/drive-file'; @@ -20,20 +20,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'folder_id' parameter - const folderId = params.folder_id; - if (folderId === undefined || folderId === null) { - return rej('folder_id is required'); - } - - // Validate id - if (!mongo.ObjectID.isValid(folderId)) { - return rej('incorrect folder_id'); - } + const [folderId, folderIdErr] = it(params.folder_id).expect.id().required().qed(); + if (folderIdErr) return rej('invalid folder_id param'); // Fetch folder const folder = await DriveFolder .findOne({ - _id: new mongo.ObjectID(folderId), + _id: folderId, user_id: user._id }); @@ -42,29 +35,17 @@ module.exports = (params, user) => } // Get 'name' parameter - let name = params.name; - if (name) { - name = name.trim(); - if (isValidFolderName(name)) { - folder.name = name; - } else { - return rej('invalid folder name'); - } - } + const [name, nameErr] = it(params.name).expect.string().validate(isValidFolderName).qed(); + if (nameErr) return rej('invalid name param'); + if (name) folder.name = name; // Get 'parent_id' parameter - let parentId = params.parent_id; + const [parentId, parentIdErr] = it(params.parent_id).expect.nullable.id().qed(); + if (parentIdErr) return rej('invalid parent_id param'); if (parentId !== undefined) { if (parentId === null) { folder.parent_id = null; } else { - // Validate id - if (!mongo.ObjectID.isValid(parentId)) { - return rej('incorrect parent_id'); - } - - parentId = new mongo.ObjectID(parentId); - // Get parent folder const parent = await DriveFolder .findOne({ diff --git a/src/api/endpoints/drive/stream.js b/src/api/endpoints/drive/stream.ts similarity index 52% rename from src/api/endpoints/drive/stream.js rename to src/api/endpoints/drive/stream.ts index cd39261de8..6ede044f58 100644 --- a/src/api/endpoints/drive/stream.js +++ b/src/api/endpoints/drive/stream.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import DriveFile from '../../models/drive-file'; import serialize from '../../serializers/drive-file'; @@ -18,35 +18,25 @@ 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); + const [limit, limitErr] = it(params.limit).expect.number().range(1, 100).default(10).qed(); + if (limitErr) return rej('invalid limit param'); - // From 1 to 100 - if (!(1 <= limit && limit <= 100)) { - return rej('invalid limit range'); - } - } else { - limit = 10; - } + // Get 'since_id' parameter + const [sinceId, sinceIdErr] = it(params.since_id).expect.id().qed(); + if (sinceIdErr) return rej('invalid since_id param'); - const since = params.since_id || null; - const max = params.max_id || null; + // 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 (since !== null && max !== null) { + if (sinceId !== null && maxId !== null) { return rej('cannot set since_id and max_id'); } // Get 'type' parameter - let type = params.type; - if (type === undefined || type === null) { - type = null; - } else if (!/^[a-zA-Z\/\-\*]+$/.test(type)) { - return rej('invalid type format'); - } else { - type = new RegExp(`^${type.replace(/\*/g, '.+?')}$`); - } + const [type, typeErr] = it(params.type).expect.string().match(/^[a-zA-Z\/\-\*]+$/).qed(); + if (typeErr) return rej('invalid type param'); // Construct query const sort = { @@ -54,19 +44,19 @@ module.exports = (params, user) => }; const query = { user_id: user._id - }; - if (since !== null) { + } as any; + if (sinceId) { sort._id = 1; query._id = { - $gt: new mongo.ObjectID(since) + $gt: sinceId }; - } else if (max !== null) { + } else if (maxId) { query._id = { - $lt: new mongo.ObjectID(max) + $lt: maxId }; } if (type !== null) { - query.type = type; + query.type = new RegExp(`^${type.replace(/\*/g, '.+?')}$`); } // Issue query diff --git a/src/api/endpoints/following/create.js b/src/api/endpoints/following/create.ts similarity index 85% rename from src/api/endpoints/following/create.js rename to src/api/endpoints/following/create.ts index 46ff77ddf1..0edc122b94 100644 --- a/src/api/endpoints/following/create.js +++ b/src/api/endpoints/following/create.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import User from '../../models/user'; import Following from '../../models/following'; import notify from '../../common/notify'; @@ -23,15 +23,8 @@ module.exports = (params, user) => const follower = user; // Get 'user_id' parameter - let userId = params.user_id; - if (userId === undefined || userId === null) { - return rej('user_id is required'); - } - - // Validate id - if (!mongo.ObjectID.isValid(userId)) { - return rej('incorrect user_id'); - } + const [userId, userIdErr] = it(params.user_id, 'id', true); + if (userIdErr) return rej('invalid user_id param'); // 自分自身 if (user._id.equals(userId)) { @@ -40,7 +33,7 @@ module.exports = (params, user) => // Get followee const followee = await User.findOne({ - _id: new mongo.ObjectID(userId) + _id: userId }, { fields: { data: false, diff --git a/src/api/endpoints/following/delete.js b/src/api/endpoints/following/delete.ts similarity index 83% rename from src/api/endpoints/following/delete.js rename to src/api/endpoints/following/delete.ts index 1085013d03..7f0e908068 100644 --- a/src/api/endpoints/following/delete.js +++ b/src/api/endpoints/following/delete.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import User from '../../models/user'; import Following from '../../models/following'; import event from '../../event'; @@ -22,15 +22,8 @@ module.exports = (params, user) => const follower = user; // Get 'user_id' parameter - let userId = params.user_id; - if (userId === undefined || userId === null) { - return rej('user_id is required'); - } - - // Validate id - if (!mongo.ObjectID.isValid(userId)) { - return rej('incorrect user_id'); - } + const [userId, userIdErr] = it(params.user_id, 'id', true); + if (userIdErr) return rej('invalid user_id param'); // Check if the followee is yourself if (user._id.equals(userId)) { @@ -39,7 +32,7 @@ module.exports = (params, user) => // Get followee const followee = await User.findOne({ - _id: new mongo.ObjectID(userId) + _id: userId }, { fields: { data: false, From d1557bcae8abc45ea655d2fe0cdb6732a0207aa0 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 19:39:41 +0900 Subject: [PATCH 41/43] wip --- src/api/endpoints/auth/{accept.js => accept.ts} | 15 +++++++-------- .../auth/session/{generate.js => generate.ts} | 7 +++---- .../endpoints/auth/session/{show.js => show.ts} | 7 +++---- .../auth/session/{userkey.js => userkey.ts} | 13 +++++-------- 4 files changed, 18 insertions(+), 24 deletions(-) rename src/api/endpoints/auth/{accept.js => accept.ts} (84%) rename src/api/endpoints/auth/session/{generate.js => generate.ts} (89%) rename src/api/endpoints/auth/session/{show.js => show.ts} (91%) rename src/api/endpoints/auth/session/{userkey.js => userkey.ts} (87%) diff --git a/src/api/endpoints/auth/accept.js b/src/api/endpoints/auth/accept.ts similarity index 84% rename from src/api/endpoints/auth/accept.js rename to src/api/endpoints/auth/accept.ts index 1c0b100948..2c104ef1c6 100644 --- a/src/api/endpoints/auth/accept.js +++ b/src/api/endpoints/auth/accept.ts @@ -5,6 +5,7 @@ */ import rndstr from 'rndstr'; const crypto = require('crypto'); +import it from '../../it'; import App from '../../models/app'; import AuthSess from '../../models/auth-session'; import AccessToken from '../../models/access-token'; @@ -43,21 +44,19 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'token' parameter - const sesstoken = params.token; - if (sesstoken == null) { - return rej('token is required'); - } + const [token, tokenErr] = it(params.token).expect.string().required().qed(); + if (tokenErr) return rej('invalid token param'); // Fetch token const session = await AuthSess - .findOne({ token: sesstoken }); + .findOne({ token: token }); if (session === null) { return rej('session not found'); } // Generate access token - const token = rndstr('a-zA-Z0-9', 32); + const accessToken = rndstr('a-zA-Z0-9', 32); // Fetch exist access token const exist = await AccessToken.findOne({ @@ -73,7 +72,7 @@ module.exports = (params, user) => // Generate Hash const sha256 = crypto.createHash('sha256'); - sha256.update(token + app.secret); + sha256.update(accessToken + app.secret); const hash = sha256.digest('hex'); // Insert access token doc @@ -81,7 +80,7 @@ module.exports = (params, user) => created_at: new Date(), app_id: session.app_id, user_id: user._id, - token: token, + token: accessToken, hash: hash }); } diff --git a/src/api/endpoints/auth/session/generate.js b/src/api/endpoints/auth/session/generate.ts similarity index 89% rename from src/api/endpoints/auth/session/generate.js rename to src/api/endpoints/auth/session/generate.ts index cf75b83e2d..6e730123c1 100644 --- a/src/api/endpoints/auth/session/generate.js +++ b/src/api/endpoints/auth/session/generate.ts @@ -4,6 +4,7 @@ * Module dependencies */ import * as uuid from 'uuid'; +import it from '../../../it'; import App from '../../../models/app'; import AuthSess from '../../../models/auth-session'; import config from '../../../../conf'; @@ -49,10 +50,8 @@ module.exports = (params) => new Promise(async (res, rej) => { // Get 'app_secret' parameter - const appSecret = params.app_secret; - if (appSecret == null) { - return rej('app_secret is required'); - } + const [appSecret, appSecretErr] = it(params.app_secret).expect.string().required().qed(); + if (appSecretErr) return rej('invalid app_secret param'); // Lookup app const app = await App.findOne({ diff --git a/src/api/endpoints/auth/session/show.js b/src/api/endpoints/auth/session/show.ts similarity index 91% rename from src/api/endpoints/auth/session/show.js rename to src/api/endpoints/auth/session/show.ts index 425c980d9d..55641929d8 100644 --- a/src/api/endpoints/auth/session/show.js +++ b/src/api/endpoints/auth/session/show.ts @@ -3,6 +3,7 @@ /** * Module dependencies */ +import it from '../../../it'; import AuthSess from '../../../models/auth-session'; import serialize from '../../../serializers/auth-session'; @@ -57,10 +58,8 @@ module.exports = (params, user) => new Promise(async (res, rej) => { // Get 'token' parameter - const token = params.token; - if (token == null) { - return rej('token is required'); - } + const [token, tokenErr] = it(params.token).expect.string().required().qed(); + if (tokenErr) return rej('invalid token param'); // Lookup session const session = await AuthSess.findOne({ diff --git a/src/api/endpoints/auth/session/userkey.js b/src/api/endpoints/auth/session/userkey.ts similarity index 87% rename from src/api/endpoints/auth/session/userkey.js rename to src/api/endpoints/auth/session/userkey.ts index 2c34304a5e..fdb8c26d4e 100644 --- a/src/api/endpoints/auth/session/userkey.js +++ b/src/api/endpoints/auth/session/userkey.ts @@ -3,6 +3,7 @@ /** * Module dependencies */ +import it from '../../../it'; import App from '../../../models/app'; import AuthSess from '../../../models/auth-session'; import AccessToken from '../../../models/access-token'; @@ -53,10 +54,8 @@ import serialize from '../../../serializers/user'; module.exports = (params) => new Promise(async (res, rej) => { // Get 'app_secret' parameter - const appSecret = params.app_secret; - if (appSecret == null) { - return rej('app_secret is required'); - } + const [appSecret, appSecretErr] = it(params.app_secret).expect.string().required().qed(); + if (appSecretErr) return rej('invalid app_secret param'); // Lookup app const app = await App.findOne({ @@ -68,10 +67,8 @@ module.exports = (params) => } // Get 'token' parameter - const token = params.token; - if (token == null) { - return rej('token is required'); - } + const [token, tokenErr] = it(params.token).expect.string().required().qed(); + if (tokenErr) return rej('invalid token param'); // Fetch token const session = await AuthSess From f11bdf36b9c75a3e10850e46ef045cf9675ab7f7 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 19:48:00 +0900 Subject: [PATCH 42/43] wip --- .../endpoints/app/{create.js => create.ts} | 44 +++++++------------ .../name_id/{available.js => available.ts} | 13 ++---- src/api/endpoints/app/{show.js => show.ts} | 16 +++---- src/api/models/app.ts | 4 ++ src/api/serializers/app.ts | 4 +- 5 files changed, 31 insertions(+), 50 deletions(-) rename src/api/endpoints/app/{create.js => create.ts} (69%) rename src/api/endpoints/app/name_id/{available.js => available.ts} (82%) rename src/api/endpoints/app/{show.js => show.ts} (83%) diff --git a/src/api/endpoints/app/create.js b/src/api/endpoints/app/create.ts similarity index 69% rename from src/api/endpoints/app/create.js rename to src/api/endpoints/app/create.ts index 8b85da7ffa..adbb205f62 100644 --- a/src/api/endpoints/app/create.js +++ b/src/api/endpoints/app/create.ts @@ -4,7 +4,9 @@ * Module dependencies */ import rndstr from 'rndstr'; +import it from '../../it'; import App from '../../models/app'; +import { isValidNameId } from '../../models/app'; import serialize from '../../serializers/app'; /** @@ -71,41 +73,25 @@ module.exports = async (params, user) => new Promise(async (res, rej) => { // Get 'name_id' parameter - const nameId = params.name_id; - if (nameId == null) { - return rej('name_id is required'); - } else if (typeof nameId != 'string') { - return rej('name_id must be a string'); - } - - // Validate name_id - if (!/^[a-zA-Z0-9\-]{3,30}$/.test(nameId)) { - return rej('invalid name_id'); - } + const [nameId, nameIdErr] = it(params.name_id).expect.string().required().validate(isValidNameId).qed(); + if (nameIdErr) return rej('invalid name_id param'); // Get 'name' parameter - const name = params.name; - if (name == null || name == '') { - return rej('name is required'); - } + const [name, nameErr] = it(params.name).expect.string().required().qed(); + if (nameErr) return rej('invalid name param'); // Get 'description' parameter - const description = params.description; - if (description == null || description == '') { - return rej('description is required'); - } + const [description, descriptionErr] = it(params.description).expect.string().required().qed(); + if (descriptionErr) return rej('invalid description param'); // Get 'permission' parameter - const permission = params.permission; - if (permission == null || permission == '') { - return rej('permission is required'); - } + const [permission, permissionErr] = it(params.permission).expect.array().unique().allString().required().qed(); + if (permissionErr) return rej('invalid permission param'); // Get 'callback_url' parameter - let callback = params.callback_url; - if (callback === '') { - callback = null; - } + // TODO: Check it is valid url + const [callbackUrl, callbackUrlErr] = it(params.callback_url).expect.nullable.string().default(null).qed(); + if (callbackUrlErr) return rej('invalid callback_url param'); // Generate secret const secret = rndstr('a-zA-Z0-9', 32); @@ -118,8 +104,8 @@ module.exports = async (params, user) => name_id: nameId, name_id_lower: nameId.toLowerCase(), description: description, - permission: permission.split(','), - callback_url: callback, + permission: permission, + callback_url: callbackUrl, secret: secret }); diff --git a/src/api/endpoints/app/name_id/available.js b/src/api/endpoints/app/name_id/available.ts similarity index 82% rename from src/api/endpoints/app/name_id/available.js rename to src/api/endpoints/app/name_id/available.ts index 159d4fff4e..6af18ae83c 100644 --- a/src/api/endpoints/app/name_id/available.js +++ b/src/api/endpoints/app/name_id/available.ts @@ -3,7 +3,9 @@ /** * Module dependencies */ +import it from '../../../it'; import App from '../../../models/app'; +import { isValidNameId } from '../../../models/app'; /** * @swagger @@ -44,15 +46,8 @@ module.exports = async (params) => new Promise(async (res, rej) => { // Get 'name_id' parameter - const nameId = params.name_id; - if (nameId == null || nameId == '') { - return rej('name_id is required'); - } - - // Validate name_id - if (!/^[a-zA-Z0-9\-]{3,30}$/.test(nameId)) { - return rej('invalid name_id'); - } + const [nameId, nameIdErr] = it(params.name_id).expect.string().required().validate(isValidNameId).qed(); + if (nameIdErr) return rej('invalid name_id param'); // Get exist const exist = await App diff --git a/src/api/endpoints/app/show.js b/src/api/endpoints/app/show.ts similarity index 83% rename from src/api/endpoints/app/show.js rename to src/api/endpoints/app/show.ts index ab5f6f4562..cfb03bb9e5 100644 --- a/src/api/endpoints/app/show.js +++ b/src/api/endpoints/app/show.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../it'; import App from '../../models/app'; import serialize from '../../serializers/app'; @@ -50,16 +50,12 @@ module.exports = (params, user, _, isSecure) => new Promise(async (res, rej) => { // Get 'app_id' parameter - let appId = params.app_id; - if (appId == null || appId == '') { - appId = null; - } + const [appId, appIdErr] = it(params.app_id, 'id'); + if (appIdErr) return rej('invalid app_id param'); // Get 'name_id' parameter - let nameId = params.name_id; - if (nameId == null || nameId == '') { - nameId = null; - } + const [nameId, nameIdErr] = it(params.name_id, 'string'); + if (nameIdErr) return rej('invalid name_id param'); if (appId === null && nameId === null) { return rej('app_id or name_id is required'); @@ -67,7 +63,7 @@ module.exports = (params, user, _, isSecure) => // Lookup app const app = appId !== null - ? await App.findOne({ _id: new mongo.ObjectID(appId) }) + ? await App.findOne({ _id: appId }) : await App.findOne({ name_id_lower: nameId.toLowerCase() }); if (app === null) { diff --git a/src/api/models/app.ts b/src/api/models/app.ts index a947d88e4c..bf5dc80c2c 100644 --- a/src/api/models/app.ts +++ b/src/api/models/app.ts @@ -7,3 +7,7 @@ const collection = db.get('apps'); (collection as any).index('secret'); // fuck type definition export default collection as any; // fuck type definition + +export function isValidNameId(nameId: string): boolean { + return typeof nameId == 'string' && /^[a-zA-Z0-9\-]{3,30}$/.test(nameId); +} diff --git a/src/api/serializers/app.ts b/src/api/serializers/app.ts index 9a02c5637a..fdeef338d9 100644 --- a/src/api/serializers/app.ts +++ b/src/api/serializers/app.ts @@ -21,8 +21,8 @@ export default ( app: any, me?: any, options?: { - includeSecret: boolean, - includeProfileImageIds: boolean + includeSecret?: boolean, + includeProfileImageIds?: boolean } ) => new Promise(async (resolve, reject) => { const opts = options || { From 970843acd429e62c884c780601fae317a6a0fabb Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 19:52:36 +0900 Subject: [PATCH 43/43] done --- .../endpoints/aggregation/posts/{like.js => like.ts} | 10 ++++------ .../endpoints/aggregation/posts/{likes.js => likes.ts} | 10 ++++------ .../endpoints/aggregation/posts/{reply.js => reply.ts} | 10 ++++------ .../aggregation/posts/{repost.js => repost.ts} | 10 ++++------ .../aggregation/users/{followers.js => followers.ts} | 10 ++++------ .../aggregation/users/{following.js => following.ts} | 10 ++++------ .../endpoints/aggregation/users/{like.js => like.ts} | 10 ++++------ .../endpoints/aggregation/users/{post.js => post.ts} | 10 ++++------ 8 files changed, 32 insertions(+), 48 deletions(-) rename src/api/endpoints/aggregation/posts/{like.js => like.ts} (88%) rename src/api/endpoints/aggregation/posts/{likes.js => likes.ts} (87%) rename src/api/endpoints/aggregation/posts/{reply.js => reply.ts} (88%) rename src/api/endpoints/aggregation/posts/{repost.js => repost.ts} (88%) rename src/api/endpoints/aggregation/users/{followers.js => followers.ts} (88%) rename src/api/endpoints/aggregation/users/{following.js => following.ts} (88%) rename src/api/endpoints/aggregation/users/{like.js => like.ts} (88%) rename src/api/endpoints/aggregation/users/{post.js => post.ts} (92%) diff --git a/src/api/endpoints/aggregation/posts/like.js b/src/api/endpoints/aggregation/posts/like.ts similarity index 88% rename from src/api/endpoints/aggregation/posts/like.js rename to src/api/endpoints/aggregation/posts/like.ts index 02724aceb6..38ed7e6e16 100644 --- a/src/api/endpoints/aggregation/posts/like.js +++ b/src/api/endpoints/aggregation/posts/like.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import Post from '../../../models/post'; import Like from '../../../models/like'; @@ -17,14 +17,12 @@ module.exports = (params) => 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'); - } + const [postId, postIdErr] = it(params.post_id).expect.id().required().qed(); + if (postIdErr) return rej('invalid post_id param'); // Lookup post const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { diff --git a/src/api/endpoints/aggregation/posts/likes.js b/src/api/endpoints/aggregation/posts/likes.ts similarity index 87% rename from src/api/endpoints/aggregation/posts/likes.js rename to src/api/endpoints/aggregation/posts/likes.ts index 1049c70687..55fe077f64 100644 --- a/src/api/endpoints/aggregation/posts/likes.js +++ b/src/api/endpoints/aggregation/posts/likes.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import Post from '../../../models/post'; import Like from '../../../models/like'; @@ -17,14 +17,12 @@ module.exports = (params) => 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'); - } + const [postId, postIdErr] = it(params.post_id).expect.id().required().qed(); + if (postIdErr) return rej('invalid post_id param'); // Lookup post const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { diff --git a/src/api/endpoints/aggregation/posts/reply.js b/src/api/endpoints/aggregation/posts/reply.ts similarity index 88% rename from src/api/endpoints/aggregation/posts/reply.js rename to src/api/endpoints/aggregation/posts/reply.ts index 9d051c6593..1f936bbc2f 100644 --- a/src/api/endpoints/aggregation/posts/reply.js +++ b/src/api/endpoints/aggregation/posts/reply.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import Post from '../../../models/post'; /** @@ -16,14 +16,12 @@ module.exports = (params) => 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'); - } + const [postId, postIdErr] = it(params.post_id).expect.id().required().qed(); + if (postIdErr) return rej('invalid post_id param'); // Lookup post const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { diff --git a/src/api/endpoints/aggregation/posts/repost.js b/src/api/endpoints/aggregation/posts/repost.ts similarity index 88% rename from src/api/endpoints/aggregation/posts/repost.js rename to src/api/endpoints/aggregation/posts/repost.ts index 01899ecea6..e4a1bf7c7b 100644 --- a/src/api/endpoints/aggregation/posts/repost.js +++ b/src/api/endpoints/aggregation/posts/repost.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import Post from '../../../models/post'; /** @@ -16,14 +16,12 @@ module.exports = (params) => 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'); - } + const [postId, postIdErr] = it(params.post_id).expect.id().required().qed(); + if (postIdErr) return rej('invalid post_id param'); // Lookup post const post = await Post.findOne({ - _id: new mongo.ObjectID(postId) + _id: postId }); if (post === null) { diff --git a/src/api/endpoints/aggregation/users/followers.js b/src/api/endpoints/aggregation/users/followers.ts similarity index 88% rename from src/api/endpoints/aggregation/users/followers.js rename to src/api/endpoints/aggregation/users/followers.ts index 3b8d1d6041..9336a102f1 100644 --- a/src/api/endpoints/aggregation/users/followers.js +++ b/src/api/endpoints/aggregation/users/followers.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import User from '../../../models/user'; import Following from '../../../models/following'; @@ -17,14 +17,12 @@ module.exports = (params) => new Promise(async (res, rej) => { // Get 'user_id' parameter - const userId = params.user_id; - if (userId === undefined || userId === null) { - return rej('user_id is required'); - } + const [userId, userIdErr] = it(params.user_id).expect.id().required().qed(); + if (userIdErr) return rej('invalid user_id param'); // Lookup user const user = await User.findOne({ - _id: new mongo.ObjectID(userId) + _id: userId }, { fields: { _id: true diff --git a/src/api/endpoints/aggregation/users/following.js b/src/api/endpoints/aggregation/users/following.ts similarity index 88% rename from src/api/endpoints/aggregation/users/following.js rename to src/api/endpoints/aggregation/users/following.ts index 0b04ff9543..d468229158 100644 --- a/src/api/endpoints/aggregation/users/following.js +++ b/src/api/endpoints/aggregation/users/following.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import User from '../../../models/user'; import Following from '../../../models/following'; @@ -17,14 +17,12 @@ module.exports = (params) => new Promise(async (res, rej) => { // Get 'user_id' parameter - const userId = params.user_id; - if (userId === undefined || userId === null) { - return rej('user_id is required'); - } + const [userId, userIdErr] = it(params.user_id).expect.id().required().qed(); + if (userIdErr) return rej('invalid user_id param'); // Lookup user const user = await User.findOne({ - _id: new mongo.ObjectID(userId) + _id: userId }, { fields: { _id: true diff --git a/src/api/endpoints/aggregation/users/like.js b/src/api/endpoints/aggregation/users/like.ts similarity index 88% rename from src/api/endpoints/aggregation/users/like.js rename to src/api/endpoints/aggregation/users/like.ts index 0b20dd09a9..4a932354ad 100644 --- a/src/api/endpoints/aggregation/users/like.js +++ b/src/api/endpoints/aggregation/users/like.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import User from '../../../models/user'; import Like from '../../../models/like'; @@ -17,14 +17,12 @@ module.exports = (params) => new Promise(async (res, rej) => { // Get 'user_id' parameter - const userId = params.user_id; - if (userId === undefined || userId === null) { - return rej('user_id is required'); - } + const [userId, userIdErr] = it(params.user_id).expect.id().required().qed(); + if (userIdErr) return rej('invalid user_id param'); // Lookup user const user = await User.findOne({ - _id: new mongo.ObjectID(userId) + _id: userId }, { fields: { _id: true diff --git a/src/api/endpoints/aggregation/users/post.js b/src/api/endpoints/aggregation/users/post.ts similarity index 92% rename from src/api/endpoints/aggregation/users/post.js rename to src/api/endpoints/aggregation/users/post.ts index 01082801e4..b62dd6ec98 100644 --- a/src/api/endpoints/aggregation/users/post.js +++ b/src/api/endpoints/aggregation/users/post.ts @@ -3,7 +3,7 @@ /** * Module dependencies */ -import * as mongo from 'mongodb'; +import it from '../../../it'; import User from '../../../models/user'; import Post from '../../../models/post'; @@ -17,14 +17,12 @@ module.exports = (params) => new Promise(async (res, rej) => { // Get 'user_id' parameter - const userId = params.user_id; - if (userId === undefined || userId === null) { - return rej('user_id is required'); - } + const [userId, userIdErr] = it(params.user_id).expect.id().required().qed(); + if (userIdErr) return rej('invalid user_id param'); // Lookup user const user = await User.findOne({ - _id: new mongo.ObjectID(userId) + _id: userId }, { fields: { _id: true