Files
sign/packages/lib/server-only/user/update-public-profile.ts

88 lines
1.7 KiB
TypeScript
Raw Normal View History

import { prisma } from '@documenso/prisma';
2024-02-28 14:43:09 +11:00
import { AppError, AppErrorCode } from '../../errors/app-error';
export type UpdatePublicProfileOptions = {
2024-02-28 14:43:09 +11:00
userId: number;
2024-06-06 14:46:48 +10:00
data: {
url?: string;
bio?: string;
enabled?: boolean;
};
};
2024-06-06 14:46:48 +10:00
export const updatePublicProfile = async ({ userId, data }: UpdatePublicProfileOptions) => {
if (Object.values(data).length === 0) {
throw new AppError(AppErrorCode.INVALID_BODY, 'Missing data to update');
}
const { url, bio, enabled } = data;
const user = await prisma.user.findFirst({
where: {
2024-06-06 14:46:48 +10:00
id: userId,
},
});
2024-06-06 14:46:48 +10:00
if (!user) {
throw new AppError(AppErrorCode.NOT_FOUND, 'User not found');
}
const finalUrl = url ?? user.url;
if (!finalUrl && enabled) {
throw new AppError(AppErrorCode.INVALID_REQUEST, 'Cannot enable a profile without a URL');
}
if (url) {
const isUrlTakenByAnotherUser = await prisma.user.findFirst({
select: {
id: true,
},
where: {
id: {
not: userId,
},
url,
},
});
const isUrlTakenByAnotherTeam = await prisma.team.findFirst({
select: {
id: true,
},
where: {
url,
},
});
if (isUrlTakenByAnotherUser || isUrlTakenByAnotherTeam) {
2024-06-10 20:54:29 +10:00
throw new AppError(AppErrorCode.PROFILE_URL_TAKEN, 'The profile username is already taken');
2024-06-06 14:46:48 +10:00
}
2024-02-28 14:43:09 +11:00
}
return await prisma.user.update({
where: {
id: userId,
},
data: {
url,
2024-06-06 14:46:48 +10:00
profile: {
2024-02-28 14:43:09 +11:00
upsert: {
create: {
2024-06-06 14:46:48 +10:00
bio,
enabled,
2024-02-28 14:43:09 +11:00
},
update: {
2024-06-06 14:46:48 +10:00
bio,
enabled,
2024-02-28 14:43:09 +11:00
},
},
},
2024-02-28 14:43:09 +11:00
},
2024-06-06 14:46:48 +10:00
include: {
profile: true,
},
});
};