karim-test README
F
cart
let [products, setProduct] = useState([])
let navigation = useNavigate()
useEffect(() => {
req_cart()
}, [])
function req_cart() {
Fetch('cart')
.then(r => {
setProduct(r.data.reduce((acc, obj) => {
let found = acc.find(a => a.product_id == obj.product_id)
if (found) {
found.count++;
} else {
acc.push({...obj, count: 1})
}
return acc
}, []))
})
}
function add_(id) {
setProduct(products.map(p => {
if (p.id == id) {
return {...p, count: p.count+1}
} else {
return p
}
}))
}
function minus(id) {
setProduct(products.map(p => {
if (p.id == id) {
if (p.count - 1 <= 0) {
return p
} else {
return {...p, count: p.count - 1}
}
} else {
return p
}
}))
}
function dele(id) {
Fetch('products')
.then(r => {
for (let i of r.data){
if (i.id == id) {
Fetch(`cart/${id}`, 'DELETE')
.then(() => {
req_cart()
})
}
}
})
}
let count_s = 0
products.map(p => count_s += p.count * p.price)
Registration
let [email, setEmail] = useState('')
let [password, setPassword] = useState('')
let [name, setName] = useState('')
let [errorEmail, setErrorEmail] = useState('')
let [errorPassword, setErrorPassword] = useState('')
let [errorName, setErrorName] = useState('')
let navigate = useNavigate()
function reg() {
Fetch('signup', 'POST', {
password: password, email: email, fio: name
})
.then(r => {
setErrorEmail(r.error?.errors?.email)
setErrorPassword(r.error?.errors?.password)
setErrorName(r.error?.errors?.fio)
if (!r.error) {
navigate('/log')
}
})
}
F
async function Fetch(url_dop, method='GET', body=null) {
let url = 'http://api-shop.alabuga.space/api-shop/' + url_dop
let token = localStorage.getItem('token')
console.log(method)
let data = await fetch(
url, {
headers: {
'Content-type': 'application/json',
'Authorization': token ? `Bearer ${token}` : ''
},
body: body && JSON.stringify(body),
method: method
}
)
return await data.json()
}
export default Fetch
Order
let product = products.find(item => item.id == products_id)
B
setting
AUTH_USER_MODEL = 'App.UserCustom'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'App.Auth.BearerToken',
),
'EXCEPTION_HANDLER': 'App.utils.exception_handler_custom',
}
Cart
class CartApi(APIView):
permission_classes = [IsAuthenticatedNotAdmin]
def get(self, request):
cart, _ = Cart.objects.get_or_create(user=request.user)
products = ProductSerializer(cart.products.all(), many=True).data
for i, product in enumerate(products):
product['product_id'] = product['id']
product['id'] = i + 1
return JsonResponse({
'data': products
}, status=200)
def post(self, request, pk):
product = get_object_or_404(Product.objects.all(), id=pk)
cart, _ = Cart.objects.get_or_create(user=request.user)
cart.products.add(product)
return JsonResponse({
'data': {
'message': 'Product added',
'product_id': product.id
}
})
def delete(self, request, pk):
cart, _ = Cart.objects.get_or_create(user=request.user)
products = ProductSerializer(cart.products.all(), many=True).data
id_delete = None
for i, product in enumerate(products):
if i + 1 == pk:
id_delete = product['id']
product['product_id'] = product['id']
product['id'] = i + 1
if id_delete is None:
return JsonResponse({
'error': {
'code': 403,
'message': 'Forbidden for you'
}
}, status=403)
product = Product.objects.get(id=id_delete)
cart.products.remove(product)
return JsonResponse({
'data': {
'message': 'Product removed from cart'
}
}, status=200)
Order
class OrderApi(APIView):
permission_classes = [IsAuthenticatedNotAdmin]
def get(self, request):
orders = Order.objects.filter(user=request.user)
serializer = OrderSerializer(orders, many=True)
return JsonResponse({
'data': serializer.data
}, status=200)
def post(self, request):
cart, _ = Cart.objects.get_or_create(user=request.user)
products = cart.products.all()
if not products:
return JsonResponse({
'error': {
'code': 422,
'message': 'Cart is empty'
}
}, status=422)
order_price = sum(map(lambda x: x.price, products))
order = Order.objects.create(user=request.user, order_price=order_price)
order.products.add(*products)
cart.products.clear()
return JsonResponse({
'data': {
'message': 'Orer created',
'order_id': order.id
}
}, status=201)
Next
class RegistrationApi(APIView):
def post(self, request):
serializer = RegistrSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
token = Token.objects.create(user=user)
return JsonResponse({
'data': {
'user_token': token.key
}
}, status=201)
class LoginApi(APIView):
def post(self, request):
serializer = LoginSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
if not user:
return JsonResponse({
'error': {
'code': 401,
'message': 'Authenticate failed'
}
}, status=401)
token, _ = Token.objects.get_or_create(user=user)
return JsonResponse({
'data': {
'user_token': token.key
}
}, status=200)
class Logout(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
request.user.auth_token.delete()
return JsonResponse({
'data': {
'message': 'logout'
}
}, status=200)
Serializer
class RegistrSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = UserCustom
def save(self, **kwargs):
user = UserCustom(
fio=self.validated_data['fio'],
email=self.validated_data['email']
)
user.set_password(self.validated_data['password'])
user.save()
return user
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField()
def validate(self, attrs):
user = authenticate(**attrs)
return user or False