Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ig 130 #136

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 9 additions & 33 deletions api/controllers/product.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,14 @@ import { TypeOf } from "zod";
import {
CreateProductInput,
createProductSchema,
deleteProductSchema,
getProductSchema,
updateProductSchema,
} from "../schemaValidators/product.schema";
import {
createProduct,
deleteProduct,
findAndUpdateProduct,
findProduct,
findProducts,
buyProducts,
} from "../services/product.service";
import { createProduct, deleteProduct, findAndUpdateProduct, findProduct, findProducts, buyProducts } from "../services/product.service";

// get product/
export async function getAllProductsHandler(
req: Request<{}, {}, CreateProductInput["body"]>,
res: Response,
next: any
) {
export async function getAllProductsHandler(req: Request<{}, {}, CreateProductInput["body"]>, res: Response, next: any) {
try {
const products = await findProducts({});
if (!products) {
Expand All @@ -32,12 +24,7 @@ export async function getAllProductsHandler(

// get product/:id

export async function getSingleProductHandler(
// TODO update request so it looks similar to createProductHandler
req: Request,
res: Response,
next: any
) {
export async function getSingleProductHandler(req: Request<{}, {}, TypeOf<typeof getProductSchema>>, res: Response, next: any) {
const id = req.params.id;
try {
const product = await findProduct({ id });
Expand All @@ -51,10 +38,7 @@ export async function getSingleProductHandler(
}

// post product/
export async function createProductHandler(
req: Request<{}, {}, TypeOf<typeof createProductSchema>>,
res: Response
) {
export async function createProductHandler(req: Request<{}, {}, TypeOf<typeof createProductSchema>>, res: Response) {
const body = req.body.body;
// const product = await createProduct(...body);
// return res.send(product);
Expand All @@ -63,11 +47,7 @@ export async function createProductHandler(

// patch product/:id

export async function updateSingleProductHandler(
// TODO update request so it looks similar to createProductHandler
req: Request,
res: Response
) {
export async function updateSingleProductHandler(req: Request<{}, {}, TypeOf<typeof updateProductSchema>>, res: Response) {
const body = req.body;
const id = req.params.id;
const product = await findProduct({ id });
Expand All @@ -84,11 +64,7 @@ export async function updateSingleProductHandler(
}

// delete product/:id
export async function deleteProductHandler(
// TODO update request so it looks similar to createProductHandler
req: Request,
res: Response
) {
export async function deleteProductHandler(req: Request<{}, {}, TypeOf<typeof deleteProductSchema>>, res: Response) {
const id = req.params.id;
const product = await findProduct({ id });
if (!product) {
Expand Down
63 changes: 33 additions & 30 deletions api/schemaValidators/product.schema.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,42 @@
import { z, number, object, string, TypeOf } from "zod";

const payload = {
body: z.object({
name: string({
required_error: 'Name is required'
}),
price: number({
required_error: 'Price is required'
}),
sportType: string({
required_error: 'Sport type is required'
}),
productCategory: string({
required_error: 'Product Category is required'
}),
brand: string({
required_error: 'Brand is required'
})
})
}
body: z.object({
name: string({
required_error: "Name is required",
}),
price: number({
required_error: "Price is required",
}),
sportType: string({
required_error: "Sport type is required",
}),
productCategory: string({
required_error: "Product Category is required",
}),
brand: string({
required_error: "Brand is required",
}),
id: string({
required_error: "Id is required",
}),
}),
};

const payloadUpdateSchema = {
body: z.object({
name: string(),
price: number(),
sportType: string(),
productCategory: string(),
brand: string(),
description: string(),
img: string(),
}).partial()}
body: z
.object({
name: string(),
price: number(),
sportType: string(),
productCategory: string(),
brand: string(),
description: string(),
img: string(),
})
.partial(),
};

// TODO
// ADD A WAY TO REQUIRE OBJECTID IN REQUEST PARAMS


export const createProductSchema = object({...payload})
export const updateProductSchema = object({...payloadUpdateSchema})
Expand Down
23 changes: 15 additions & 8 deletions web/src/components/pages/Login/component.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ChangeEvent, useState } from 'react';
import { ChangeEvent, useState, useContext } from 'react';
import { Link, useNavigate } from 'react-router-dom';

import { RoutePaths } from '../../../models';
import { NotificationMode, RoutePaths } from '../../../models';
import { User } from '../../../models/user';
import { Api } from '../../../Api';
import { USER_TOKEN } from '../../../constants';
Expand All @@ -10,11 +10,15 @@ import { setLocalStorage } from '../../../utils/localStorage';
import { Form, FormInput } from '../../shared';

import './style.css';
import { saveUserDataAction } from '../../../services/actions/userActions';
import { useDispatch } from 'react-redux';
import { NotificationContext } from '../../../contexts';

export const LoginPage = (): JSX.Element => {
export const LoginPage = (): any => {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dont have to set return type here

const [form, setForm] = useState(new User());
const [errors, setErrors] = useState(new User());
const [isLoading, setIsLoading] = useState(false);
const { addNotification } = useContext(NotificationContext);

const handleChange = (e: ChangeEvent<{ value: string; name: string }>) => {
const { name, value } = e.target;
Expand Down Expand Up @@ -42,17 +46,20 @@ export const LoginPage = (): JSX.Element => {
let navigate = useNavigate();

const api = new Api();
const dispatch = useDispatch();

const login = async () => {
setIsLoading(true);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why remove?

try {
// TODO save user data to reducer
const userData = (await api.post('url..', form)) as User;
const userData = (await api.post('/login', form)) as User;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wrong url, its /auth/login

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use generic types for POST
we want to declare with post requset will return

//
post method in api class should return Promise

setLocalStorage(USER_TOKEN, userData.token);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

token doesnt exist in userData. its different (check response)

dispatch(saveUserDataAction(form));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we want to store userData that comes from api (check api response). not form. PASSWORD and token cannot be stored here :p

navigate(RoutePaths.MainPage);
} catch (error: any) {
// TODO display notification from context
console.log(error?.response.data || error?.response.status);
return addNotification({
mode: NotificationMode.INFO,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why INFO when its an error?

title: 'Login',
message: error,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think its error.message

});
} finally {
setIsLoading(false);
}
Expand Down
20 changes: 14 additions & 6 deletions web/src/components/pages/Register/component.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,43 @@
import React, { ChangeEvent, useState } from 'react';
import React, { ChangeEvent, useContext, useState } from 'react';

import { Form, FormInput } from '../../shared';

import { Api } from '../../../Api';
import { useNavigate } from 'react-router-dom';
import { RoutePaths, User } from '../../../models';
import { NotificationMode, RoutePaths, User } from '../../../models';

import { USER_TOKEN } from '../../../constants';
import { setLocalStorage } from '../../../utils/localStorage';

import './style.css';
import { saveUserDataAction } from '../../../services/actions/userActions';
import { useDispatch } from 'react-redux';
import { NotificationContext } from '../../../contexts';

export const RegisterPage = (): JSX.Element => {
const [errors, setErrors] = useState(new User());
const [form, setForm] = useState(new User());
const [isLoading, setLoading] = useState(false);
const { addNotification } = useContext(NotificationContext);

const navigate = useNavigate();

const api = new Api();
const dispatch = useDispatch();

async function register() {
setLoading(true);
try {
// TODO save user data to reducer
const userData = (await api.post('url...', form)) as User;
const userData = (await api.post('/register', form)) as User;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check login component comments and fix ALL register

setLocalStorage(USER_TOKEN, userData.token);
dispatch(saveUserDataAction(form));
navigate(RoutePaths.MainPage);
} catch (error: any) {
// TODO display notification from context
console.log(error?.response.data || error?.response.status);
return addNotification({
mode: NotificationMode.INFO,
title: 'Register',
message: error,
});
} finally {
setLoading(false);
}
Expand Down
1 change: 1 addition & 0 deletions web/src/components/shared/Form/FormInput/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ interface Props {
name: string;
id?: string;
className?: string;
value?: any;
type?: 'text' | 'button' | 'checkbox' | 'password' | 'email';
placeholder?: string;
onChange: (e: any) => void;
Expand Down
16 changes: 5 additions & 11 deletions web/src/services/actions/userActions.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { User } from '../../models/user';

export const ADD_USER = 'ADD_USER';
export const REMOVE_USER = 'REMOVE_USER';
export const SAVE_USER_DATA = 'SAVE_USER_DATA';

export const addUser = (value: User) => {
export const saveUserDataAction = (user: User) => {
return {
type: ADD_USER,
payload: value,
type: SAVE_USER_DATA,
payload: user,
};
};

export const removeUser = (value: User) => {
return {
type: REMOVE_USER,
payload: value,
};
};

4 changes: 3 additions & 1 deletion web/src/services/reducers/combineReducers.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { combineReducers } from 'redux';
import { cartReducer as cart } from './cart.reducer';
import { pageResourceReducer as pageResource } from './page-resource.reducer';
import { userReducer as user } from './user.reducer';

export default combineReducers({
cart,
pageResource
pageResource,
user,
});
13 changes: 13 additions & 0 deletions web/src/services/reducers/user.reducer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { User } from '../../models/user';
import { SAVE_USER_DATA } from '../actions/userActions';

const initUserState: User = new User();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we dont want initUserState. or if you want to just empty object


export function userReducer(state = initUserState, action: any): User {
switch (action.type) {
case SAVE_USER_DATA:
return { ...state, ...action.payload };
default:
return state;
}
}
30 changes: 0 additions & 30 deletions web/src/services/reducers/userReducer.ts

This file was deleted.