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

92 lines
1.8 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, { message: 'Missing data to update' });
2024-06-06 14:46:48 +10:00
}
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, { message: 'User not found' });
2024-06-06 14:46:48 +10:00
}
const finalUrl = url ?? user.url;
if (!finalUrl && enabled) {
throw new AppError(AppErrorCode.INVALID_REQUEST, {
message: 'Cannot enable a profile without a URL',
});
2024-06-06 14:46:48 +10:00
}
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) {
throw new AppError(AppErrorCode.PROFILE_URL_TAKEN, {
message: '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,
},
});
};