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

Antti/json server #4

Merged
merged 49 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
dad603e
Created a json-server folder. Created a few API tests inside pages fo…
Sep 29, 2023
5af593c
More tests in pages/api and with the json-server
Sep 30, 2023
574b0fa
Merged from Antin-dev
Oct 11, 2023
bad94e3
CSS and json-server tests
Oct 11, 2023
ba91e39
Merged from antti/modal
Nov 1, 2023
d19d5a3
Refactoring index.tsx. Renamed fetchFunctions.tsx to jsonServerFuncti…
Nov 1, 2023
727d27d
Refactoring index.tsx. Cleared the json-server's 'database'. Added a …
Nov 1, 2023
adf6e8e
Refactoring index.tsx and DeleteModal.tsx. Site now loads gifts from …
Nov 9, 2023
ed20f50
Refactoring jsonServerFunctions.ts. Changed the way how getOne functi…
Nov 9, 2023
8b35517
Added remove function to jsonServerFunctions.ts
Nov 9, 2023
f65ba75
Refactoring DeleteModal.tsx
Nov 9, 2023
390648a
Refactoring index.tsx, added more Tailwind animation tests
Nov 9, 2023
b59bc32
Did an ESLint check and fix. Deleted the api folder inside the pages …
Nov 9, 2023
2602e90
Fixed errors ESLint gave. Changed giftListRefrechFunction's return to…
Nov 10, 2023
742f7bb
Created an useState for info modal to tell if the gift was deleted al…
Nov 10, 2023
e722466
Added opacity for Modal to look like it is focused
Nov 28, 2023
53258f0
Added a check if the gift wanted to be deleted exist still in json-se…
Nov 28, 2023
7640b76
Merged from antti/modal to antti/json-server
Dec 18, 2023
b830873
ESLint fixes. Deleted a few type checks that were not needed
Dec 18, 2023
7c4c5ed
Fixed couple promise-returning errors ESLint gave. Changed couple con…
Dec 18, 2023
0ee36ba
Changed db.json to have a real name instead of tests
Dec 19, 2023
4777315
Fixed typos in jsonServerFunctions.ts
Dec 19, 2023
808334a
Moved db.json file to root folder for Vercel's json-server host. Dele…
Dec 21, 2023
417109e
Changed FullLocalStorage type to Gifts_Type to be more clarifying
Jan 8, 2024
5298332
Revert "Changed FullLocalStorage type to Gifts_Type to be more clarif…
Jan 8, 2024
ddeccfc
Changed FullLocalStorage type to Gifts to be more clarifying
Jan 8, 2024
2dfcc78
Changed the way how getAll returns its data. Changed variables types …
Jan 8, 2024
0c6fb70
Changed getOne function to take only ID as a parameter. Changed JSDoc…
Jan 8, 2024
4abe5fa
Changed JSDoc and the way how Update function works in jsonServerFunc…
Jan 8, 2024
54c6bf0
Removed export default when exporting functions in jsonServerFunction…
Jan 8, 2024
5772267
Changed jsonServerFunctions to have gift in their name to make more c…
Jan 9, 2024
33a8c68
Modified JSDoc documentations and added types for return statements i…
Jan 9, 2024
ad30587
Changed module name from create to createGift in index.tsx to make it…
Jan 9, 2024
aabb832
Changed Container component to div element due to no difference
Jan 9, 2024
c498eaa
Deleted Container component due to no usage
Jan 9, 2024
fa7b9ff
Changed fetchData -> fetchGifts. Changed catch function to console.er…
Jan 9, 2024
8bdda47
Changed removeGift's argument to not have template literals in Delete…
Jan 9, 2024
355c0d0
ESLint fixes
Jan 9, 2024
6b4537b
Added "prepush" script to package.json
anttiasmala Jan 9, 2024
d085fc0
Added URLs for localhost and for externals. Localhost url is commente…
anttiasmala Jan 9, 2024
49ad5e8
Changed surname Virtanen to Meikäläinen to be correct placeholder name
anttiasmala Jan 9, 2024
57cdd77
Fixed JSDoc faulty documentation in jsonServerFunctions.ts. Fixed upd…
anttiasmala Jan 12, 2024
01b7d23
Changed Gifts type to Gift
anttiasmala Jan 20, 2024
43138e8
Deleted isGiftDeletedAlreadyType due to no usage
anttiasmala Jan 20, 2024
9f4f6b1
Changed inquality check to strict inequality and getGift function now…
anttiasmala Jan 20, 2024
1247c5f
Merged main branch to antti/json-server branch
anttiasmala Jan 21, 2024
8f179a7
Renamed accept_button_icon.tsx to CheckMarkIcon.tsx
anttiasmala Jan 22, 2024
cca673d
Deleted icons/index.ts due to no usage currently. Changed the way how…
anttiasmala Jan 22, 2024
83311cf
ESLint fixes
anttiasmala Jan 23, 2024
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
8 changes: 0 additions & 8 deletions components/Container.tsx

This file was deleted.

16 changes: 6 additions & 10 deletions components/DeleteModal.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { TitleText } from './TitleText';
import React, { Dispatch, SetStateAction } from 'react';
import { FullLocalStorage } from '~/pages';
import { Gifts } from '~/pages';
import { Modal } from './Modal';
import jsonServerFunctions from '~/utils/jsonServerFunctions';
import SvgAcceptButtonIcon from '~/icons/accept_button_icon';
import SvgDeclineButtonIcon from '~/icons/decline_button_icon';
import { Button } from './Button';
import { getGift, removeGift } from '~/utils/jsonServerFunctions';

type ModalType = {
gift: FullLocalStorage;
gift: Gifts;
giftListRefreshFunction: () => void;
setIsModalOpen: Dispatch<SetStateAction<boolean>>;
};
Expand All @@ -19,13 +19,9 @@ export function DeleteModal({
setIsModalOpen,
}: ModalType) {
async function handleDeletion() {
const giftToBeDeleted: any[] = await jsonServerFunctions.getOne(
`id=${gift.id}`,
);
if (giftToBeDeleted.length != 0) {
await jsonServerFunctions
.remove(`${gift.id}`)
.catch(() => giftListRefreshFunction());
const giftToBeDeleted = await getGift(gift.id);
if (giftToBeDeleted !== null) {
await removeGift(gift.id);
}
giftListRefreshFunction();
setIsModalOpen(false);
Expand Down
5 changes: 2 additions & 3 deletions components/InfoModal.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Container } from './Container';
import { Modal } from './Modal';
import { TitleText } from './TitleText';

Expand All @@ -9,7 +8,7 @@ type InfoModalType = {

export function InfoModal({ title, info }: InfoModalType) {
return (
<Container>
<div>
<Modal>
<TitleText className="row-start-1 row-end-1 ps-5 font-bold">
{title}
Expand All @@ -18,6 +17,6 @@ export function InfoModal({ title, info }: InfoModalType) {
{info}
</p>
</Modal>
</Container>
</div>
);
}
2 changes: 1 addition & 1 deletion db.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"gifts": [
{
"name": "Matti Virtanen",
"name": "Matti Meikäläinen",
"gift": "Kortti",
"id": "ad674e17-6643-423f-8517-70fbd3ec1df8",
"createdDate": 1702975113280
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"lint": "(next lint || true) && npm run check-types",
"lint:fix": "next lint --fix",
"start-json-server": "json-server -p3001 --watch db.json",
"prepush": "next lint --max-warnings=0 && npm run check-types",
"svgr": "svgr --out-dir icons --typescript --jsx-runtime automatic --no-dimensions --silent --filename-case snake -- public/images/icons"
},
"dependencies": {
Expand Down
30 changes: 14 additions & 16 deletions pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { Button } from '~/components/Button';
import { TitleText } from '~/components/TitleText';
import { Input } from '../components/Input';
import { DeleteModal } from '~/components/DeleteModal';
import jsonServerFunctions from '~/utils/jsonServerFunctions';
import { createGift, getAllGifts } from '~/utils/jsonServerFunctions';

const inter = Inter({ subsets: ['latin'] });

export type FullLocalStorage = {
export type Gifts = {
name: string;
gift: string;
id: string;
Expand All @@ -23,22 +23,22 @@ export type isGiftDeletedAlreadyType = {
};

export default function Home() {
const [giftData, setGiftData] = useState<FullLocalStorage[]>([]);
const [giftData, setGiftData] = useState<Gifts[]>([]);
const [giftNameError, setGiftNameError] = useState(false);
const [receiverError, setReceiverError] = useState(false);
const [newReceiver, setNewReceiver] = useState('');
const [newGiftName, setNewGiftName] = useState('');
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalGiftData, setModalGiftData] = useState<FullLocalStorage>();
const [modalGiftData, setModalGiftData] = useState<Gifts>();

useEffect(() => {
console.log('effect');
async function fetchData() {
const gifts = await (await jsonServerFunctions.getAll()).data;
async function fetchGifts() {
const gifts = await getAllGifts();
setGiftData(gifts);
}
fetchData().catch((e) => {
throw new Error(e);
fetchGifts().catch((e) => {
console.error(e);
});
}, []);

Expand All @@ -47,7 +47,7 @@ export default function Home() {
setGiftNameError(false);
setReceiverError(false);
// this variable is used for checking both inputs
// could use return statement instead of errorFound, but it would not give an error message to all invalid input. Only the first invalid input.
// could use return statement instead of errorFound, but it would not give an error message to all invalid inputs. Only the first invalid input.
let errorFound = false;

if (typeof newGiftName !== 'string' || newGiftName.length === 0) {
Expand All @@ -63,26 +63,24 @@ export default function Home() {
}

const generatedUUID = crypto.randomUUID();
const JSON_OBJECT: FullLocalStorage = {
const newGift: Gifts = {
name: newReceiver,
gift: newGiftName,
id: generatedUUID,
createdDate: new Date().getTime(),
};

const currentGiftList: FullLocalStorage[] = (
await jsonServerFunctions.getAll()
).data;
const updatedGiftList = currentGiftList.concat(JSON_OBJECT);
const currentGiftList = await getAllGifts();
const updatedGiftList = currentGiftList.concat(newGift);

await jsonServerFunctions.create(JSON_OBJECT);
await createGift(newGift);
setGiftData(updatedGiftList);
setNewGiftName('');
setNewReceiver('');
}

async function refreshGiftList() {
setGiftData(await (await jsonServerFunctions.getAll()).data);
setGiftData(await getAllGifts());
}

return (
Expand Down
52 changes: 29 additions & 23 deletions utils/jsonServerFunctions.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,51 @@
import axios from 'axios';
import { Gifts } from '~/pages';

const baseURL = 'http://localhost:3001/gifts';
//const baseURL = 'http://localhost:3001/gifts'; // localhost url
const baseURL = 'https://my-json-server.typicode.com/samuliasmala/lahjalista/gifts'; // external url

async function getAll() {
return await axios.get(baseURL);
/**
*
* @returns an array that contains all the gifts as objects
*/
export async function getAllGifts() {
return (await axios.get(baseURL)).data as Gifts[];
}

/**
*
* @param searchParameters should be given a string that contains search parameters as query strings.
* @example name=Foo&gift=Bar
* @returns an array of JavaScript objects if found. Else an empty array
* @param id should be given a string that contains the id that is wanted to be searched.
* @returns an object of a gift if it was found. Else it will return null
*/
async function getOne(searchParameters: string) {
return (await axios.get(`${baseURL}?${searchParameters}`)).data;
export async function getGift(id: string) {
const gifts = (await axios.get(`${baseURL}?id=${id}`)).data;
if (gifts.length != 0) {
return gifts[0];
}
return null;
}

async function create(newObject: object) {
return (await axios.post(baseURL, newObject)).data;
/**
*
* @param newObject a new object of a gift that will added to the server
*/
export async function createGift(newObject: object) {
await axios.post(baseURL, newObject);
}

/**
*
* @param searchParameters should be given a string that contains search parameters as query strings.
* @example name=Foo&gift=Bar
* @param newObject a new object that will be replacing the old object
* @returns an array of JavaScript objects after the update
* @param id should be given a string that contains search parameters as query strings.
* @param newObject a new object of Gifts that will be replacing the old object
*/
async function update(searchParameters: string, newObject: object) {
return (await axios.put(`${baseURL}?${searchParameters}`, newObject)).data;
export async function updateGift(id: string, newObject: Gifts) {
await axios.put(`${baseURL}/${id}`, newObject);
}

/**
*
* @param id should be given the id that is wanted to be removed
* @returns
*/
async function remove(id: string) {
return (await axios.delete(`${baseURL}/${id}`)).data;
export async function removeGift(id: string) {
await axios.delete(`${baseURL}/${id}`);
}

const exportableModules = { getAll, getOne, create, update, remove };

export default exportableModules;
4 changes: 2 additions & 2 deletions utils/sortGiftsOldestFirst.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { FullLocalStorage } from '~/pages';
import { Gifts } from '~/pages';
/**
*
* @param giftArray an array of objects
* @returns an array of objects that is sorted from lowest createdDate to highest
*/

export function sortGiftsOldestFirst(giftArray: readonly FullLocalStorage[]) {
export function sortGiftsOldestFirst(giftArray: readonly Gifts[]) {
return [...giftArray].sort((a, b) => a.createdDate - b.createdDate);
}