Sharkey/src/server/api/endpoints/messaging/messages.ts
syuilo 2756f553c6
Improve error handling of API (#4345)
* wip

* wip

* wip

* Update attached_notes.ts

* wip

* Refactor

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* Update call.ts

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* ✌️

* Fix
2019-02-22 11:46:58 +09:00

114 lines
2 KiB
TypeScript

import $ from 'cafy';
import ID, { transform } from '../../../../misc/cafy-id';
import Message from '../../../../models/messaging-message';
import User from '../../../../models/user';
import { pack } from '../../../../models/messaging-message';
import read from '../../common/read-messaging-message';
import define from '../../define';
import { ApiError } from '../../error';
export const meta = {
desc: {
'ja-JP': '指定したユーザーとのMessagingのメッセージ一覧を取得します。',
'en-US': 'Get messages of messaging.'
},
requireCredential: true,
kind: 'messaging-read',
params: {
userId: {
validator: $.type(ID),
transform: transform,
desc: {
'ja-JP': '対象のユーザーのID',
'en-US': 'Target user ID'
}
},
limit: {
validator: $.optional.num.range(1, 100),
default: 10
},
sinceId: {
validator: $.optional.type(ID),
transform: transform,
},
untilId: {
validator: $.optional.type(ID),
transform: transform,
},
markAsRead: {
validator: $.optional.bool,
default: true
}
},
errors: {
noSuchUser: {
message: 'No such user.',
code: 'NO_SUCH_USER',
id: '11795c64-40ea-4198-b06e-3c873ed9039d'
},
}
};
export default define(meta, async (ps, user) => {
// Fetch recipient
const recipient = await User.findOne({
_id: ps.userId
}, {
fields: {
_id: true
}
});
if (recipient === null) {
throw new ApiError(meta.errors.noSuchUser);
}
const query = {
$or: [{
userId: user._id,
recipientId: recipient._id
}, {
userId: recipient._id,
recipientId: user._id
}]
} as any;
const sort = {
_id: -1
};
if (ps.sinceId) {
sort._id = 1;
query._id = {
$gt: ps.sinceId
};
} else if (ps.untilId) {
query._id = {
$lt: ps.untilId
};
}
const messages = await Message
.find(query, {
limit: ps.limit,
sort: sort
});
// Mark all as read
if (ps.markAsRead) {
read(user._id, recipient._id, messages);
}
return await Promise.all(messages.map(message => pack(message, user, {
populateRecipient: false
})));
});