mizzkey/src/server/api/endpoints/users/groups/invite.ts

103 lines
2.4 KiB
TypeScript
Raw Normal View History

2019-05-18 13:36:33 +02:00
import $ from 'cafy';
import { ID } from '@/misc/cafy-id.js';
import define from '../../../define.js';
import { ApiError } from '../../../error.js';
import { getUser } from '../../../common/getters.js';
import { UserGroups, UserGroupJoinings, UserGroupInvitations } from '@/models/index.js';
import { genId } from '@/misc/gen-id.js';
import { UserGroupInvitation } from '@/models/entities/user-group-invitation.js';
import { createNotification } from '@/services/create-notification.js';
2019-05-18 13:36:33 +02:00
export const meta = {
tags: ['groups', 'users'],
2020-02-15 13:33:32 +01:00
requireCredential: true as const,
2019-05-18 13:36:33 +02:00
kind: 'write:user-groups',
params: {
groupId: {
validator: $.type(ID),
},
userId: {
validator: $.type(ID),
},
},
errors: {
noSuchGroup: {
message: 'No such group.',
code: 'NO_SUCH_GROUP',
id: '583f8bc0-8eee-4b78-9299-1e14fc91e409'
},
noSuchUser: {
message: 'No such user.',
code: 'NO_SUCH_USER',
id: 'da52de61-002c-475b-90e1-ba64f9cf13a8'
},
alreadyAdded: {
message: 'That user has already been added to that group.',
code: 'ALREADY_ADDED',
id: '7e35c6a0-39b2-4488-aea6-6ee20bd5da2c'
2019-05-19 13:41:23 +02:00
},
alreadyInvited: {
message: 'That user has already been invited to that group.',
code: 'ALREADY_INVITED',
id: 'ee0f58b4-b529-4d13-b761-b9a3e69f97e6'
2019-05-18 13:36:33 +02:00
}
}
};
export default define(meta, async (ps, me) => {
// Fetch the group
const userGroup = await UserGroups.findOne({
id: ps.groupId,
userId: me.id,
});
if (userGroup == null) {
throw new ApiError(meta.errors.noSuchGroup);
}
// Fetch the user
const user = await getUser(ps.userId).catch(e => {
if (e.id === '15348ddd-432d-49c2-8a5a-8069753becff') throw new ApiError(meta.errors.noSuchUser);
throw e;
});
2019-05-19 13:41:23 +02:00
const joining = await UserGroupJoinings.findOne({
2019-05-18 13:36:33 +02:00
userGroupId: userGroup.id,
userId: user.id
});
2019-05-19 13:41:23 +02:00
if (joining) {
2019-05-18 13:36:33 +02:00
throw new ApiError(meta.errors.alreadyAdded);
}
const existInvitation = await UserGroupInvitations.findOne({
2019-05-19 13:41:23 +02:00
userGroupId: userGroup.id,
userId: user.id
});
if (existInvitation) {
2019-05-19 13:41:23 +02:00
throw new ApiError(meta.errors.alreadyInvited);
}
const invitation = await UserGroupInvitations.insert({
2019-05-18 13:36:33 +02:00
id: genId(),
createdAt: new Date(),
userId: user.id,
userGroupId: userGroup.id
} as UserGroupInvitation).then(x => UserGroupInvitations.findOneOrFail(x.identifiers[0]));
// 通知を作成
2020-03-28 10:07:41 +01:00
createNotification(user.id, 'groupInvited', {
notifierId: me.id,
userGroupInvitationId: invitation.id
});
2019-05-18 13:36:33 +02:00
});