-
Notifications
You must be signed in to change notification settings - Fork 0
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/api #10
Merged
Merged
Antti/api #10
Changes from all commits
Commits
Show all changes
71 commits
Select commit
Hold shift + click to select a range
83a89a6
Created api folder. Added there a new file gift.ts. Added some basic …
anttiasmala 6eca4ff
Created a switch for every request method. Created as well a handler …
anttiasmala cbb31e1
Changed PUT and DELETE spots in case-switch. Created a placeholder fu…
anttiasmala 4ab759b
Changed removeGift function name to deleGift. Changed file name from …
anttiasmala 0f4f823
Fixed imports due to new name of file giftRequests.ts
anttiasmala 74e9d8b
Added a new variable queryId and gave it a type of string due to ESLi…
anttiasmala 811c8cd
Changed removeGift function to deleteGift to make things working. Cha…
anttiasmala 1b1f106
Added comments after variable queryId to remember to check the commen…
anttiasmala 750ba21
ESLint fixes
anttiasmala 4f160e9
Merged main branch into antti/api
anttiasmala a5f8014
Changed a few lines of JSDoc in giftRequests.ts
anttiasmala fa04b84
Fixed a merge conflict that was not saved for some reason
anttiasmala 7a73272
Created handlePATCH function. Added PATCH into Switch statement
anttiasmala 0df5a97
Added a response if method used in HTTP request is not found in Switc…
anttiasmala 3ba7a4f
Added a try/catch block into handleDELETE
anttiasmala b32eaba
Fixed patch request
anttiasmala 74e1463
Created a new function catchError that is used in all of the handleRE…
anttiasmala ca33ad2
Added try/catch blocks to rest of the handlers
anttiasmala f1e8bdc
Added a new error if the server is down and cannot connect. Added try…
anttiasmala f1a95d3
Enable some rules which are difficult for beginners
samuliasmala da7d388
Changed switch statement to use Record. Changed localhost URL to baseURL
anttiasmala e0c94eb
Added types for returns so they work as they should work
anttiasmala e1d4018
Created a new folder called gifts. Created a new file [id].ts that wo…
anttiasmala 6cba371
Changed status code 400 -> 405 to make status code correct
anttiasmala fb91d72
Added a check if the request is GET
anttiasmala 2fbaf75
Added a try/catch block
anttiasmala a12db8a
Created a variable for baseURL. Added a get request and added a conso…
anttiasmala 5d3e84d
Deleted console.logs. Added responses for error and successful gift r…
anttiasmala da3fcbb
Copied catchError function from gifts.ts. Changed functio name catchE…
anttiasmala 25ee352
Changed the way getGift requests for the gift. Uses now a path instea…
anttiasmala 4076b8b
Renamed gifts.ts -> index.ts and moved it into gifts folder
anttiasmala 14d2973
Added handler for methods and created a handler for GET request
anttiasmala e27585f
Added a handler for POST request
anttiasmala 87b2e5d
Added a handler for PATCH request
anttiasmala aba83d7
Added a handler for PUT request
anttiasmala d9f6e51
Added a handler for DELETE request. PUT and DELETE handlers were insi…
anttiasmala c8deff4
Changed rest of the requests inside giftRequests.ts to use instead th…
anttiasmala 2f649f2
Changed /api/gifts/index.ts file drastically. Deleted handlers that a…
anttiasmala cc23804
Added checks for the ID that it is a string. Added a custom error cod…
anttiasmala 50163b9
Moved functions and variables a bit to make them more clear
anttiasmala decebfd
Deleted one as Type Assersion. Added a string check for handlePUT fun…
anttiasmala 59bb5b3
Changed the way how type check does its check. Now it looks if the re…
anttiasmala 3c3a081
Changed handleGET return's type from Gift[] -> Gift to make it right
anttiasmala 01b475f
Created a new function errorFound. Added try/catch block everywhere w…
anttiasmala 1eca2c7
Deleted localStorageKeyID type from Gift. localStorage is not used an…
anttiasmala ef96b0e
ESLint fixes
anttiasmala e24a8f2
Added a new useState for errors. Created function errorFound and adde…
anttiasmala a94503d
Added an error for only AxiosError
anttiasmala 6581d91
Deleted console.log that was used for debugging and testing purposes
anttiasmala 5141a1d
Added .env line to .gitignore file. .env*.local did not seem to ignor…
anttiasmala 9bf6780
Fixed POST request so it will call the correct endpoint
anttiasmala f5c3484
Moved POST request back to api/gifts/index.ts
anttiasmala 777eb4d
Deleted errorFound function and imported it from the [id].ts file. Ch…
anttiasmala 5811abf
ESLint fixes
anttiasmala c27061e
Deleted generatedUUID variable. Kept the id property in newGift so id…
anttiasmala e88aeca
Changed the way how handlePOST works. It will overwrite the id that w…
anttiasmala e7792d5
.env file will be used for frontend env-variables. .env.local will be…
anttiasmala 2770713
Changed the URL to match with other requests. Added a return statement
anttiasmala b34a6d2
Added return statements to updateGift and deleteGift functions
anttiasmala b3da19a
Moved the query ID string check before running a handler. Now only ne…
anttiasmala 3cd5bbf
json-server generates ID on its own. Now returns the data of the crea…
anttiasmala 7100a3f
Changed type from Gift to CreateGift to make it work properly
anttiasmala 5de268e
Created a new type CreateGift and made it exportable. Deleted ID prop…
anttiasmala 8a84529
Added type Gift into createdGift variable
anttiasmala 201c30c
Created a "global" variable queryID that stores the ID request was ma…
anttiasmala 9c1ef15
Deleted global queryId variable. Created new type HandlerParams where…
anttiasmala 2b5b7f6
PATCH and PUT returns now Axios request's data. Delete request return…
anttiasmala 1cde780
Made frontend's PATCH and POST requests to return data. Fixed the cre…
anttiasmala fea57e2
deleteGift function in giftRequests.ts does not return the axios request
anttiasmala 59a117e
Deleted currentGiftList variable. updatedGiftList variable concats gi…
anttiasmala d352812
handleDELETE does not return the body anymore
anttiasmala File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
import axios, { isAxiosError } from 'axios'; | ||
import { NextApiRequest, NextApiResponse } from 'next'; | ||
import { Gift } from '~/pages'; | ||
|
||
const baseURL = 'http://localhost:3001/gifts'; | ||
|
||
type HandlerParams = { | ||
req: NextApiRequest; | ||
res: NextApiResponse; | ||
queryId: string; | ||
}; | ||
|
||
const HANDLERS: Record<string, (params: HandlerParams) => Promise<void>> = { | ||
GET: handleGET, | ||
PATCH: handlePATCH, | ||
PUT: handlePUT, | ||
DELETE: handleDELETE, | ||
} as const; | ||
|
||
export default async function handler( | ||
req: NextApiRequest, | ||
res: NextApiResponse, | ||
) { | ||
try { | ||
const reqHandler = req.method !== undefined && HANDLERS[req.method]; | ||
if (reqHandler) { | ||
if (typeof req.query.id !== 'string') { | ||
throw new Error('Invalid ID', { cause: 'idError' }); | ||
} | ||
const queryId = req.query.id; | ||
|
||
await reqHandler({ req, res, queryId }); | ||
} else { | ||
return res | ||
.status(405) | ||
.send( | ||
`${req.method} is not a valid method. GET, PATCH, PUT and DELETE request are valid.`, | ||
); | ||
} | ||
} catch (e) { | ||
return errorFound(res, e); | ||
} | ||
} | ||
|
||
async function handleGET({ res, queryId }: HandlerParams) { | ||
const giftRequest = await axios.get(`${baseURL}/${queryId}`); | ||
return res.status(giftRequest.status).send(giftRequest.data as Gift); | ||
} | ||
|
||
async function handlePATCH({ req, res, queryId }: HandlerParams) { | ||
const patchRequest = await axios.patch(`${baseURL}/${queryId}`, req.body); | ||
return res.status(patchRequest.status).json(patchRequest.data as Gift); | ||
} | ||
|
||
async function handlePUT({ req, res, queryId }: HandlerParams) { | ||
const putRequest = await axios.put(`${baseURL}/${queryId}`, req.body); | ||
return res.status(putRequest.status).json(putRequest.data as Gift); | ||
} | ||
|
||
async function handleDELETE({ res, queryId }: HandlerParams) { | ||
const deleteRequest = await axios.delete(`${baseURL}/${queryId}`); | ||
res.status(deleteRequest.status).end(); | ||
return; | ||
} | ||
|
||
export function errorFound(res: NextApiResponse, e: unknown) { | ||
if (isAxiosError(e) && e.response?.status === 404) { | ||
return res | ||
.status(e.response.status) | ||
.send('Lahjaa ei löytynyt palvelimelta!'); | ||
} else if (isAxiosError(e) && e.code === 'ECONNREFUSED') { | ||
return res.status(500).send('Palvelin virhe!'); | ||
} else if (e instanceof Error) { | ||
if (e.cause === 'idError') return res.status(400).send('Virheellinen ID!'); | ||
|
||
return res.status(500).send('Odottamaton virhe tapahtui!'); | ||
} else { | ||
return res.status(500).send('Odottamaton virhe tapahtui!'); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import axios from 'axios'; | ||
import { NextApiRequest, NextApiResponse } from 'next'; | ||
import { Gift } from '../..'; | ||
import { errorFound } from './[id]'; | ||
|
||
const baseURL = 'http://localhost:3001/gifts'; | ||
|
||
const HANDLERS: Record< | ||
string, | ||
(req: NextApiRequest, res: NextApiResponse) => Promise<void> | ||
> = { | ||
GET: handleGET, | ||
POST: handlePOST, | ||
} as const; | ||
|
||
export default async function handler( | ||
req: NextApiRequest, | ||
res: NextApiResponse, | ||
) { | ||
try { | ||
const reqHandler = req.method !== undefined && HANDLERS[req.method]; | ||
if (reqHandler) { | ||
await reqHandler(req, res); | ||
} else { | ||
return res | ||
.status(405) | ||
.send( | ||
`${req.method} is not a valid method. Valid methods are: GET and POST`, | ||
); | ||
} | ||
} catch (e) { | ||
return errorFound(res, e); | ||
} | ||
} | ||
|
||
async function handleGET(req: NextApiRequest, res: NextApiResponse) { | ||
const giftRequest = await axios.get(`${baseURL}`); | ||
return res.status(giftRequest.status).json(giftRequest.data as Gift[]); | ||
} | ||
|
||
async function handlePOST(req: NextApiRequest, res: NextApiResponse) { | ||
const postRequest = await axios.post(baseURL, req.body); | ||
return res.status(postRequest.status).json(postRequest.data as Gift); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import axios from 'axios'; | ||
import { CreateGift, Gift } from '~/pages'; | ||
|
||
const baseURL = '/api/gifts'; | ||
|
||
/** | ||
* | ||
* @returns an array that contains all the gifts as objects | ||
*/ | ||
export async function getAllGifts() { | ||
return (await axios.get(baseURL)).data as Gift[]; | ||
} | ||
|
||
/** | ||
* | ||
* @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 | ||
*/ | ||
export async function getGift(id: string) { | ||
return (await axios.get(`${baseURL}/${id}`)).data as Gift; | ||
} | ||
|
||
/** | ||
* | ||
* @param newObject a new object of a gift with type Gift that will added to the server | ||
*/ | ||
export async function createGift(newObject: CreateGift) { | ||
return (await axios.post(`${baseURL}`, newObject)).data as Gift; | ||
} | ||
|
||
/** | ||
* | ||
* @param id should be given a string that contains the id of the gift that is wanted to be updated | ||
* @param newObject should be given parts of Gift object type that are wanted to be updated | ||
*/ | ||
export async function updateGift(id: string, newObject: Partial<Gift>) { | ||
return (await axios.patch(`${baseURL}/${id}`, newObject)).data as Gift; | ||
} | ||
|
||
/** | ||
* | ||
* @param id should be given the id of the gift that is wanted to be deleted | ||
*/ | ||
export async function deleteGift(id: string) { | ||
await axios.delete(`${baseURL}/${id}`); | ||
return; | ||
} | ||
samuliasmala marked this conversation as resolved.
Show resolved
Hide resolved
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tällaisia tuskin tarvitsee kommentoida, mutta laitan kuitenkin. Vaihdoin removeGift -> deleteGift.
Remove
kuulostaa "väliaikaiselta", kuin taasdelete
pysyvältä ratkaisultaEdit: typo korjattu