Skip to content

Commit

Permalink
Merge pull request #215 from Roger13579/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
Roger13579 authored Jun 13, 2024
2 parents de64cbd + 3b42406 commit d12c336
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
1 change: 0 additions & 1 deletion src/dto/cart/editCartDto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export class EditCartDTO {
this._userId = (user as IUser)._id;
this._products = products.map((product) => ({
...product,
productId: new Types.ObjectId(product.productId),
}));
}
}
42 changes: 32 additions & 10 deletions src/validator/cart/deleteCart.pipe.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,53 @@
import { body } from 'express-validator';
import { PipeBase } from '../pipe.base';
import { CustomResponseType } from '../../types/customResponseType';
import { DeleteCartType, IDeleteCartReq } from '../../types/cart.type';
import {
DeleteCartType,
ICartProduct,
IDeleteCartReq,
} from '../../types/cart.type';
import { TCustomValidator } from '../index.type';
import { IPlan } from '../../types/product.type';

export class DeleteCartPipe extends PipeBase {
private validateProductIds: TCustomValidator<unknown> = (value, { req }) => {
private validateProducts: TCustomValidator<unknown> = (value, { req }) => {
const { type } = (req as IDeleteCartReq).body;

const isClearAll = type === DeleteCartType.all && !value;
const isProductsStrArr =
Array.isArray(value) && value.every((item) => typeof item === 'string');
const isClearItems = type === DeleteCartType.items && isProductsStrArr;
const requiredFields: (keyof ICartProduct)[] = ['productId', 'plan'];
const requiredPlan: (keyof IPlan)[] = ['name', 'discount', 'headCount'];
const isProductsArr =
Array.isArray(value) &&
value.every((item) =>
this.allRequiredFieldsHaveValues(item, requiredFields),
) &&
value.every((item) =>
this.allRequiredFieldsHaveValues(item.plan, requiredPlan),
);
const isClearItems = type === DeleteCartType.items && isProductsArr;

return isClearAll || isClearItems;
};

private allRequiredFieldsHaveValues<T extends object>(
obj: T,
requiredFields: (keyof T)[],
): boolean {
return requiredFields.every(
(field) =>
Object.values(obj) !== null &&
obj[field] !== undefined &&
obj[field] !== '',
);
}
public transform = () => [
body('type')
.exists()
.isIn(Object.keys(DeleteCartType))
.withMessage(CustomResponseType.INVALID_DELETE_CART_MESSAGE + 'type'),
body('productIds')
.custom(this.validateProductIds)
.withMessage(
CustomResponseType.INVALID_DELETE_CART_MESSAGE + 'productIds',
),
body('products')
.custom(this.validateProducts)
.withMessage(CustomResponseType.INVALID_DELETE_CART_MESSAGE + 'products'),
this.validationHandler,
];
constructor() {
Expand Down

0 comments on commit d12c336

Please sign in to comment.