mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-07-17 01:47:22 +00:00
Move next js project to archive (#207)
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
|
||||
import {
|
||||
CreateBeerPostComment,
|
||||
EditBeerPostCommentById,
|
||||
FindOrDeleteBeerPostCommentById,
|
||||
GetAllBeerPostComments,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The select object for retrieving beer post comments.
|
||||
*
|
||||
* @example
|
||||
* const beerPostComments = await DBClient.instance.beerComment.findMany({
|
||||
* select: beerPostCommentSelect,
|
||||
* });
|
||||
*/
|
||||
const beerPostCommentSelect = {
|
||||
id: true,
|
||||
content: true,
|
||||
rating: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
postedBy: {
|
||||
select: { id: true, username: true, createdAt: true, userAvatar: true },
|
||||
},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Creates a new comment for a beer post.
|
||||
*
|
||||
* @param params - The options for creating the comment.
|
||||
* @param params.body - The body of the comment.
|
||||
* @param params.body.content - The content of the comment.
|
||||
* @param params.body.rating - The rating of the beer.
|
||||
* @param params.beerPostId - The ID of the beer post.
|
||||
* @param params.userId - The ID of the user creating the comment.
|
||||
* @returns A promise that resolves to the created beer comment.
|
||||
*/
|
||||
export const createBeerPostCommentService: CreateBeerPostComment = ({
|
||||
body,
|
||||
beerPostId,
|
||||
userId,
|
||||
}) => {
|
||||
const { content, rating } = body;
|
||||
return DBClient.instance.beerComment.create({
|
||||
data: {
|
||||
content,
|
||||
rating,
|
||||
beerPost: { connect: { id: beerPostId } },
|
||||
postedBy: { connect: { id: userId } },
|
||||
},
|
||||
select: beerPostCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Edits a comment for a beer post.
|
||||
*
|
||||
* @param params - The options for editing the comment.
|
||||
* @param params.body - The body of the comment.
|
||||
* @param params.body.content - The content of the comment.
|
||||
* @param params.body.rating - The rating of the beer.
|
||||
* @param params.beerPostCommentId - The ID of the beer post comment.
|
||||
* @returns A promise that resolves to the updated beer comment.
|
||||
*/
|
||||
export const editBeerPostCommentByIdService: EditBeerPostCommentById = ({
|
||||
beerPostCommentId,
|
||||
body,
|
||||
}) => {
|
||||
const { content, rating } = body;
|
||||
return DBClient.instance.beerComment.update({
|
||||
where: { id: beerPostCommentId },
|
||||
data: { content, rating, updatedAt: new Date() },
|
||||
select: beerPostCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds a comment for a beer post by ID.
|
||||
*
|
||||
* @param params - The options for finding the comment.
|
||||
* @param params.beerPostCommentId - The ID of the beer post comment.
|
||||
* @returns A promise that resolves to the found beer comment.
|
||||
*/
|
||||
export const getBeerPostCommentByIdService: FindOrDeleteBeerPostCommentById = ({
|
||||
beerPostCommentId,
|
||||
}) => {
|
||||
return DBClient.instance.beerComment.findUnique({
|
||||
where: { id: beerPostCommentId },
|
||||
select: beerPostCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a comment for a beer post by ID.
|
||||
*
|
||||
* @param params - The options for deleting the comment.
|
||||
* @param params.beerPostCommentId - The ID of the beer post comment.
|
||||
* @returns A promise that resolves to the deleted beer comment.
|
||||
*/
|
||||
export const deleteBeerCommentByIdService: FindOrDeleteBeerPostCommentById = ({
|
||||
beerPostCommentId,
|
||||
}) => {
|
||||
return DBClient.instance.beerComment.delete({
|
||||
where: { id: beerPostCommentId },
|
||||
select: beerPostCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets all comments for a beer post.
|
||||
*
|
||||
* @param params - The options for getting the comments.
|
||||
* @param params.beerPostId - The ID of the beer post.
|
||||
* @param params.pageNum - The page number of the comments.
|
||||
* @param params.pageSize - The number of comments per page.
|
||||
* @returns A promise that resolves to the found beer comments.
|
||||
*/
|
||||
export const getAllBeerCommentsService: GetAllBeerPostComments = async ({
|
||||
beerPostId,
|
||||
pageNum,
|
||||
pageSize,
|
||||
}) => {
|
||||
const comments = await DBClient.instance.beerComment.findMany({
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
take: pageSize,
|
||||
where: { beerPostId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: beerPostCommentSelect,
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.beerComment.count({ where: { beerPostId } });
|
||||
|
||||
return { comments, count };
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
import CommentQueryResult from '@/services/schema/CommentSchema/CommentQueryResult';
|
||||
import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
type BeerPostComment = z.infer<typeof CommentQueryResult>;
|
||||
|
||||
export type CreateBeerPostComment = (args: {
|
||||
body: z.infer<typeof CreateCommentValidationSchema>;
|
||||
userId: string;
|
||||
beerPostId: string;
|
||||
}) => Promise<BeerPostComment>;
|
||||
|
||||
export type EditBeerPostCommentById = (args: {
|
||||
body: z.infer<typeof CreateCommentValidationSchema>;
|
||||
beerPostCommentId: string;
|
||||
}) => Promise<BeerPostComment>;
|
||||
|
||||
export type FindOrDeleteBeerPostCommentById = (args: {
|
||||
beerPostCommentId: string;
|
||||
}) => Promise<BeerPostComment | null>;
|
||||
|
||||
export type GetAllBeerPostComments = (args: {
|
||||
beerPostId: string;
|
||||
pageNum: number;
|
||||
pageSize: number;
|
||||
}) => Promise<{
|
||||
comments: BeerPostComment[];
|
||||
count: number;
|
||||
}>;
|
||||
@@ -0,0 +1,138 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import {
|
||||
CreateNewBeerStyleComment,
|
||||
GetAllBeerStyleComments,
|
||||
UpdateBeerStyleCommentById,
|
||||
FindOrDeleteBeerStyleCommentById,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The select object for retrieving beer style comments.
|
||||
*
|
||||
* @example
|
||||
* const beerStyleComments = await DBClient.instance.beerStyleComment.findMany({
|
||||
* select: beerStyleCommentSelect,
|
||||
* });
|
||||
*/
|
||||
const beerStyleCommentSelect = {
|
||||
id: true,
|
||||
content: true,
|
||||
rating: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
postedBy: {
|
||||
select: { id: true, username: true, createdAt: true, userAvatar: true },
|
||||
},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Creates a new comment for a beer style.
|
||||
*
|
||||
* @param params - The options for creating the comment.
|
||||
* @param params.body - The body of the comment.
|
||||
* @param params.body.content - The content of the comment.
|
||||
* @param params.body.rating - The rating of the beer style.
|
||||
* @param params.beerStyleId - The ID of the beer style.
|
||||
* @param params.userId - The ID of the user creating the comment.
|
||||
* @returns A promise that resolves to the created beer comment.
|
||||
*/
|
||||
export const createNewBeerStyleComment: CreateNewBeerStyleComment = ({
|
||||
body,
|
||||
userId,
|
||||
beerStyleId,
|
||||
}) => {
|
||||
const { content, rating } = body;
|
||||
return DBClient.instance.beerStyleComment.create({
|
||||
data: {
|
||||
content,
|
||||
rating,
|
||||
beerStyle: { connect: { id: beerStyleId } },
|
||||
postedBy: { connect: { id: userId } },
|
||||
},
|
||||
select: beerStyleCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets all comments for a beer style.
|
||||
*
|
||||
* @param params - The options for getting the comments.
|
||||
* @param params.beerStyleId - The ID of the beer style.
|
||||
* @param params.pageNum - The page number of the comments.
|
||||
* @param params.pageSize - The page size of the comments.
|
||||
* @returns A promise that resolves to the beer style comments.
|
||||
*/
|
||||
export const getAllBeerStyleComments: GetAllBeerStyleComments = async ({
|
||||
beerStyleId,
|
||||
pageNum,
|
||||
pageSize,
|
||||
}) => {
|
||||
const comments = await DBClient.instance.beerStyleComment.findMany({
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
take: pageSize,
|
||||
where: { beerStyleId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: beerStyleCommentSelect,
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.beerStyleComment.count({
|
||||
where: { beerStyleId },
|
||||
});
|
||||
|
||||
return { comments, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates a beer style comment by ID.
|
||||
*
|
||||
* @param params - The options for updating the comment.
|
||||
* @param params.body - The body of the comment.
|
||||
* @param params.body.content - The content of the comment.
|
||||
* @param params.body.rating - The rating of the beer style.
|
||||
* @param params.beerStyleCommentId - The ID of the beer style comment.
|
||||
* @returns A promise that resolves to the updated beer comment.
|
||||
*/
|
||||
export const updateBeerStyleCommentById: UpdateBeerStyleCommentById = ({
|
||||
body,
|
||||
beerStyleCommentId,
|
||||
}) => {
|
||||
const { content, rating } = body;
|
||||
|
||||
return DBClient.instance.beerStyleComment.update({
|
||||
where: { id: beerStyleCommentId },
|
||||
data: { content, rating, updatedAt: new Date() },
|
||||
select: beerStyleCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds a comment for a beer style by ID.
|
||||
*
|
||||
* @param params - The options for finding the comment.
|
||||
* @param params.beerStyleCommentId - The ID of the beer style comment.
|
||||
* @returns A promise that resolves to the found beer comment.
|
||||
*/
|
||||
export const findBeerStyleCommentById: FindOrDeleteBeerStyleCommentById = ({
|
||||
beerStyleCommentId,
|
||||
}) => {
|
||||
return DBClient.instance.beerStyleComment.findUnique({
|
||||
where: { id: beerStyleCommentId },
|
||||
select: beerStyleCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a comment for a beer style by ID.
|
||||
*
|
||||
* @param params - The options for deleting the comment.
|
||||
* @param params.beerStyleCommentId - The ID of the beer style comment.
|
||||
* @returns A promise that resolves to the deleted beer comment.
|
||||
*/
|
||||
export const deleteBeerStyleCommentById: FindOrDeleteBeerStyleCommentById = ({
|
||||
beerStyleCommentId,
|
||||
}) => {
|
||||
return DBClient.instance.beerStyleComment.delete({
|
||||
where: { id: beerStyleCommentId },
|
||||
select: beerStyleCommentSelect,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
import CommentQueryResult from '@/services/schema/CommentSchema/CommentQueryResult';
|
||||
import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
type BeerStyleComment = z.infer<typeof CommentQueryResult>;
|
||||
|
||||
export type FindOrDeleteBeerStyleCommentById = (args: {
|
||||
beerStyleCommentId: string;
|
||||
}) => Promise<BeerStyleComment | null>;
|
||||
|
||||
export type UpdateBeerStyleCommentById = (args: {
|
||||
body: z.infer<typeof CreateCommentValidationSchema>;
|
||||
beerStyleCommentId: string;
|
||||
}) => Promise<BeerStyleComment>;
|
||||
|
||||
export type GetAllBeerStyleComments = (args: {
|
||||
beerStyleId: string;
|
||||
pageNum: number;
|
||||
pageSize: number;
|
||||
}) => Promise<{
|
||||
comments: BeerStyleComment[];
|
||||
count: number;
|
||||
}>;
|
||||
|
||||
export type CreateNewBeerStyleComment = (args: {
|
||||
body: z.infer<typeof CreateCommentValidationSchema>;
|
||||
userId: string;
|
||||
beerStyleId: string;
|
||||
}) => Promise<BeerStyleComment>;
|
||||
@@ -0,0 +1,138 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import {
|
||||
CreateNewBreweryComment,
|
||||
FindDeleteBreweryCommentById,
|
||||
GetAllBreweryComments,
|
||||
UpdateBreweryCommentById,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The select object for retrieving brewery comments.
|
||||
*
|
||||
* @example
|
||||
* const breweryComments = await DBClient.instance.breweryComment.findMany({
|
||||
* select: breweryCommentSelect,
|
||||
* });
|
||||
*/
|
||||
const breweryCommentSelect = {
|
||||
id: true,
|
||||
content: true,
|
||||
rating: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
postedBy: {
|
||||
select: { id: true, username: true, createdAt: true, userAvatar: true },
|
||||
},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Updates a brewery comment by ID.
|
||||
*
|
||||
* @param params - The options for updating the brewery comment.
|
||||
* @param params.breweryCommentId - The ID of the brewery comment.
|
||||
* @param params.body - The body of the comment.
|
||||
* @param params.body.content - The content of the comment.
|
||||
* @param params.body.rating - The rating of the brewery.
|
||||
* @returns A promise that resolves to the updated brewery comment.
|
||||
*/
|
||||
export const updateBreweryCommentById: UpdateBreweryCommentById = ({
|
||||
breweryCommentId,
|
||||
body,
|
||||
}) => {
|
||||
const { content, rating } = body;
|
||||
|
||||
return DBClient.instance.breweryComment.update({
|
||||
where: { id: breweryCommentId },
|
||||
data: { content, rating },
|
||||
select: breweryCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new comment for a brewery.
|
||||
*
|
||||
* @param params - The options for creating the comment.
|
||||
* @param params.body - The body of the comment.
|
||||
* @param params.body.content - The content of the comment.
|
||||
* @param params.body.rating - The rating of the brewery.
|
||||
* @param params.breweryPostId - The ID of the brewery post.
|
||||
* @param params.userId - The ID of the user creating the comment.
|
||||
* @returns A promise that resolves to the created brewery comment.
|
||||
*/
|
||||
export const createNewBreweryComment: CreateNewBreweryComment = ({
|
||||
body,
|
||||
breweryPostId,
|
||||
userId,
|
||||
}) => {
|
||||
const { content, rating } = body;
|
||||
return DBClient.instance.breweryComment.create({
|
||||
data: {
|
||||
content,
|
||||
rating,
|
||||
breweryPost: { connect: { id: breweryPostId } },
|
||||
postedBy: { connect: { id: userId } },
|
||||
},
|
||||
select: breweryCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets all comments for a brewery.
|
||||
*
|
||||
* @param params - The options for getting the comments.
|
||||
* @param params.breweryPostId - The ID of the brewery post.
|
||||
* @param params.pageNum - The page number of the comments.
|
||||
* @param params.pageSize - The number of comments per page.
|
||||
* @returns A promise that resolves to the retrieved brewery comments.
|
||||
*/
|
||||
export const getAllBreweryComments: GetAllBreweryComments = async ({
|
||||
id,
|
||||
pageNum,
|
||||
pageSize,
|
||||
}) => {
|
||||
const comments = await DBClient.instance.breweryComment.findMany({
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
take: pageSize,
|
||||
where: { breweryPostId: id },
|
||||
select: breweryCommentSelect,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.breweryComment.count({
|
||||
where: { breweryPostId: id },
|
||||
});
|
||||
|
||||
return { comments, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds a comment for a brewery post by ID.
|
||||
*
|
||||
* @param params - The options for finding the comment.
|
||||
* @param params.breweryCommentId - The ID of the brewery post comment.
|
||||
* @returns A promise that resolves to the found brewery comment.
|
||||
*/
|
||||
export const getBreweryCommentById: FindDeleteBreweryCommentById = ({
|
||||
breweryCommentId,
|
||||
}) => {
|
||||
return DBClient.instance.breweryComment.findUnique({
|
||||
where: { id: breweryCommentId },
|
||||
select: breweryCommentSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a comment for a brewery post by ID.
|
||||
*
|
||||
* @param params - The options for deleting the comment.
|
||||
* @param params.breweryCommentId - The ID of the brewery post comment.
|
||||
* @returns A promise that resolves to the deleted brewery comment.
|
||||
*/
|
||||
export const deleteBreweryCommentByIdService: FindDeleteBreweryCommentById = ({
|
||||
breweryCommentId,
|
||||
}) => {
|
||||
return DBClient.instance.breweryComment.delete({
|
||||
where: { id: breweryCommentId },
|
||||
select: breweryCommentSelect,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import CommentQueryResult from '@/services/schema/CommentSchema/CommentQueryResult';
|
||||
import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
type BreweryComment = z.infer<typeof CommentQueryResult>;
|
||||
|
||||
export type UpdateBreweryCommentById = (args: {
|
||||
breweryCommentId: string;
|
||||
body: z.infer<typeof CreateCommentValidationSchema>;
|
||||
}) => Promise<BreweryComment>;
|
||||
|
||||
export type CreateNewBreweryComment = (args: {
|
||||
body: z.infer<typeof CreateCommentValidationSchema>;
|
||||
breweryPostId: string;
|
||||
userId: string;
|
||||
}) => Promise<BreweryComment>;
|
||||
|
||||
export type GetAllBreweryComments = (args: {
|
||||
id: string;
|
||||
pageNum: number;
|
||||
pageSize: number;
|
||||
}) => Promise<{ comments: BreweryComment[]; count: number }>;
|
||||
|
||||
export type FindDeleteBreweryCommentById = (args: {
|
||||
breweryCommentId: string;
|
||||
}) => Promise<BreweryComment | null>;
|
||||
@@ -0,0 +1,87 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import { BeerImage } from '@prisma/client';
|
||||
import { cloudinary } from '@/config/cloudinary';
|
||||
import {
|
||||
AddBeerImagesToDB,
|
||||
DeleteBeerImageFromDBAndStorage,
|
||||
UpdateBeerImageMetadata,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Adds beer images to the database.
|
||||
*
|
||||
* @param options - The options for adding beer images.
|
||||
* @param options.body - The body of the request.
|
||||
* @param options.body.alt - The alt text for the beer image.
|
||||
* @param options.body.caption - The caption for the beer image.
|
||||
* @param options.files - The array of files to be uploaded as beer images.
|
||||
* @param options.beerPostId - The ID of the beer post.
|
||||
* @param options.userId - The ID of the user.
|
||||
* @returns A promise that resolves to an array of created beer images.
|
||||
*/
|
||||
export const addBeerImagesService: AddBeerImagesToDB = ({
|
||||
body,
|
||||
files,
|
||||
beerPostId,
|
||||
userId,
|
||||
}) => {
|
||||
const beerImagePromises: Promise<BeerImage>[] = [];
|
||||
|
||||
const { alt, caption } = body;
|
||||
files.forEach((file) => {
|
||||
beerImagePromises.push(
|
||||
DBClient.instance.beerImage.create({
|
||||
data: {
|
||||
alt,
|
||||
caption,
|
||||
postedBy: { connect: { id: userId } },
|
||||
beerPost: { connect: { id: beerPostId } },
|
||||
path: file.path,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return Promise.all(beerImagePromises);
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a beer image from the database and storage.
|
||||
*
|
||||
* @param options - The options for deleting a beer image.
|
||||
* @param options.beerImageId - The ID of the beer image.
|
||||
*/
|
||||
export const deleteBeerImageService: DeleteBeerImageFromDBAndStorage = async ({
|
||||
beerImageId,
|
||||
}) => {
|
||||
const deleted = await DBClient.instance.beerImage.delete({
|
||||
where: { id: beerImageId },
|
||||
select: { path: true, id: true },
|
||||
});
|
||||
const { path } = deleted;
|
||||
await cloudinary.uploader.destroy(path);
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the beer image metadata in the database.
|
||||
*
|
||||
* @param options - The options for updating the beer image metadata.
|
||||
* @param options.beerImageId - The ID of the beer image.
|
||||
* @param options.body - The body of the request containing the alt and caption.
|
||||
* @param options.body.alt - The alt text for the beer image.
|
||||
* @param options.body.caption - The caption for the beer image.
|
||||
* @returns A promise that resolves to the updated beer image.
|
||||
*/
|
||||
|
||||
export const updateBeerImageService: UpdateBeerImageMetadata = async ({
|
||||
beerImageId,
|
||||
body,
|
||||
}) => {
|
||||
const { alt, caption } = body;
|
||||
const updated = await DBClient.instance.beerImage.update({
|
||||
where: { id: beerImageId },
|
||||
data: { alt, caption },
|
||||
});
|
||||
|
||||
return updated;
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import ImageMetadataValidationSchema from '@/services/schema/ImageSchema/ImageMetadataValidationSchema';
|
||||
import { BeerImage } from '@prisma/client';
|
||||
import { z } from 'zod';
|
||||
|
||||
export type AddBeerImagesToDB = (args: {
|
||||
files: Express.Multer.File[];
|
||||
body: z.infer<typeof ImageMetadataValidationSchema>;
|
||||
beerPostId: string;
|
||||
userId: string;
|
||||
}) => Promise<BeerImage[]>;
|
||||
|
||||
export type DeleteBeerImageFromDBAndStorage = (args: {
|
||||
beerImageId: string;
|
||||
}) => Promise<void>;
|
||||
|
||||
export type UpdateBeerImageMetadata = (args: {
|
||||
beerImageId: string;
|
||||
body: z.infer<typeof ImageMetadataValidationSchema>;
|
||||
}) => Promise<BeerImage>;
|
||||
@@ -0,0 +1,87 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import { BreweryImage } from '@prisma/client';
|
||||
import { cloudinary } from '@/config/cloudinary';
|
||||
import {
|
||||
AddBreweryImagesToDB,
|
||||
DeleteBreweryImageFromDBAndStorage,
|
||||
UpdateBreweryImageMetadata,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Adds brewery images to the database.
|
||||
*
|
||||
* @param options - The options for adding brewery images.
|
||||
* @param options.body - The body of the request containing the alt and caption.
|
||||
* @param options.body.alt - The alt text for the brewery image.
|
||||
* @param options.body.caption - The caption for the brewery image.
|
||||
* @param options.files - The array of files to be uploaded as brewery images.
|
||||
* @param options.breweryPostId - The ID of the brewery post.
|
||||
* @param options.userId - The ID of the user adding the images.
|
||||
* @returns A promise that resolves to an array of created brewery images.
|
||||
*/
|
||||
|
||||
export const addBreweryImagesService: AddBreweryImagesToDB = ({
|
||||
body,
|
||||
files,
|
||||
breweryPostId,
|
||||
userId,
|
||||
}) => {
|
||||
const breweryImagePromises: Promise<BreweryImage>[] = [];
|
||||
|
||||
const { alt, caption } = body;
|
||||
files.forEach((file) => {
|
||||
breweryImagePromises.push(
|
||||
DBClient.instance.breweryImage.create({
|
||||
data: {
|
||||
alt,
|
||||
caption,
|
||||
postedBy: { connect: { id: userId } },
|
||||
breweryPost: { connect: { id: breweryPostId } },
|
||||
path: file.path,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return Promise.all(breweryImagePromises);
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a brewery image from the database and storage.
|
||||
*
|
||||
* @param options - The options for deleting a brewery image.
|
||||
* @param options.breweryImageId - The ID of the brewery image.
|
||||
*/
|
||||
export const deleteBreweryImageService: DeleteBreweryImageFromDBAndStorage = async ({
|
||||
breweryImageId,
|
||||
}) => {
|
||||
const deleted = await DBClient.instance.breweryImage.delete({
|
||||
where: { id: breweryImageId },
|
||||
select: { path: true, id: true },
|
||||
});
|
||||
const { path } = deleted;
|
||||
await cloudinary.uploader.destroy(path);
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the brewery image metadata in the database.
|
||||
*
|
||||
* @param options - The options for updating the brewery image metadata.
|
||||
* @param options.breweryImageId - The ID of the brewery image.
|
||||
* @param options.body - The body of the request containing the alt and caption.
|
||||
* @param options.body.alt - The alt text for the brewery image.
|
||||
* @param options.body.caption - The caption for the brewery image.
|
||||
* @returns A promise that resolves to the updated brewery image.
|
||||
*/
|
||||
export const updateBreweryImageService: UpdateBreweryImageMetadata = async ({
|
||||
breweryImageId,
|
||||
body,
|
||||
}) => {
|
||||
const { alt, caption } = body;
|
||||
const updated = await DBClient.instance.breweryImage.update({
|
||||
where: { id: breweryImageId },
|
||||
data: { alt, caption },
|
||||
});
|
||||
|
||||
return updated;
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import ImageMetadataValidationSchema from '@/services/schema/ImageSchema/ImageMetadataValidationSchema';
|
||||
import { BreweryImage } from '@prisma/client';
|
||||
import { z } from 'zod';
|
||||
|
||||
export type AddBreweryImagesToDB = (args: {
|
||||
files: Express.Multer.File[];
|
||||
body: z.infer<typeof ImageMetadataValidationSchema>;
|
||||
breweryPostId: string;
|
||||
userId: string;
|
||||
}) => Promise<BreweryImage[]>;
|
||||
|
||||
export type DeleteBreweryImageFromDBAndStorage = (args: {
|
||||
breweryImageId: string;
|
||||
}) => Promise<void>;
|
||||
|
||||
export type UpdateBreweryImageMetadata = (args: {
|
||||
breweryImageId: string;
|
||||
body: z.infer<typeof ImageMetadataValidationSchema>;
|
||||
}) => Promise<BreweryImage>;
|
||||
@@ -0,0 +1,60 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import {
|
||||
CreateBeerPostLike,
|
||||
FindBeerPostLikeById,
|
||||
GetBeerPostLikeCount,
|
||||
RemoveBeerPostLike,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Creates a new beer post like.
|
||||
*
|
||||
* @param params - The parameters object for creating the beer post like.
|
||||
* @param params.beerPostId - The ID of the beer post.
|
||||
* @param params.likedById - The ID of the user who will like the beer post.
|
||||
* @returns A promise that resolves to the newly created beer post like.
|
||||
*/
|
||||
export const createBeerPostLikeService: CreateBeerPostLike = async ({
|
||||
beerPostId,
|
||||
likedById,
|
||||
}) =>
|
||||
DBClient.instance.beerPostLike.create({
|
||||
data: {
|
||||
beerPost: { connect: { id: beerPostId } },
|
||||
likedBy: { connect: { id: likedById } },
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Retrieves a beer post like by ID.
|
||||
*
|
||||
* @param params - The parameters object for retrieving the beer post like.
|
||||
* @param params.beerPostId - The ID of the beer post.
|
||||
* @param params.likedById - The ID of the user who liked the beer post.
|
||||
* @returns A promise that resolves to the beer post like.
|
||||
*/
|
||||
export const findBeerPostLikeByIdService: FindBeerPostLikeById = async ({
|
||||
beerPostId,
|
||||
likedById,
|
||||
}) => DBClient.instance.beerPostLike.findFirst({ where: { beerPostId, likedById } });
|
||||
|
||||
/**
|
||||
* Removes a beer post like.
|
||||
*
|
||||
* @param params - The parameters object for removing the beer post like.
|
||||
* @param params.beerPostLikeId - The ID of the beer post like to remove.
|
||||
* @returns A promise that resolves to the removed beer post like.
|
||||
*/
|
||||
export const removeBeerPostLikeService: RemoveBeerPostLike = async ({ beerPostLikeId }) =>
|
||||
DBClient.instance.beerPostLike.delete({ where: { id: beerPostLikeId } });
|
||||
|
||||
/**
|
||||
* Retrieves the number of likes for a beer post.
|
||||
*
|
||||
* @param params - The parameters object for retrieving the number of likes for a beer
|
||||
* post.
|
||||
* @param params.beerPostId - The ID of the beer post.
|
||||
* @returns A promise that resolves to the number of likes for a beer post.
|
||||
*/
|
||||
export const getBeerPostLikeCountService: GetBeerPostLikeCount = async ({ beerPostId }) =>
|
||||
DBClient.instance.beerPostLike.count({ where: { beerPostId } });
|
||||
@@ -0,0 +1,11 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const BeerPostLikeSchema = z.object({
|
||||
id: z.string().cuid(),
|
||||
beerPostId: z.string().cuid(),
|
||||
likedById: z.string().cuid(),
|
||||
createdAt: z.coerce.date(),
|
||||
updatedAt: z.coerce.date().nullable(),
|
||||
});
|
||||
|
||||
export default BeerPostLikeSchema;
|
||||
@@ -0,0 +1,23 @@
|
||||
import GetUserSchema from '@/services/users/auth/schema/GetUserSchema';
|
||||
|
||||
import { z } from 'zod';
|
||||
import BeerPostLikeSchema from '../schema/BeerPostLikeSchema';
|
||||
|
||||
type User = z.infer<typeof GetUserSchema>;
|
||||
type ReturnSchema = z.infer<typeof BeerPostLikeSchema>;
|
||||
|
||||
export type CreateBeerPostLike = (args: {
|
||||
beerPostId: string;
|
||||
likedById: User['id'];
|
||||
}) => Promise<ReturnSchema>;
|
||||
|
||||
export type FindBeerPostLikeById = (args: {
|
||||
beerPostId: string;
|
||||
likedById: User['id'];
|
||||
}) => Promise<ReturnSchema | null>;
|
||||
|
||||
export type RemoveBeerPostLike = (args: {
|
||||
beerPostLikeId: string;
|
||||
}) => Promise<ReturnSchema>;
|
||||
|
||||
export type GetBeerPostLikeCount = (args: { beerPostId: string }) => Promise<number>;
|
||||
@@ -0,0 +1,63 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
|
||||
import {
|
||||
CreateBeerStyleLike,
|
||||
FindBeerStyleLike,
|
||||
GetBeerStyleLikeCount,
|
||||
RemoveBeerStyleLike,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Creates a new beer style like.
|
||||
*
|
||||
* @param params - The parameters object for creating the beer style like.
|
||||
* @param params.beerStyleId - The ID of the beer style.
|
||||
* @param params.likedById - The ID of the user who will like the beer style.
|
||||
* @returns A promise that resolves to the newly created beer style like.
|
||||
*/
|
||||
export const createBeerStyleLikeService: CreateBeerStyleLike = async ({
|
||||
beerStyleId,
|
||||
likedById,
|
||||
}) =>
|
||||
DBClient.instance.beerStyleLike.create({
|
||||
data: {
|
||||
beerStyle: { connect: { id: beerStyleId } },
|
||||
likedBy: { connect: { id: likedById } },
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Retrieves a beer style like by ID.
|
||||
*
|
||||
* @param params - The parameters object for retrieving the beer style like.
|
||||
* @param params.beerStyleId - The ID of the beer style.
|
||||
* @param params.likedById - The ID of the user who liked the beer style.
|
||||
* @returns A promise that resolves to the beer style like.
|
||||
*/
|
||||
export const findBeerStyleLikeService: FindBeerStyleLike = async ({
|
||||
beerStyleId,
|
||||
likedById,
|
||||
}) => DBClient.instance.beerStyleLike.findFirst({ where: { beerStyleId, likedById } });
|
||||
|
||||
/**
|
||||
* Removes a beer style like.
|
||||
*
|
||||
* @param params - The parameters object for removing the beer style like.
|
||||
* @param params.beerStyleLikeId - The ID of the beer style like to remove.
|
||||
* @returns A promise that resolves to the removed beer style like.
|
||||
*/
|
||||
export const removeBeerStyleLikeService: RemoveBeerStyleLike = async ({
|
||||
beerStyleLikeId,
|
||||
}) => DBClient.instance.beerStyleLike.delete({ where: { id: beerStyleLikeId } });
|
||||
|
||||
/**
|
||||
* Retrieves the number of likes for a beer style.
|
||||
*
|
||||
* @param params - The parameters object for retrieving the number of likes for a beer
|
||||
* style.
|
||||
* @param params.beerStyleId - The ID of the beer style.
|
||||
* @returns A promise that resolves to the number of likes for a beer style.
|
||||
*/
|
||||
export const getBeerStyleLikeCountService: GetBeerStyleLikeCount = async ({
|
||||
beerStyleId,
|
||||
}) => DBClient.instance.beerStyleLike.count({ where: { beerStyleId } });
|
||||
@@ -0,0 +1,11 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const BeerStyleLikeSchema = z.object({
|
||||
id: z.string().cuid(),
|
||||
beerStyleId: z.string().cuid(),
|
||||
likedById: z.string().cuid(),
|
||||
createdAt: z.coerce.date(),
|
||||
updatedAt: z.coerce.date().nullable(),
|
||||
});
|
||||
|
||||
export default BeerStyleLikeSchema;
|
||||
@@ -0,0 +1,23 @@
|
||||
import GetUserSchema from '@/services/users/auth/schema/GetUserSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
import BeerStyleLikeSchema from '../schema/BeerStyleLikeSchema';
|
||||
|
||||
type User = z.infer<typeof GetUserSchema>;
|
||||
type ReturnSchema = z.infer<typeof BeerStyleLikeSchema>;
|
||||
|
||||
export type CreateBeerStyleLike = (args: {
|
||||
beerStyleId: string;
|
||||
likedById: User['id'];
|
||||
}) => Promise<ReturnSchema>;
|
||||
|
||||
export type FindBeerStyleLike = (args: {
|
||||
beerStyleId: string;
|
||||
likedById: User['id'];
|
||||
}) => Promise<ReturnSchema | null>;
|
||||
|
||||
export type RemoveBeerStyleLike = (args: {
|
||||
beerStyleLikeId: string;
|
||||
}) => Promise<ReturnSchema>;
|
||||
|
||||
export type GetBeerStyleLikeCount = (args: { beerStyleId: string }) => Promise<number>;
|
||||
@@ -0,0 +1,63 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
|
||||
import {
|
||||
CreateBreweryPostLike,
|
||||
FindBreweryPostLike,
|
||||
GetBreweryPostLikeCount,
|
||||
RemoveBreweryPostLike,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Creates a new brewery post like.
|
||||
*
|
||||
* @param params - The parameters object for creating the brewery post like.
|
||||
* @param params.breweryPostId - The ID of the brewery post.
|
||||
* @param params.likedById - The ID of the user who will like the brewery post.
|
||||
* @returns A promise that resolves to the newly created brewery post like.
|
||||
*/
|
||||
export const createBreweryPostLikeService: CreateBreweryPostLike = async ({
|
||||
breweryPostId,
|
||||
likedById,
|
||||
}) =>
|
||||
DBClient.instance.breweryPostLike.create({
|
||||
data: {
|
||||
breweryPost: { connect: { id: breweryPostId } },
|
||||
likedBy: { connect: { id: likedById } },
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Retrieves a brewery post like by ID.
|
||||
*
|
||||
* @param params - The parameters object for retrieving the brewery post like.
|
||||
* @param params.breweryPostId - The ID of the brewery post.
|
||||
* @param params.likedById - The ID of the user who liked the brewery post.
|
||||
* @returns A promise that resolves to the brewery post like.
|
||||
*/
|
||||
export const findBreweryPostLikeService: FindBreweryPostLike = async ({
|
||||
breweryPostId,
|
||||
likedById,
|
||||
}) =>
|
||||
DBClient.instance.breweryPostLike.findFirst({ where: { breweryPostId, likedById } });
|
||||
|
||||
/**
|
||||
* Removes a brewery post like.
|
||||
*
|
||||
* @param params - The parameters object for removing the brewery post like.
|
||||
* @param params.breweryPostLikeId - The ID of the brewery post like to remove.
|
||||
* @returns A promise that resolves to the removed brewery post like.
|
||||
*/
|
||||
export const removeBreweryPostLikeService: RemoveBreweryPostLike = async ({
|
||||
breweryPostLikeId,
|
||||
}) => DBClient.instance.breweryPostLike.delete({ where: { id: breweryPostLikeId } });
|
||||
|
||||
/**
|
||||
* Retrieves the number of likes for a brewery post.
|
||||
*
|
||||
* @param params - The parameters object for retrieving the number of likes for a brewery
|
||||
* @param params.breweryPostId - The ID of the brewery post.
|
||||
* @returns A promise that resolves to the number of likes for a brewery post.
|
||||
*/
|
||||
export const getBreweryPostLikeCountService: GetBreweryPostLikeCount = async ({
|
||||
breweryPostId,
|
||||
}) => DBClient.instance.breweryPostLike.count({ where: { breweryPostId } });
|
||||
@@ -0,0 +1,11 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const BreweryPostLikeSchema = z.object({
|
||||
id: z.string().cuid(),
|
||||
breweryPostId: z.string().cuid(),
|
||||
likedById: z.string().cuid(),
|
||||
createdAt: z.coerce.date(),
|
||||
updatedAt: z.coerce.date().nullable(),
|
||||
});
|
||||
|
||||
export default BreweryPostLikeSchema;
|
||||
@@ -0,0 +1,24 @@
|
||||
import GetUserSchema from '@/services/users/auth/schema/GetUserSchema';
|
||||
import { z } from 'zod';
|
||||
import BreweryPostLikeSchema from '../schema/BreweryPostLikeSchema';
|
||||
|
||||
type User = z.infer<typeof GetUserSchema>;
|
||||
type ReturnSchema = z.infer<typeof BreweryPostLikeSchema>;
|
||||
|
||||
export type CreateBreweryPostLike = (args: {
|
||||
breweryPostId: string;
|
||||
likedById: User['id'];
|
||||
}) => Promise<ReturnSchema>;
|
||||
|
||||
export type FindBreweryPostLike = (args: {
|
||||
breweryPostId: string;
|
||||
likedById: User['id'];
|
||||
}) => Promise<ReturnSchema | null>;
|
||||
|
||||
export type RemoveBreweryPostLike = (args: {
|
||||
breweryPostLikeId: string;
|
||||
}) => Promise<ReturnSchema>;
|
||||
|
||||
export type GetBreweryPostLikeCount = (args: {
|
||||
breweryPostId: string;
|
||||
}) => Promise<number>;
|
||||
276
archive/next-js-web-app/src/services/posts/beer-post/index.ts
Normal file
276
archive/next-js-web-app/src/services/posts/beer-post/index.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import {
|
||||
CreateNewBeerPost,
|
||||
EditBeerPostById,
|
||||
FindOrDeleteBeerPostById,
|
||||
GetAllBeerPosts,
|
||||
GetAllBeerPostsByBreweryId,
|
||||
GetAllBeerPostsByPostedById,
|
||||
GetAllBeerPostsByStyleId,
|
||||
GetBeerRecommendations,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The select object for retrieving beer posts.
|
||||
*
|
||||
* Satisfies the BeerPostQueryResult zod schema.
|
||||
*
|
||||
* @example
|
||||
* const beerPosts = await DBClient.instance.beerPost.findMany({
|
||||
* select: beerPostSelect,
|
||||
* });
|
||||
*/
|
||||
const beerPostSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
abv: true,
|
||||
ibu: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
beerImages: {
|
||||
select: {
|
||||
alt: true,
|
||||
path: true,
|
||||
caption: true,
|
||||
id: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
},
|
||||
brewery: { select: { id: true, name: true } },
|
||||
style: { select: { id: true, name: true, description: true } },
|
||||
postedBy: { select: { id: true, username: true } },
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Creates a new beer post.
|
||||
*
|
||||
* @param params - The parameters object for creating the beer post.
|
||||
* @param params.name - The name of the beer.
|
||||
* @param params.description - The description of the beer.
|
||||
* @param params.abv - The alcohol by volume of the beer.
|
||||
* @param params.ibu - The International Bitterness Units of the beer.
|
||||
* @param params.styleId - The ID of the beer style.
|
||||
* @param params.breweryId - The ID of the brewery.
|
||||
* @param params.userId - The ID of the user who posted the beer.
|
||||
* @returns A promise that resolves to the newly created beer post.
|
||||
*/
|
||||
export const createNewBeerPost: CreateNewBeerPost = ({
|
||||
name,
|
||||
description,
|
||||
abv,
|
||||
ibu,
|
||||
styleId,
|
||||
breweryId,
|
||||
userId,
|
||||
}) => {
|
||||
return DBClient.instance.beerPost.create({
|
||||
data: {
|
||||
name,
|
||||
description,
|
||||
abv,
|
||||
ibu,
|
||||
style: { connect: { id: styleId } },
|
||||
postedBy: { connect: { id: userId } },
|
||||
brewery: { connect: { id: breweryId } },
|
||||
},
|
||||
select: beerPostSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves a beer post by ID.
|
||||
*
|
||||
* @param params - The parameters object for retrieving the beer post.
|
||||
* @param params.beerPostId - The ID of the beer post to retrieve.
|
||||
* @returns A promise that resolves to the beer post.
|
||||
*/
|
||||
export const getBeerPostById: FindOrDeleteBeerPostById = async ({ beerPostId }) => {
|
||||
return DBClient.instance.beerPost.findFirst({
|
||||
where: { id: beerPostId },
|
||||
select: beerPostSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves all beer posts with pagination.
|
||||
*
|
||||
* @param params - The parameters object for retrieving beer posts.
|
||||
* @param params.pageNum The page number to retrieve.
|
||||
* @param params.pageSize The number of beer posts per page.
|
||||
* @returns An object containing the beer posts and the total count.
|
||||
*/
|
||||
export const getAllBeerPostsService: GetAllBeerPosts = async ({ pageNum, pageSize }) => {
|
||||
const beerPosts = await DBClient.instance.beerPost.findMany({
|
||||
select: beerPostSelect,
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.beerPost.count();
|
||||
|
||||
return { beerPosts, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves beer posts by beer style ID.
|
||||
*
|
||||
* @param params - The parameters object for retrieving beer posts.
|
||||
* @param params.pageNum - The page number of the results.
|
||||
* @param params.pageSize - The number of results per page.
|
||||
* @param params.styleId - The ID of the beer style.
|
||||
* @returns A promise that resolves to an object containing the beer posts and the total
|
||||
* count.
|
||||
*/
|
||||
export const getBeerPostsByBeerStyleIdService: GetAllBeerPostsByStyleId = async ({
|
||||
pageNum,
|
||||
pageSize,
|
||||
styleId,
|
||||
}) => {
|
||||
const beerPosts = await DBClient.instance.beerPost.findMany({
|
||||
where: { styleId },
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
select: beerPostSelect,
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.beerPost.count({
|
||||
where: { styleId },
|
||||
});
|
||||
|
||||
return { beerPosts, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves beer posts by brewery ID.
|
||||
*
|
||||
* @param params - The parameters object for retrieving beer posts.
|
||||
* @param params.pageNum - The page number of the results.
|
||||
* @param params.pageSize - The number of beer posts per page.
|
||||
* @param params.breweryId - The ID of the brewery.
|
||||
* @returns A promise that resolves to an object containing the beer posts and the total
|
||||
* count.
|
||||
*/
|
||||
export const getBeerPostsByBreweryIdService: GetAllBeerPostsByBreweryId = async ({
|
||||
pageNum,
|
||||
pageSize,
|
||||
breweryId,
|
||||
}) => {
|
||||
const beerPosts = await DBClient.instance.beerPost.findMany({
|
||||
where: { breweryId },
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
select: beerPostSelect,
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.beerPost.count({
|
||||
where: { breweryId },
|
||||
});
|
||||
|
||||
return { beerPosts, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves beer posts by the ID of the user who posted them.
|
||||
*
|
||||
* @param params - The parameters object for retrieving beer posts.
|
||||
* @param params.pageNum The page number of the results.
|
||||
* @param params.pageSize The number of results per page.
|
||||
* @param params.postedById The ID of the user who posted the beer posts.
|
||||
* @returns A promise that resolves to an object containing the beer posts and the total
|
||||
* count.
|
||||
*/
|
||||
export const getBeerPostsByPostedByIdService: GetAllBeerPostsByPostedById = async ({
|
||||
pageNum,
|
||||
pageSize,
|
||||
postedById,
|
||||
}) => {
|
||||
const beerPosts = await DBClient.instance.beerPost.findMany({
|
||||
where: { postedById },
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
select: beerPostSelect,
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.beerPost.count({
|
||||
where: { postedById },
|
||||
});
|
||||
|
||||
return { beerPosts, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves beer recommendations based on the given parameters.
|
||||
*
|
||||
* @param params - The parameters object for retrieving beer recommendations.
|
||||
* @param params.beerPost - The beer post for which recommendations are requested.
|
||||
* @param params.pageNum - The page number of the recommendations.
|
||||
* @param params.pageSize - The number of recommendations per page.
|
||||
* @returns A promise that resolves to an object containing the beer recommendations and
|
||||
* the total count.
|
||||
*/
|
||||
export const getBeerRecommendationsService: GetBeerRecommendations = async ({
|
||||
beerPost,
|
||||
pageNum,
|
||||
pageSize,
|
||||
}) => {
|
||||
const beerRecommendations = await DBClient.instance.beerPost.findMany({
|
||||
where: {
|
||||
OR: [{ styleId: beerPost.style.id }, { breweryId: beerPost.brewery.id }],
|
||||
NOT: { id: beerPost.id },
|
||||
},
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
select: beerPostSelect,
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.beerPost.count({
|
||||
where: {
|
||||
OR: [{ styleId: beerPost.style.id }, { breweryId: beerPost.brewery.id }],
|
||||
NOT: { id: beerPost.id },
|
||||
},
|
||||
});
|
||||
|
||||
return { beerRecommendations, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Service for editing a beer post by ID.
|
||||
*
|
||||
* @param params - The parameters object for editing the beer post.
|
||||
* @param params.beerPostId - The ID of the beer post to edit.
|
||||
* @param params.body - The updated data for the beer post.
|
||||
* @param params.body.abv - The updated ABV (Alcohol By Volume) of the beer.
|
||||
* @param params.body.description - The updated description of the beer.
|
||||
* @param params.body.ibu - The updated IBU (International Bitterness Units) of the beer.
|
||||
* @param params.body.name - The updated name of the beer.
|
||||
* @returns - A promise that resolves to the updated beer post.
|
||||
*/
|
||||
export const editBeerPostByIdService: EditBeerPostById = async ({
|
||||
body: { abv, description, ibu, name },
|
||||
beerPostId,
|
||||
}) => {
|
||||
return DBClient.instance.beerPost.update({
|
||||
where: { id: beerPostId },
|
||||
data: { abv, description, ibu, name },
|
||||
select: beerPostSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Service for deleting a beer post by ID.
|
||||
*
|
||||
* @param params - The parameters object for deleting the beer post.
|
||||
* @param params.beerPostId - The ID of the beer post to delete.
|
||||
* @returns - A promise that resolves to the deleted beer post.
|
||||
*/
|
||||
export const deleteBeerPostByIdService: FindOrDeleteBeerPostById = async ({
|
||||
beerPostId,
|
||||
}) => {
|
||||
return DBClient.instance.beerPost.delete({
|
||||
where: { id: beerPostId },
|
||||
select: beerPostSelect,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import ImageQueryValidationSchema from '@/services/schema/ImageSchema/ImageQueryValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
const BeerPostQueryResult = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
brewery: z.object({ id: z.string(), name: z.string() }),
|
||||
description: z.string(),
|
||||
beerImages: z.array(ImageQueryValidationSchema),
|
||||
ibu: z.number(),
|
||||
abv: z.number(),
|
||||
style: z.object({ id: z.string(), name: z.string(), description: z.string() }),
|
||||
postedBy: z.object({ id: z.string(), username: z.string() }),
|
||||
createdAt: z.coerce.date(),
|
||||
updatedAt: z.coerce.date().nullable(),
|
||||
});
|
||||
|
||||
export default BeerPostQueryResult;
|
||||
@@ -0,0 +1,43 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const CreateBeerPostValidationSchema = z.object({
|
||||
name: z
|
||||
.string({
|
||||
required_error: 'Beer name is required.',
|
||||
invalid_type_error: 'Beer name must be a string.',
|
||||
})
|
||||
.min(1, { message: 'Beer name is required.' })
|
||||
.max(100, { message: 'Beer name is too long.' }),
|
||||
description: z
|
||||
.string()
|
||||
.min(1, { message: 'Description is required.' })
|
||||
.max(500, { message: 'Description is too long.' }),
|
||||
abv: z
|
||||
.number({
|
||||
required_error: 'ABV is required.',
|
||||
invalid_type_error: 'ABV must be a number.',
|
||||
})
|
||||
.min(0.1, { message: 'ABV must be greater than 0.1.' })
|
||||
.max(50, { message: 'ABV must be less than 50.' }),
|
||||
ibu: z
|
||||
.number({
|
||||
required_error: 'IBU is required.',
|
||||
invalid_type_error: 'IBU must be a number.',
|
||||
})
|
||||
.min(2, { message: 'IBU must be greater than 2.' })
|
||||
.max(100, { message: 'IBU must be less than 100.' }),
|
||||
styleId: z
|
||||
.string({
|
||||
required_error: 'Style id is required.',
|
||||
invalid_type_error: 'Style id must be a string.',
|
||||
})
|
||||
.cuid({ message: 'Invalid type id.' }),
|
||||
breweryId: z
|
||||
.string({
|
||||
required_error: 'Brewery id is required.',
|
||||
invalid_type_error: 'Brewery id must be a string.',
|
||||
})
|
||||
.cuid({ message: 'Invalid brewery id.' }),
|
||||
});
|
||||
|
||||
export default CreateBeerPostValidationSchema;
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from 'zod';
|
||||
import CreateBeerPostValidationSchema from './CreateBeerPostValidationSchema';
|
||||
|
||||
const EditBeerPostValidationSchema = CreateBeerPostValidationSchema.omit({
|
||||
breweryId: true,
|
||||
styleId: true,
|
||||
}).extend({ id: z.string().cuid() });
|
||||
|
||||
export default EditBeerPostValidationSchema;
|
||||
@@ -0,0 +1,60 @@
|
||||
import { z } from 'zod';
|
||||
import BeerPostQueryResult from '../schema/BeerPostQueryResult';
|
||||
import EditBeerPostValidationSchema from '../schema/EditBeerPostValidationSchema';
|
||||
import CreateBeerPostValidationSchema from '../schema/CreateBeerPostValidationSchema';
|
||||
|
||||
const CreateSchema = CreateBeerPostValidationSchema.extend({
|
||||
userId: z.string().cuid(),
|
||||
});
|
||||
const EditSchema = EditBeerPostValidationSchema.omit({ id: true });
|
||||
|
||||
type BeerPost = z.infer<typeof BeerPostQueryResult>;
|
||||
|
||||
export type CreateNewBeerPost = (args: z.infer<typeof CreateSchema>) => Promise<BeerPost>;
|
||||
|
||||
export type EditBeerPostById = (args: {
|
||||
beerPostId: string;
|
||||
body: z.infer<typeof EditSchema>;
|
||||
}) => Promise<BeerPost>;
|
||||
|
||||
export type FindOrDeleteBeerPostById = (args: {
|
||||
beerPostId: string;
|
||||
}) => Promise<BeerPost | null>;
|
||||
|
||||
export type GetAllBeerPosts = (args: { pageNum: number; pageSize: number }) => Promise<{
|
||||
beerPosts: BeerPost[];
|
||||
count: number;
|
||||
}>;
|
||||
|
||||
export type GetAllBeerPostsByPostedById = (args: {
|
||||
postedById: string;
|
||||
pageSize: number;
|
||||
pageNum: number;
|
||||
}) => Promise<{
|
||||
beerPosts: BeerPost[];
|
||||
count: number;
|
||||
}>;
|
||||
|
||||
export type GetAllBeerPostsByStyleId = (args: {
|
||||
styleId: string;
|
||||
pageSize: number;
|
||||
pageNum: number;
|
||||
}) => Promise<{
|
||||
beerPosts: BeerPost[];
|
||||
count: number;
|
||||
}>;
|
||||
|
||||
export type GetAllBeerPostsByBreweryId = (args: {
|
||||
breweryId: string;
|
||||
pageSize: number;
|
||||
pageNum: number;
|
||||
}) => Promise<{
|
||||
beerPosts: BeerPost[];
|
||||
count: number;
|
||||
}>;
|
||||
|
||||
export type GetBeerRecommendations = (args: {
|
||||
beerPost: BeerPost;
|
||||
pageNum: number;
|
||||
pageSize: number;
|
||||
}) => Promise<{ beerRecommendations: BeerPost[]; count: number }>;
|
||||
@@ -0,0 +1,182 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import type {
|
||||
CreateBeerStyle,
|
||||
DeleteBeerStyleById,
|
||||
EditBeerStyleById,
|
||||
GetAllBeerStyles,
|
||||
GetBeerStyleById,
|
||||
} from '@/services/posts/beer-style-post/types';
|
||||
|
||||
/**
|
||||
* The select object for retrieving beer styles.
|
||||
*
|
||||
* Satisfies the BeerStyleQueryResult zod schema.
|
||||
*
|
||||
* @remarks
|
||||
* Prisma does not support tuples, so we have to typecast the ibuRange and abvRange fields
|
||||
* to satisfy the zod schema.
|
||||
* @example
|
||||
* const beerStyles = await DBClient.instance.beerStyle.findMany({
|
||||
* select: beerStyleSelect,
|
||||
* });
|
||||
*/
|
||||
const beerStyleSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
abvRange: true,
|
||||
ibuRange: true,
|
||||
description: true,
|
||||
postedBy: { select: { id: true, username: true } },
|
||||
glassware: { select: { id: true, name: true } },
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Deletes a beer style by id.
|
||||
*
|
||||
* @param args - The arguments for the service.
|
||||
* @param args.beerStyleId - The id of the beer style to delete.
|
||||
* @returns The deleted beer style.
|
||||
*/
|
||||
export const deleteBeerStyleService: DeleteBeerStyleById = async ({ beerStyleId }) => {
|
||||
const deleted = await DBClient.instance.beerStyle.delete({
|
||||
where: { id: beerStyleId },
|
||||
select: beerStyleSelect,
|
||||
});
|
||||
|
||||
return deleted as Awaited<ReturnType<typeof deleteBeerStyleService>>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Edits a beer style by id.
|
||||
*
|
||||
* @param args - The arguments for the service.
|
||||
* @param args.beerStyleId - The id of the beer style to edit.
|
||||
* @param args.body - The data to update the beer style with.
|
||||
* @param args.body.abvRange - The abv range of the beer style.
|
||||
* @param args.body.description - The description of the beer style.
|
||||
* @param args.body.glasswareId - The id of the glassware to connect to the beer style.
|
||||
* @param args.body.ibuRange - The ibu range of the beer style.
|
||||
* @param args.body.name - The name of the beer style.
|
||||
* @returns The updated beer style.
|
||||
*/
|
||||
export const editBeerStyleService: EditBeerStyleById = async ({ beerStyleId, body }) => {
|
||||
const { abvRange, description, glasswareId, ibuRange, name } = body;
|
||||
|
||||
const glassware = await DBClient.instance.glassware.findUnique({
|
||||
where: { id: glasswareId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!glassware) {
|
||||
throw new ServerError(
|
||||
'A glassware with that id does not exist and cannot be connected.',
|
||||
404,
|
||||
);
|
||||
}
|
||||
|
||||
const updated = await DBClient.instance.beerStyle.update({
|
||||
where: { id: beerStyleId },
|
||||
data: {
|
||||
abvRange,
|
||||
description,
|
||||
ibuRange,
|
||||
name,
|
||||
glassware: { connect: { id: glasswareId } },
|
||||
},
|
||||
select: beerStyleSelect,
|
||||
});
|
||||
|
||||
return updated as Awaited<ReturnType<typeof editBeerStyleService>>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets all beer styles with pagination.
|
||||
*
|
||||
* @param args - The arguments for the service.
|
||||
* @param args.pageNum - The page number of the results.
|
||||
* @param args.pageSize - The page size of the results.
|
||||
* @returns The beer styles and the total count of beer styles.
|
||||
*/
|
||||
export const getAllBeerStylesService: GetAllBeerStyles = async ({
|
||||
pageNum,
|
||||
pageSize,
|
||||
}) => {
|
||||
const beerStyles = await DBClient.instance.beerStyle.findMany({
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
select: beerStyleSelect,
|
||||
});
|
||||
|
||||
const beerStyleCount = await DBClient.instance.beerStyle.count();
|
||||
|
||||
return {
|
||||
beerStyles: beerStyles as Awaited<
|
||||
ReturnType<typeof getAllBeerStylesService>
|
||||
>['beerStyles'],
|
||||
beerStyleCount,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets a beer style by id.
|
||||
*
|
||||
* @param args - The arguments for the service.
|
||||
* @param args.beerStyleId - The id of the beer style to get.
|
||||
* @returns The beer style.
|
||||
*/
|
||||
export const getBeerStyleByIdService: GetBeerStyleById = async ({ beerStyleId }) => {
|
||||
const beerStyle = await DBClient.instance.beerStyle.findUnique({
|
||||
where: { id: beerStyleId },
|
||||
select: beerStyleSelect,
|
||||
});
|
||||
|
||||
return beerStyle as Awaited<ReturnType<typeof getBeerStyleByIdService>>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a beer style.
|
||||
*
|
||||
* @param args - The arguments for the service.
|
||||
* @param args.body - The data to create the beer style with.
|
||||
* @param args.body.abvRange - The abv range of the beer style.
|
||||
* @param args.body.description - The description of the beer style.
|
||||
* @param args.body.glasswareId - The id of the glassware to connect to the beer style.
|
||||
* @param args.body.ibuRange - The ibu range of the beer style.
|
||||
* @param args.body.name - The name of the beer style.
|
||||
* @param args.glasswareId - The id of the glassware to connect to the beer style.
|
||||
* @param args.postedById - The id of the user who posted the beer style.
|
||||
*/
|
||||
export const createBeerStyleService: CreateBeerStyle = async ({
|
||||
body: { abvRange, description, ibuRange, name },
|
||||
glasswareId,
|
||||
postedById,
|
||||
}) => {
|
||||
const glassware = await DBClient.instance.glassware.findUnique({
|
||||
where: { id: glasswareId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!glassware) {
|
||||
throw new ServerError(
|
||||
'A glassware with that id does not exist and cannot be connected.',
|
||||
404,
|
||||
);
|
||||
}
|
||||
|
||||
const beerStyle = await DBClient.instance.beerStyle.create({
|
||||
data: {
|
||||
name,
|
||||
description,
|
||||
abvRange,
|
||||
ibuRange,
|
||||
glassware: { connect: { id: glasswareId } },
|
||||
postedBy: { connect: { id: postedById } },
|
||||
},
|
||||
select: beerStyleSelect,
|
||||
});
|
||||
|
||||
return beerStyle as Awaited<ReturnType<typeof createBeerStyleService>>;
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const BeerStyleQueryResult = z.object({
|
||||
abvRange: z.tuple([z.number(), z.number()]),
|
||||
createdAt: z.coerce.date(),
|
||||
description: z.string(),
|
||||
glassware: z.object({ id: z.string().cuid(), name: z.string() }),
|
||||
ibuRange: z.tuple([z.number(), z.number()]),
|
||||
id: z.string().cuid(),
|
||||
name: z.string(),
|
||||
postedBy: z.object({ id: z.string().cuid(), username: z.string() }),
|
||||
updatedAt: z.coerce.date().nullable(),
|
||||
});
|
||||
|
||||
export default BeerStyleQueryResult;
|
||||
@@ -0,0 +1,46 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const CreateBeerStyleValidationSchema = z.object({
|
||||
glasswareId: z
|
||||
.string()
|
||||
.cuid({
|
||||
message: 'Glassware ID must be a valid CUID.',
|
||||
})
|
||||
.min(1, { message: 'Glassware ID is required.' }),
|
||||
description: z
|
||||
.string()
|
||||
.min(1, { message: 'Description is required.' })
|
||||
.max(500, { message: 'Description must be less than or equal to 500 characters.' }),
|
||||
ibuRange: z
|
||||
.tuple([
|
||||
z
|
||||
.number()
|
||||
.min(0, { message: 'IBU range minimum must be greater than or equal to 0.' })
|
||||
.max(100, { message: 'IBU range minimum must be less than or equal to 100.' }),
|
||||
z
|
||||
.number()
|
||||
.min(0, { message: 'IBU range maximum must be greater than or equal to 0.' })
|
||||
.max(100, { message: 'IBU range maximum must be less than or equal to 100.' }),
|
||||
])
|
||||
.refine((ibuRange) => ibuRange[0] <= ibuRange[1], {
|
||||
message: 'IBU range minimum must be less than or equal to maximum.',
|
||||
}),
|
||||
abvRange: z
|
||||
.tuple([
|
||||
z
|
||||
.number()
|
||||
.min(0, { message: 'ABV range minimum must be greater than or equal to 0.' }),
|
||||
z
|
||||
.number()
|
||||
.min(0, { message: 'ABV range maximum must be greater than or equal to 0.' }),
|
||||
])
|
||||
.refine((abvRange) => abvRange[0] <= abvRange[1], {
|
||||
message: 'ABV range minimum must be less than or equal to maximum.',
|
||||
}),
|
||||
name: z
|
||||
.string()
|
||||
.min(1, { message: 'Name is required.' })
|
||||
.max(100, { message: 'Name must be less than or equal to 100 characters.' }),
|
||||
});
|
||||
|
||||
export default CreateBeerStyleValidationSchema;
|
||||
@@ -0,0 +1,39 @@
|
||||
import { z } from 'zod';
|
||||
import BeerStyleQueryResult from '../schema/BeerStyleQueryResult';
|
||||
|
||||
type BeerStyle = z.infer<typeof BeerStyleQueryResult>;
|
||||
|
||||
export type GetBeerStyleById = (args: {
|
||||
beerStyleId: string;
|
||||
}) => Promise<BeerStyle | null>;
|
||||
|
||||
export type DeleteBeerStyleById = (args: {
|
||||
beerStyleId: string;
|
||||
}) => Promise<BeerStyle | null>;
|
||||
|
||||
export type EditBeerStyleById = (args: {
|
||||
beerStyleId: string;
|
||||
body: {
|
||||
name: string;
|
||||
description: string;
|
||||
abvRange: [number, number];
|
||||
ibuRange: [number, number];
|
||||
glasswareId: string;
|
||||
};
|
||||
}) => Promise<BeerStyle | null>;
|
||||
|
||||
export type GetAllBeerStyles = (args: { pageNum: number; pageSize: number }) => Promise<{
|
||||
beerStyles: BeerStyle[];
|
||||
beerStyleCount: number;
|
||||
}>;
|
||||
|
||||
export type CreateBeerStyle = (args: {
|
||||
body: {
|
||||
name: string;
|
||||
description: string;
|
||||
abvRange: [number, number];
|
||||
ibuRange: [number, number];
|
||||
};
|
||||
glasswareId: string;
|
||||
postedById: string;
|
||||
}) => Promise<BeerStyle>;
|
||||
241
archive/next-js-web-app/src/services/posts/brewery-post/index.ts
Normal file
241
archive/next-js-web-app/src/services/posts/brewery-post/index.ts
Normal file
@@ -0,0 +1,241 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
|
||||
import {
|
||||
CreateBreweryPostLocation,
|
||||
CreateNewBreweryPost,
|
||||
GetAllBreweryPosts,
|
||||
GetAllBreweryPostsByPostedById,
|
||||
GetBreweryPostById,
|
||||
GetMapBreweryPosts,
|
||||
UpdateBreweryPost,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The select object to use when querying for brewery posts.
|
||||
*
|
||||
* @remarks
|
||||
* Prisma does not support tuples, so we have to typecast the coordinates field to
|
||||
* [number, number] in order to satisfy the zod schema.
|
||||
*/
|
||||
const breweryPostSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
createdAt: true,
|
||||
dateEstablished: true,
|
||||
postedBy: { select: { id: true, username: true } },
|
||||
breweryImages: {
|
||||
select: {
|
||||
path: true,
|
||||
caption: true,
|
||||
id: true,
|
||||
alt: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
},
|
||||
location: {
|
||||
select: {
|
||||
city: true,
|
||||
address: true,
|
||||
coordinates: true,
|
||||
country: true,
|
||||
stateOrProvince: true,
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Creates a new brewery post.
|
||||
*
|
||||
* @param args - The arguments to create a new brewery post.
|
||||
* @param args.name - The name of the brewery.
|
||||
* @param args.description - The description of the brewery.
|
||||
* @param args.dateEstablished - The date the brewery was established.
|
||||
* @param args.userId - The id of the user who created the brewery post.
|
||||
* @param args.locationId - The id of the location of the brewery.
|
||||
* @returns The newly created brewery post.
|
||||
*/
|
||||
export const createNewBreweryPostService: CreateNewBreweryPost = async ({
|
||||
dateEstablished,
|
||||
description,
|
||||
locationId,
|
||||
name,
|
||||
userId,
|
||||
}) => {
|
||||
const post = (await DBClient.instance.breweryPost.create({
|
||||
data: {
|
||||
name,
|
||||
description,
|
||||
dateEstablished,
|
||||
location: { connect: { id: locationId } },
|
||||
postedBy: { connect: { id: userId } },
|
||||
},
|
||||
select: breweryPostSelect,
|
||||
})) as Awaited<ReturnType<typeof createNewBreweryPostService>>;
|
||||
|
||||
return post;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves all brewery posts paginated.
|
||||
*
|
||||
* @param args - The arguments to get all brewery posts.
|
||||
* @param args.pageNum - The page number of the brewery posts to get.
|
||||
* @param args.pageSize - The number of brewery posts to get per page.
|
||||
* @returns All brewery posts.
|
||||
*/
|
||||
export const getAllBreweryPostsService: GetAllBreweryPosts = async ({
|
||||
pageNum,
|
||||
pageSize,
|
||||
}) => {
|
||||
const breweryPosts = (await DBClient.instance.breweryPost.findMany({
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
select: breweryPostSelect,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})) as Awaited<ReturnType<typeof getAllBreweryPostsService>>['breweryPosts'];
|
||||
|
||||
const count = await DBClient.instance.breweryPost.count();
|
||||
return { breweryPosts, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves a brewery post by ID.
|
||||
*
|
||||
* @param args - The arguments to get a brewery post by ID.
|
||||
* @param args.breweryPostId - The ID of the brewery post to get.
|
||||
* @returns The brewery post.
|
||||
*/
|
||||
export const getBreweryPostByIdService: GetBreweryPostById = async ({
|
||||
breweryPostId,
|
||||
}) => {
|
||||
const breweryPost = await DBClient.instance.breweryPost.findFirst({
|
||||
select: breweryPostSelect,
|
||||
where: { id: breweryPostId },
|
||||
});
|
||||
|
||||
return breweryPost as Awaited<ReturnType<typeof getBreweryPostByIdService>>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves all brewery posts by posted by ID.
|
||||
*
|
||||
* @param args - The arguments to get all brewery posts by posted by ID.
|
||||
* @param args.pageNum - The page number of the brewery posts to get.
|
||||
* @param args.pageSize - The number of brewery posts to get per page.
|
||||
* @param args.postedById - The ID of the user who posted the brewery posts.
|
||||
*/
|
||||
export const getAllBreweryPostsByPostedByIdService: GetAllBreweryPostsByPostedById =
|
||||
async ({ pageNum, pageSize, postedById }) => {
|
||||
const breweryPosts = (await DBClient.instance.breweryPost.findMany({
|
||||
where: { postedBy: { id: postedById } },
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
select: breweryPostSelect,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})) as Awaited<
|
||||
ReturnType<typeof getAllBreweryPostsByPostedByIdService>
|
||||
>['breweryPosts'];
|
||||
|
||||
const count = await DBClient.instance.breweryPost.count({
|
||||
where: { postedBy: { id: postedById } },
|
||||
});
|
||||
|
||||
return { breweryPosts, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a brewery post location.
|
||||
*
|
||||
* @param args - The arguments to create a brewery post location.
|
||||
* @param args.body - The body of the request.
|
||||
* @param args.body.address - The address of the brewery.
|
||||
* @param args.body.city - The city of the brewery.
|
||||
* @param args.body.country - The country of the brewery.
|
||||
* @param args.body.stateOrProvince - The state or province of the brewery.
|
||||
* @param args.body.coordinates - The coordinates of the brewery in an array of [latitude,
|
||||
* longitude].
|
||||
* @param args.postedById - The ID of the user who posted the brewery post.
|
||||
* @returns The newly created brewery post location.
|
||||
*/
|
||||
export const createBreweryPostLocationService: CreateBreweryPostLocation = async ({
|
||||
body: { address, city, country, stateOrProvince, coordinates },
|
||||
postedById,
|
||||
}) => {
|
||||
const [latitude, longitude] = coordinates;
|
||||
|
||||
return DBClient.instance.breweryLocation.create({
|
||||
data: {
|
||||
address,
|
||||
city,
|
||||
country,
|
||||
stateOrProvince,
|
||||
coordinates: [latitude, longitude],
|
||||
postedBy: { connect: { id: postedById } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets all brewery posts for the post map.
|
||||
*
|
||||
* @param args - The arguments to get all brewery posts for the post map.
|
||||
* @param args.pageNum - The page number of the brewery posts to get.
|
||||
* @param args.pageSize - The number of brewery posts to get per page.
|
||||
* @returns All brewery posts for the post map.
|
||||
*/
|
||||
export const getMapBreweryPostsService: GetMapBreweryPosts = async ({
|
||||
pageNum,
|
||||
pageSize,
|
||||
}) => {
|
||||
const breweryPosts = await DBClient.instance.breweryPost.findMany({
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
location: {
|
||||
select: { coordinates: true, city: true, country: true, stateOrProvince: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.breweryPost.count();
|
||||
return { breweryPosts, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates a brewery post.
|
||||
*
|
||||
* @param args - The arguments to update a brewery post.
|
||||
* @param args.breweryPostId - The ID of the brewery post to update.
|
||||
* @param args.body - The body of the request.
|
||||
* @param args.body.name - The name of the brewery.
|
||||
* @param args.body.description - The description of the brewery.
|
||||
* @param args.body.dateEstablished - The date the brewery was established.
|
||||
* @returns The updated brewery post.
|
||||
*/
|
||||
export const updateBreweryPostService: UpdateBreweryPost = async ({
|
||||
breweryPostId,
|
||||
body,
|
||||
}) => {
|
||||
const breweryPost = await DBClient.instance.breweryPost.update({
|
||||
where: { id: breweryPostId },
|
||||
data: body,
|
||||
select: breweryPostSelect,
|
||||
});
|
||||
|
||||
return breweryPost as Awaited<ReturnType<typeof updateBreweryPostService>>;
|
||||
};
|
||||
|
||||
export const deleteBreweryPostService: GetBreweryPostById = async ({ breweryPostId }) => {
|
||||
const breweryPost = await DBClient.instance.breweryPost.delete({
|
||||
where: { id: breweryPostId },
|
||||
select: breweryPostSelect,
|
||||
});
|
||||
|
||||
return breweryPost as Awaited<ReturnType<typeof deleteBreweryPostService>>;
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const BreweryPostMapQueryResult = z.object({
|
||||
location: z.object({
|
||||
coordinates: z.array(z.number()),
|
||||
city: z.string(),
|
||||
country: z.string().nullable(),
|
||||
stateOrProvince: z.string().nullable(),
|
||||
}),
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
});
|
||||
|
||||
export default BreweryPostMapQueryResult;
|
||||
@@ -0,0 +1,21 @@
|
||||
import ImageQueryValidationSchema from '@/services/schema/ImageSchema/ImageQueryValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
const BreweryPostQueryResult = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
location: z.object({
|
||||
city: z.string(),
|
||||
address: z.string(),
|
||||
coordinates: z.tuple([z.number(), z.number()]),
|
||||
country: z.string().nullable(),
|
||||
stateOrProvince: z.string().nullable(),
|
||||
}),
|
||||
postedBy: z.object({ id: z.string(), username: z.string() }),
|
||||
breweryImages: z.array(ImageQueryValidationSchema),
|
||||
createdAt: z.coerce.date(),
|
||||
dateEstablished: z.coerce.date(),
|
||||
});
|
||||
|
||||
export default BreweryPostQueryResult;
|
||||
@@ -0,0 +1,55 @@
|
||||
import { isPast } from 'date-fns';
|
||||
import { z } from 'zod';
|
||||
|
||||
const CreateBreweryPostSchema = z.object({
|
||||
name: z
|
||||
.string({
|
||||
required_error: 'Brewery name is required.',
|
||||
invalid_type_error: 'Brewery name must be a string.',
|
||||
})
|
||||
.min(1, { message: 'Brewery name is required.' })
|
||||
.max(100, { message: 'Brewery name is too long.' }),
|
||||
description: z
|
||||
.string({
|
||||
required_error: 'Description is required.',
|
||||
invalid_type_error: 'Description must be a string.',
|
||||
})
|
||||
.min(1, { message: 'Description is required.' })
|
||||
.max(1500, { message: 'Description is too long.' }),
|
||||
address: z
|
||||
.string({
|
||||
required_error: 'Address is required.',
|
||||
invalid_type_error: 'Address must be a string.',
|
||||
})
|
||||
.min(1, { message: 'Address is required.' })
|
||||
.max(300, { message: 'Address is too long.' }),
|
||||
|
||||
city: z
|
||||
.string({
|
||||
required_error: 'City is required.',
|
||||
invalid_type_error: 'City must be a string.',
|
||||
})
|
||||
.min(1, { message: 'City is required.' })
|
||||
.max(100, { message: 'City is too long.' }),
|
||||
|
||||
region: z
|
||||
.string({ invalid_type_error: 'region must be a string.' })
|
||||
.min(1, { message: 'region is required.' })
|
||||
.max(100, { message: 'region is too long.' })
|
||||
.optional(),
|
||||
|
||||
country: z
|
||||
.string({ invalid_type_error: 'Country must be a string.' })
|
||||
.max(100, { message: 'Country is too long.' })
|
||||
.optional(),
|
||||
|
||||
dateEstablished: z.coerce
|
||||
.date({
|
||||
required_error: 'Date established is required.',
|
||||
invalid_type_error: 'Date established must be a date string.',
|
||||
})
|
||||
.refine((val) => !Number.isNaN(val.toString()), { message: 'Date is invalid.' })
|
||||
.refine((val) => isPast(new Date(val)), { message: 'Date must be in the past.' }),
|
||||
});
|
||||
|
||||
export default CreateBreweryPostSchema;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from 'zod';
|
||||
import CreateBreweryPostSchema from './CreateBreweryPostSchema';
|
||||
|
||||
const CreateNewBreweryPostWithoutLocationSchema = CreateBreweryPostSchema.omit({
|
||||
address: true,
|
||||
city: true,
|
||||
country: true,
|
||||
stateOrProvince: true,
|
||||
}).extend({
|
||||
userId: z.string().cuid(),
|
||||
locationId: z.string().cuid(),
|
||||
});
|
||||
|
||||
export default CreateNewBreweryPostWithoutLocationSchema;
|
||||
@@ -0,0 +1,13 @@
|
||||
import { z } from 'zod';
|
||||
import CreateBreweryPostSchema from './CreateBreweryPostSchema';
|
||||
|
||||
const EditBreweryPostValidationSchema = CreateBreweryPostSchema.extend({
|
||||
id: z.string().cuid(),
|
||||
}).omit({
|
||||
address: true,
|
||||
city: true,
|
||||
region: true,
|
||||
country: true,
|
||||
});
|
||||
|
||||
export default EditBreweryPostValidationSchema;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const GetMapBreweryPostsSchema = z.object({
|
||||
name: z.string(),
|
||||
id: z.string().cuid(),
|
||||
location: z.object({
|
||||
city: z.string(),
|
||||
country: z.string().nullable(),
|
||||
stateOrProvince: z.string().nullable(),
|
||||
coordinates: z.array(z.number(), z.number()),
|
||||
}),
|
||||
});
|
||||
|
||||
export default GetMapBreweryPostsSchema;
|
||||
@@ -0,0 +1,57 @@
|
||||
import { z } from 'zod';
|
||||
import BreweryPostQueryResult from '../schema/BreweryPostQueryResult';
|
||||
import CreateNewBreweryPostWithoutLocationSchema from '../schema/CreateNewBreweryPostWithoutLocationSchema';
|
||||
import BreweryPostMapQueryResult from '../schema/BreweryPostMapQueryResult';
|
||||
|
||||
export type CreateNewBreweryPost = (
|
||||
args: z.infer<typeof CreateNewBreweryPostWithoutLocationSchema>,
|
||||
) => Promise<z.infer<typeof BreweryPostQueryResult>>;
|
||||
|
||||
export type GetAllBreweryPosts = (args: {
|
||||
pageNum: number;
|
||||
pageSize: number;
|
||||
}) => Promise<{
|
||||
breweryPosts: z.infer<typeof BreweryPostQueryResult>[];
|
||||
count: number;
|
||||
}>;
|
||||
|
||||
export type GetBreweryPostById = (args: {
|
||||
breweryPostId: string;
|
||||
}) => Promise<z.infer<typeof BreweryPostQueryResult> | null>;
|
||||
|
||||
export type GetAllBreweryPostsByPostedById = (args: {
|
||||
pageNum: number;
|
||||
pageSize: number;
|
||||
postedById: string;
|
||||
}) => Promise<{
|
||||
breweryPosts: z.infer<typeof BreweryPostQueryResult>[];
|
||||
count: number;
|
||||
}>;
|
||||
|
||||
export type CreateBreweryPostLocation = (args: {
|
||||
body: {
|
||||
address: string;
|
||||
city: string;
|
||||
country?: string;
|
||||
stateOrProvince?: string;
|
||||
coordinates: [number, number];
|
||||
};
|
||||
postedById: string;
|
||||
}) => Promise<{ id: string }>;
|
||||
|
||||
export type GetMapBreweryPosts = (args: {
|
||||
pageNum: number;
|
||||
pageSize: number;
|
||||
}) => Promise<{
|
||||
breweryPosts: z.infer<typeof BreweryPostMapQueryResult>[];
|
||||
count: number;
|
||||
}>;
|
||||
|
||||
export type UpdateBreweryPost = (args: {
|
||||
breweryPostId: string;
|
||||
body: {
|
||||
name: string;
|
||||
description: string;
|
||||
dateEstablished: Date;
|
||||
};
|
||||
}) => Promise<z.infer<typeof BreweryPostQueryResult>>;
|
||||
@@ -0,0 +1,17 @@
|
||||
import { z } from 'zod';
|
||||
import ImageQueryValidationSchema from '../ImageSchema/ImageQueryValidationSchema';
|
||||
|
||||
const CommentQueryResult = z.object({
|
||||
id: z.string().cuid(),
|
||||
content: z.string().min(1).max(500),
|
||||
rating: z.number().int().min(1).max(5),
|
||||
createdAt: z.coerce.date(),
|
||||
updatedAt: z.coerce.date().nullable(),
|
||||
postedBy: z.object({
|
||||
id: z.string().cuid(),
|
||||
username: z.string().min(1).max(50),
|
||||
userAvatar: ImageQueryValidationSchema.nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
export default CommentQueryResult;
|
||||
@@ -0,0 +1,15 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const CreateCommentValidationSchema = z.object({
|
||||
content: z
|
||||
.string()
|
||||
.min(1, { message: 'Comment must not be empty.' })
|
||||
.max(300, { message: 'Comment must be less than 300 characters.' }),
|
||||
rating: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1, { message: 'Rating must be greater than 1.' })
|
||||
.max(5, { message: 'Rating must be less than 5.' }),
|
||||
});
|
||||
|
||||
export default CreateCommentValidationSchema;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const ImageMetadataValidationSchema = z.object({
|
||||
caption: z.string().min(1, { message: 'Caption is required.' }),
|
||||
alt: z.string().min(1, { message: 'Alt text is required.' }),
|
||||
});
|
||||
|
||||
export default ImageMetadataValidationSchema;
|
||||
@@ -0,0 +1,12 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const ImageQueryValidationSchema = z.object({
|
||||
id: z.string().cuid(),
|
||||
path: z.string().url(),
|
||||
alt: z.string(),
|
||||
caption: z.string(),
|
||||
createdAt: z.coerce.date(),
|
||||
updatedAt: z.coerce.date().nullable(),
|
||||
});
|
||||
|
||||
export default ImageQueryValidationSchema;
|
||||
@@ -0,0 +1,31 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const UploadImageValidationSchema = z.object({
|
||||
images: z
|
||||
.instanceof(typeof FileList !== 'undefined' ? FileList : Object)
|
||||
.refine((fileList) => fileList instanceof FileList, {
|
||||
message: 'You must submit this form in a web browser.',
|
||||
})
|
||||
.refine((fileList) => (fileList as FileList).length > 0, {
|
||||
message: 'You must upload at least one file.',
|
||||
})
|
||||
.refine((fileList) => (fileList as FileList).length < 5, {
|
||||
message: 'You can only upload up to 5 files at a time.',
|
||||
})
|
||||
.refine(
|
||||
(fileList) =>
|
||||
[...(fileList as FileList)]
|
||||
.map((file) => file.type)
|
||||
.every((fileType) => fileType.startsWith('image/')),
|
||||
{ message: 'You must upload only images.' },
|
||||
)
|
||||
.refine(
|
||||
(fileList) =>
|
||||
[...(fileList as FileList)]
|
||||
.map((file) => file.size)
|
||||
.every((fileSize) => fileSize < 15 * 1024 * 1024),
|
||||
{ message: 'You must upload images smaller than 15MB.' },
|
||||
),
|
||||
});
|
||||
|
||||
export default UploadImageValidationSchema;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const PaginatedQueryResponseSchema = z.object({
|
||||
page_num: z.string().regex(/^\d+$/),
|
||||
page_size: z.string().regex(/^\d+$/),
|
||||
});
|
||||
|
||||
export default PaginatedQueryResponseSchema;
|
||||
308
archive/next-js-web-app/src/services/users/auth/index.ts
Normal file
308
archive/next-js-web-app/src/services/users/auth/index.ts
Normal file
@@ -0,0 +1,308 @@
|
||||
/* eslint-disable import/prefer-default-export */
|
||||
import { hashPassword } from '@/config/auth/passwordFns';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import { BASE_URL } from '@/config/env';
|
||||
import { generateConfirmationToken, generateResetPasswordToken } from '@/config/jwt';
|
||||
import sendEmail from '@/config/sparkpost/sendEmail';
|
||||
|
||||
import { ReactElement } from 'react';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import { render } from '@react-email/render';
|
||||
import WelcomeEmail from '@/emails/WelcomeEmail';
|
||||
import ResetPasswordEmail from '@/emails/ForgotEmail';
|
||||
|
||||
import {
|
||||
CreateNewUser,
|
||||
DeleteUserById,
|
||||
FindUserByEmail,
|
||||
FindUserByUsername,
|
||||
FindUserById,
|
||||
SendConfirmationEmail,
|
||||
SendResetPasswordEmail,
|
||||
UpdateUserToBeConfirmedById,
|
||||
UpdateUserPassword,
|
||||
UpdateUserById,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The select object for retrieving users.
|
||||
*
|
||||
* Satisfies the GetUserSchema zod schema.
|
||||
*
|
||||
* @example
|
||||
* const users = await DBClient.instance.user.findMany({
|
||||
* select: userSelect,
|
||||
* });
|
||||
*/
|
||||
const userSelect = {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
dateOfBirth: true,
|
||||
createdAt: true,
|
||||
accountIsVerified: true,
|
||||
updatedAt: true,
|
||||
role: true,
|
||||
userAvatar: true,
|
||||
bio: true,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* The select object for retrieving users without sensitive information.
|
||||
*
|
||||
* @example
|
||||
* const user = await DBClient.instance.user.findUnique({
|
||||
* where: { id: userId },
|
||||
* select: AuthUserSelect,
|
||||
* });
|
||||
*/
|
||||
const authUserSelect = {
|
||||
id: true,
|
||||
username: true,
|
||||
hash: true,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Creates a new user.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.email The email of the user to create.
|
||||
* @param args.password The password of the user to create.
|
||||
* @param args.firstName The first name of the user to create.
|
||||
* @param args.lastName The last name of the user to create.
|
||||
* @param args.dateOfBirth The date of birth of the user to create.
|
||||
* @param args.username The username of the user to create.
|
||||
* @returns The user.
|
||||
*/
|
||||
export const createNewUserService: CreateNewUser = async ({
|
||||
email,
|
||||
password,
|
||||
firstName,
|
||||
lastName,
|
||||
dateOfBirth,
|
||||
username,
|
||||
}) => {
|
||||
const hash = await hashPassword(password);
|
||||
|
||||
const user = await DBClient.instance.user.create({
|
||||
data: {
|
||||
username,
|
||||
email,
|
||||
hash,
|
||||
firstName,
|
||||
lastName,
|
||||
dateOfBirth: new Date(dateOfBirth),
|
||||
},
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
return user;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a user by id.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to delete.
|
||||
* @returns The user that was deleted if found, otherwise null.
|
||||
*/
|
||||
export const deleteUserService: DeleteUserById = ({ userId }) => {
|
||||
return DBClient.instance.user.delete({ where: { id: userId }, select: authUserSelect });
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds a user by username.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.username The username of the user to find.
|
||||
* @returns The user if found, otherwise null.
|
||||
*/
|
||||
|
||||
export const findUserByUsernameService: FindUserByUsername = async ({ username }) => {
|
||||
return DBClient.instance.user.findUnique({
|
||||
where: { username },
|
||||
select: authUserSelect,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds a user by email.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.email The email of the user to find.
|
||||
*/
|
||||
export const findUserByEmailService: FindUserByEmail = async ({ email }) => {
|
||||
return DBClient.instance.user.findUnique({ where: { email }, select: userSelect });
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds a user by id.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to find.
|
||||
* @returns The user if found, otherwise null.
|
||||
*/
|
||||
export const findUserByIdService: FindUserById = ({ userId }) => {
|
||||
return DBClient.instance.user.findUnique({ where: { id: userId }, select: userSelect });
|
||||
};
|
||||
|
||||
/**
|
||||
* Sends a confirmation email to the user using React Email and SparkPost.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to send the confirmation email to.
|
||||
* @param args.username The username of the user to send the confirmation email to.
|
||||
* @param args.email The email of the user to send the confirmation email to.
|
||||
* @returns The user if found, otherwise null.
|
||||
*/
|
||||
export const sendConfirmationEmailService: SendConfirmationEmail = async ({
|
||||
userId,
|
||||
username,
|
||||
email,
|
||||
}) => {
|
||||
const confirmationToken = generateConfirmationToken({ id: userId, username });
|
||||
const url = `${BASE_URL}/users/confirm?token=${confirmationToken}`;
|
||||
|
||||
const name = username;
|
||||
const address = email;
|
||||
const subject = 'Confirm your email';
|
||||
|
||||
const component = WelcomeEmail({ name, url, subject })! as ReactElement<
|
||||
unknown,
|
||||
string
|
||||
>;
|
||||
|
||||
const html = render(component);
|
||||
const text = render(component, { plainText: true });
|
||||
|
||||
await sendEmail({ address, subject, text, html });
|
||||
};
|
||||
|
||||
/**
|
||||
* Sends a reset password email to the specified user.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to send the reset password email to.
|
||||
* @param args.username The username of the user to send the reset password email to.
|
||||
* @param args.email The email of the user to send the reset password email to.
|
||||
* @returns A promise that resolves to void.
|
||||
*/
|
||||
export const sendResetPasswordEmailService: SendResetPasswordEmail = async ({
|
||||
userId,
|
||||
username,
|
||||
email,
|
||||
}) => {
|
||||
const token = generateResetPasswordToken({ id: userId, username });
|
||||
|
||||
const url = `${BASE_URL}/users/reset-password?token=${token}`;
|
||||
|
||||
const component = ResetPasswordEmail({ name: username, url })! as ReactElement<
|
||||
unknown,
|
||||
string
|
||||
>;
|
||||
|
||||
const html = render(component);
|
||||
const text = render(component, { plainText: true });
|
||||
|
||||
await sendEmail({
|
||||
address: email,
|
||||
subject: 'Reset Password',
|
||||
html,
|
||||
text,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates a user to be confirmed by id.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to update.
|
||||
* @returns The user.
|
||||
*/
|
||||
export const confirmUserService: UpdateUserToBeConfirmedById = async ({ userId }) => {
|
||||
return DBClient.instance.user.update({
|
||||
where: { id: userId },
|
||||
data: { accountIsVerified: true, updatedAt: new Date() },
|
||||
select: userSelect,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateUserPasswordService: UpdateUserPassword = async ({
|
||||
password,
|
||||
userId,
|
||||
}) => {
|
||||
const hash = await hashPassword(password);
|
||||
|
||||
const user = await DBClient.instance.user.update({
|
||||
where: { id: userId },
|
||||
data: { hash, updatedAt: new Date() },
|
||||
select: authUserSelect,
|
||||
});
|
||||
|
||||
return user;
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates a user by id.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to update.
|
||||
* @param args.data The data to update the user with.
|
||||
* @param args.data.email The email of the user to update.
|
||||
* @param args.data.firstName The first name of the user to update.
|
||||
* @param args.data.lastName The last name of the user to update.
|
||||
* @param args.data.username The username of the user to update.
|
||||
*/
|
||||
export const updateUserService: UpdateUserById = async ({ userId, data }) => {
|
||||
const user = await DBClient.instance.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new ServerError('User not found', 404);
|
||||
}
|
||||
|
||||
const updatedFields = {
|
||||
email: data.email !== user.email,
|
||||
username: data.username !== user.username,
|
||||
firstName: data.firstName !== user.firstName,
|
||||
lastName: data.lastName !== user.lastName,
|
||||
} as const;
|
||||
|
||||
if (updatedFields.email) {
|
||||
const emailIsTaken = await findUserByEmailService({ email: data.email });
|
||||
if (emailIsTaken) {
|
||||
throw new ServerError('Email is already taken', 400);
|
||||
}
|
||||
|
||||
await sendConfirmationEmailService({
|
||||
userId,
|
||||
username: data.username,
|
||||
email: data.email,
|
||||
});
|
||||
}
|
||||
|
||||
if (updatedFields.username) {
|
||||
const usernameIsTaken = await findUserByUsernameService({ username: data.username });
|
||||
if (usernameIsTaken) {
|
||||
throw new ServerError('Username is already taken', 400);
|
||||
}
|
||||
}
|
||||
|
||||
const updatedUser = await DBClient.instance.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
email: updatedFields.email ? data.email : undefined,
|
||||
username: updatedFields.username ? data.username : undefined,
|
||||
firstName: updatedFields.firstName ? data.firstName : undefined,
|
||||
lastName: updatedFields.lastName ? data.lastName : undefined,
|
||||
accountIsVerified: updatedFields.email ? false : undefined,
|
||||
},
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
return updatedUser;
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
import { validateEmailRequest } from '@/requests/users/auth';
|
||||
import validateUsernameRequest from '@/requests/users/profile/validateUsernameRequest';
|
||||
import sub from 'date-fns/sub';
|
||||
import { z } from 'zod';
|
||||
|
||||
const MINIMUM_DATE_OF_BIRTH = sub(new Date(), { years: 19 });
|
||||
const NAME_REGEX =
|
||||
/^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ðæ ,.'-]+$/u;
|
||||
|
||||
export const BaseCreateUserSchema = z.object({
|
||||
password: z
|
||||
.string()
|
||||
.min(8, { message: 'Password must be at least 8 characters.' })
|
||||
.refine((password) => /[A-Z]/.test(password), {
|
||||
message: 'Password must contain at least one uppercase letter.',
|
||||
})
|
||||
.refine((password) => /[0-9]/.test(password), {
|
||||
message: 'Password must contain at least one number.',
|
||||
})
|
||||
.refine((password) => /[^a-zA-Z0-9]/.test(password), {
|
||||
message: 'Password must contain at least one special character.',
|
||||
}),
|
||||
confirmPassword: z.string(),
|
||||
firstName: z
|
||||
.string()
|
||||
.min(1, { message: 'First name must not be empty.' })
|
||||
.max(20, { message: 'First name must be less than 20 characters.' })
|
||||
.refine((firstName) => NAME_REGEX.test(firstName), {
|
||||
message: 'First name must only contain letters or hyphens.',
|
||||
}),
|
||||
lastName: z
|
||||
.string()
|
||||
.min(1, { message: 'Last name must not be empty.' })
|
||||
.max(20, { message: 'Last name must be less than 20 characters.' })
|
||||
.refine((lastName) => NAME_REGEX.test(lastName), {
|
||||
message: 'Last name must only contain letters.',
|
||||
}),
|
||||
dateOfBirth: z
|
||||
.string()
|
||||
.refine((val) => !Number.isNaN(Date.parse(val)), {
|
||||
message: 'Date is invalid.',
|
||||
})
|
||||
.refine((dateOfBirth) => new Date(dateOfBirth) <= MINIMUM_DATE_OF_BIRTH, {
|
||||
message: 'You must be at least 19 years old to register.',
|
||||
}),
|
||||
username: z
|
||||
.string()
|
||||
.min(1, { message: 'Username must not be empty.' })
|
||||
.max(20, { message: 'Username must be less than 20 characters.' }),
|
||||
email: z.string().email({ message: 'Email must be a valid email address.' }),
|
||||
});
|
||||
|
||||
export const CreateUserValidationSchema = BaseCreateUserSchema.refine(
|
||||
(data) => data.password === data.confirmPassword,
|
||||
{ message: 'Passwords do not match.', path: ['confirmPassword'] },
|
||||
);
|
||||
|
||||
export const CreateUserValidationSchemaWithUsernameAndEmailCheck =
|
||||
BaseCreateUserSchema.extend({
|
||||
email: z
|
||||
.string()
|
||||
.email({ message: 'Email must be a valid email address.' })
|
||||
.refine(async (email) => validateEmailRequest({ email }), {
|
||||
message: 'Email is already taken.',
|
||||
}),
|
||||
username: z
|
||||
.string()
|
||||
.min(1, { message: 'Username must not be empty.' })
|
||||
.max(20, { message: 'Username must be less than 20 characters.' })
|
||||
.refine(async (username) => validateUsernameRequest(username), {
|
||||
message: 'Username is already taken.',
|
||||
}),
|
||||
}).refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Passwords do not match.',
|
||||
path: ['confirmPassword'],
|
||||
});
|
||||
|
||||
export const UpdatePasswordSchema = BaseCreateUserSchema.pick({
|
||||
password: true,
|
||||
confirmPassword: true,
|
||||
}).refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Passwords do not match.',
|
||||
path: ['confirmPassword'],
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { BaseCreateUserSchema } from './CreateUserValidationSchemas';
|
||||
|
||||
const EditUserSchema = BaseCreateUserSchema.pick({
|
||||
username: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
});
|
||||
|
||||
export default EditUserSchema;
|
||||
@@ -0,0 +1,19 @@
|
||||
import ImageQueryValidationSchema from '@/services/schema/ImageSchema/ImageQueryValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
const GetUserSchema = z.object({
|
||||
id: z.string().cuid(),
|
||||
username: z.string(),
|
||||
createdAt: z.coerce.date(),
|
||||
updatedAt: z.coerce.date().nullable(),
|
||||
email: z.string().email(),
|
||||
firstName: z.string(),
|
||||
lastName: z.string(),
|
||||
dateOfBirth: z.coerce.date(),
|
||||
accountIsVerified: z.boolean(),
|
||||
role: z.enum(['USER', 'ADMIN']),
|
||||
bio: z.string().nullable(),
|
||||
userAvatar: ImageQueryValidationSchema.nullable(),
|
||||
});
|
||||
|
||||
export default GetUserSchema;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const LoginValidationSchema = z.object({
|
||||
username: z
|
||||
.string({
|
||||
required_error: 'Username is required.',
|
||||
invalid_type_error: 'Username must be a string.',
|
||||
})
|
||||
.min(1, { message: 'Username is required.' }),
|
||||
password: z
|
||||
.string({
|
||||
required_error: 'Password is required.',
|
||||
invalid_type_error: 'Password must be a string.',
|
||||
})
|
||||
.min(1, { message: 'Password is required.' }),
|
||||
});
|
||||
|
||||
export default LoginValidationSchema;
|
||||
@@ -0,0 +1,7 @@
|
||||
import z from 'zod';
|
||||
|
||||
const TokenValidationSchema = z.object({
|
||||
token: z.string(),
|
||||
});
|
||||
|
||||
export default TokenValidationSchema;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const UpdateProfileSchema = z.object({
|
||||
bio: z.string(),
|
||||
userAvatar: z
|
||||
.instanceof(typeof FileList !== 'undefined' ? FileList : Object)
|
||||
.refine((fileList) => fileList instanceof FileList, {
|
||||
message: 'You must submit this form in a web browser.',
|
||||
})
|
||||
.refine((fileList) => [...(fileList as FileList)].length <= 1, {
|
||||
message: 'You must upload only one or zero files.',
|
||||
})
|
||||
.refine(
|
||||
(fileList) =>
|
||||
[...(fileList as FileList)]
|
||||
.map((file) => file.type)
|
||||
.every((fileType) => fileType.startsWith('image/')),
|
||||
{ message: 'You must upload only images.' },
|
||||
)
|
||||
.refine(
|
||||
(fileList) =>
|
||||
[...(fileList as FileList)]
|
||||
.map((file) => file.size)
|
||||
.every((fileSize) => fileSize < 15 * 1024 * 1024),
|
||||
{ message: 'You must upload images smaller than 15MB.' },
|
||||
),
|
||||
});
|
||||
|
||||
export default UpdateProfileSchema;
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from 'zod';
|
||||
import GetUserSchema from '../schema/GetUserSchema';
|
||||
import { CreateUserValidationSchema } from '../schema/CreateUserValidationSchemas';
|
||||
|
||||
type User = z.infer<typeof GetUserSchema>;
|
||||
type AuthUser = { username: string; hash: string; id: string };
|
||||
|
||||
export type CreateNewUser = (
|
||||
args: z.infer<typeof CreateUserValidationSchema>,
|
||||
) => Promise<User>;
|
||||
|
||||
export type DeleteUserById = (args: { userId: string }) => Promise<AuthUser | null>;
|
||||
|
||||
export type FindUserById = (args: { userId: string }) => Promise<User | null>;
|
||||
|
||||
export type FindUserByUsername = (args: { username: string }) => Promise<AuthUser | null>;
|
||||
|
||||
export type FindUserByEmail = (args: { email: string }) => Promise<User | null>;
|
||||
|
||||
export type UpdateUserPassword = (args: {
|
||||
userId: string;
|
||||
password: string;
|
||||
}) => Promise<AuthUser | null>;
|
||||
|
||||
export type SendConfirmationEmail = (args: {
|
||||
userId: string;
|
||||
username: string;
|
||||
email: string;
|
||||
}) => Promise<void>;
|
||||
|
||||
export type SendResetPasswordEmail = (args: {
|
||||
userId: string;
|
||||
username: string;
|
||||
email: string;
|
||||
}) => Promise<void>;
|
||||
|
||||
export type UpdateUserToBeConfirmedById = (args: { userId: string }) => Promise<User>;
|
||||
|
||||
export type UpdateUserById = (args: {
|
||||
userId: string;
|
||||
data: {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
username: string;
|
||||
};
|
||||
}) => Promise<User>;
|
||||
193
archive/next-js-web-app/src/services/users/profile/index.ts
Normal file
193
archive/next-js-web-app/src/services/users/profile/index.ts
Normal file
@@ -0,0 +1,193 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import {
|
||||
GetUsersFollowedByOrFollowingUser,
|
||||
UpdateUserAvatar,
|
||||
UpdateUserProfileById,
|
||||
UserFollowService,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The select object for retrieving users.
|
||||
*
|
||||
* Satisfies the GetUserSchema zod schema.
|
||||
*
|
||||
* @example
|
||||
* const users = await DBClient.instance.user.findMany({
|
||||
* select: userSelect,
|
||||
* });
|
||||
*/
|
||||
const userSelect = {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
dateOfBirth: true,
|
||||
createdAt: true,
|
||||
accountIsVerified: true,
|
||||
updatedAt: true,
|
||||
role: true,
|
||||
userAvatar: true,
|
||||
bio: true,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Finds a user follow by the followerId and followingId.
|
||||
*
|
||||
* @returns The user follow if found, otherwise null.
|
||||
*/
|
||||
export const findUserFollow: UserFollowService = ({ followerId, followingId }) => {
|
||||
return DBClient.instance.userFollow.findFirst({ where: { followerId, followingId } });
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new user follow.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.followerId The follower id of the user follow to create.
|
||||
* @param args.followingId The following id of the user follow to create.
|
||||
* @returns The user follow.
|
||||
*/
|
||||
export const createUserFollow: UserFollowService = ({ followerId, followingId }) => {
|
||||
return DBClient.instance.userFollow.create({ data: { followerId, followingId } });
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a user follow.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.followerId The follower id of the user follow to delete.
|
||||
* @param args.followingId The following id of the user follow to delete.
|
||||
* @returns The user follow.
|
||||
*/
|
||||
export const deleteUserFollow: UserFollowService = ({ followerId, followingId }) => {
|
||||
return DBClient.instance.userFollow.delete({
|
||||
where: { followerId_followingId: { followerId, followingId } },
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the users followed by the session user.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to check if followed by the session user.
|
||||
* @param args.pageNum The page number of the users to retrieve.
|
||||
* @param args.pageSize The page size of the users to retrieve.
|
||||
* @returns The users followed by the queried user and the count of users followed by the
|
||||
* queried user.
|
||||
*/
|
||||
export const getUsersFollowedByUser: GetUsersFollowedByOrFollowingUser = async ({
|
||||
userId,
|
||||
pageNum,
|
||||
pageSize,
|
||||
}) => {
|
||||
const usersFollowedByQueriedUser = await DBClient.instance.userFollow.findMany({
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
where: { follower: { id: userId } },
|
||||
select: {
|
||||
follower: { select: { username: true, userAvatar: true, id: true } },
|
||||
},
|
||||
});
|
||||
const count = await DBClient.instance.userFollow.count({
|
||||
where: { follower: { id: userId } },
|
||||
});
|
||||
const follows = usersFollowedByQueriedUser.map((u) => u.follower);
|
||||
|
||||
return { follows, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the users following the session user.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to check if followed by the session user.
|
||||
* @param args.pageNum The page number of the users to retrieve.
|
||||
* @param args.pageSize The page size of the users to retrieve.
|
||||
*/
|
||||
export const getUsersFollowingUser: GetUsersFollowedByOrFollowingUser = async ({
|
||||
userId,
|
||||
pageNum,
|
||||
pageSize,
|
||||
}) => {
|
||||
const usersFollowingQueriedUser = await DBClient.instance.userFollow.findMany({
|
||||
take: pageSize,
|
||||
skip: (pageNum - 1) * pageSize,
|
||||
where: { following: { id: userId } },
|
||||
select: {
|
||||
following: { select: { username: true, userAvatar: true, id: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const count = await DBClient.instance.userFollow.count({
|
||||
where: { following: { id: userId } },
|
||||
});
|
||||
|
||||
const follows = usersFollowingQueriedUser.map((u) => u.following);
|
||||
return { follows, count };
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the user avatar of the user.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to update the avatar of.
|
||||
* @param args.data The data to update the user avatar with.
|
||||
* @param args.data.alt The alt text of the user avatar.
|
||||
* @param args.data.path The path of the user avatar.
|
||||
* @param args.data.caption The caption of the user avatar.
|
||||
* @returns The updated user.
|
||||
*/
|
||||
export const updateUserAvatar: UpdateUserAvatar = async ({ userId, data }) => {
|
||||
const user = await DBClient.instance.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new ServerError('User not found', 404);
|
||||
}
|
||||
|
||||
const updatedUser = await DBClient.instance.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
userAvatar: {
|
||||
upsert: {
|
||||
create: {
|
||||
alt: data.alt,
|
||||
path: data.path,
|
||||
caption: data.caption,
|
||||
},
|
||||
update: {
|
||||
alt: data.alt,
|
||||
path: data.path,
|
||||
caption: data.caption,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
return updatedUser;
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates a user's profile by id.
|
||||
*
|
||||
* @param args The arguments for service.
|
||||
* @param args.userId The id of the user to update.
|
||||
* @param args.data The data to update the user with.
|
||||
* @param args.data.bio The bio of the user.
|
||||
* @returns The user.
|
||||
*/
|
||||
export const updateUserProfileById: UpdateUserProfileById = async ({ userId, data }) => {
|
||||
const user = await DBClient.instance.user.update({
|
||||
where: { id: userId },
|
||||
data: { bio: data.bio },
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
return user;
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import GetUserSchema from '@/services/users/auth/schema/GetUserSchema';
|
||||
|
||||
const FollowInfoSchema = GetUserSchema.pick({
|
||||
userAvatar: true,
|
||||
id: true,
|
||||
username: true,
|
||||
});
|
||||
|
||||
export default FollowInfoSchema;
|
||||
@@ -0,0 +1,38 @@
|
||||
import { UserFollow } from '@prisma/client';
|
||||
import { z } from 'zod';
|
||||
|
||||
import FollowInfoSchema from '../schema/FollowInfoSchema';
|
||||
import GetUserSchema from '../../auth/schema/GetUserSchema';
|
||||
|
||||
type FollowInfo = z.infer<typeof FollowInfoSchema>;
|
||||
type User = z.infer<typeof GetUserSchema>;
|
||||
|
||||
export type UserFollowService = (args: {
|
||||
followerId: string;
|
||||
followingId: string;
|
||||
}) => Promise<UserFollow | null>;
|
||||
|
||||
export type UpdateUserProfileById = (args: {
|
||||
userId: string;
|
||||
data: { bio: string };
|
||||
}) => Promise<User>;
|
||||
|
||||
export type CheckIfUserIsFollowedBySessionUser = (args: {
|
||||
followerId: string;
|
||||
followingId: string;
|
||||
}) => Promise<boolean>;
|
||||
|
||||
export type GetUsersFollowedByOrFollowingUser = (args: {
|
||||
userId: string;
|
||||
pageNum: number;
|
||||
pageSize: number;
|
||||
}) => Promise<{ follows: FollowInfo[]; count: number }>;
|
||||
|
||||
export type UpdateUserAvatar = (args: {
|
||||
userId: string;
|
||||
data: {
|
||||
alt: string;
|
||||
path: string;
|
||||
caption: string;
|
||||
};
|
||||
}) => Promise<User>;
|
||||
Reference in New Issue
Block a user