From b578ce659afefb2ad3893a0cf5c53e07d2d9a194 Mon Sep 17 00:00:00 2001 From: tactonbishop Date: Thu, 4 Aug 2022 14:30:04 +0100 Subject: [PATCH] Last Sync: 2022-08-04 14:30:04 --- .../NodeJS/REST_APIs/{2_PUT.md => 2_POST.md} | 33 +++++++++++- .../NodeJS/REST_APIs/3_PUT.md | 52 +++++++++++++++++++ .../NodeJS/REST_APIs/Validation.md | 4 +- 3 files changed, 85 insertions(+), 4 deletions(-) rename Programming_Languages/NodeJS/REST_APIs/{2_PUT.md => 2_POST.md} (60%) create mode 100644 Programming_Languages/NodeJS/REST_APIs/3_PUT.md diff --git a/Programming_Languages/NodeJS/REST_APIs/2_PUT.md b/Programming_Languages/NodeJS/REST_APIs/2_POST.md similarity index 60% rename from Programming_Languages/NodeJS/REST_APIs/2_PUT.md rename to Programming_Languages/NodeJS/REST_APIs/2_POST.md index 7b2302f..b32b3f2 100644 --- a/Programming_Languages/NodeJS/REST_APIs/2_PUT.md +++ b/Programming_Languages/NodeJS/REST_APIs/2_POST.md @@ -45,7 +45,6 @@ const addCourse = async (newCourse) => { console.error(err); } }; - addCourse("Biology and Life Sciences"); ``` @@ -55,4 +54,34 @@ Which returns: { id: 4, name: 'Biology and Life Sciences' } ``` -The `id` is added by the server, not the client. Having created the new value we add it to our `courses` array. (In reality we would be creating a new entry in a database.) Then we follow the convention of returning the new value back to the client. \ No newline at end of file +The `id` is added by the server, not the client. Having created the new value we add it to our `courses` array. (In reality we would be creating a new entry in a database.) Then we follow the convention of returning the new value back to the client. + +## Validation + +We should accept alterations to the database that are not first validated. We can use the [Joi validator](/Programming_Languages/NodeJS/REST_APIs/Validation.md) to vet the request: + +```js +function validateCourse(course) { + const schema = Joi.object({ + name: Joi.string().min(3).required(), + }); + + const { error } = schema.validate(course); + return error; +} +``` +We can then add the validation as part of our general error handling: + +```js +app.post('/api/courses', (req, res) => { + const course = { + id: courses.length + 1, + name: req.body.name + } + const { error } = schema.validate(req.body); + if (error) return error.details.map((joiErr) => res.status(400).send(joiErr.message)); + + courses.push(course); + res.send(course) +}) +``` diff --git a/Programming_Languages/NodeJS/REST_APIs/3_PUT.md b/Programming_Languages/NodeJS/REST_APIs/3_PUT.md new file mode 100644 index 0000000..f7cb955 --- /dev/null +++ b/Programming_Languages/NodeJS/REST_APIs/3_PUT.md @@ -0,0 +1,52 @@ +--- +tags: + - Programming_Languages + - backend + - node-js + - express + - REST + - apis +--- + +# Creating a REST API with Node and Express: PUT requests + +To demonstrate the handling of PUT requests, we will create a handler that updates an element in the course array, based on its `id` and return the updated entry: + +```js +app.put("/api/courses/:id", (req, res) => { + const course = courses.find((c) => c.id === parseInt(req.params.id)); + + if (!course) + return res.status(404).send("A course with the given ID was not found"); + const { error } = validateCourse(req.body); + + if (error) + return error.details.map((joiErr) => res.status(400).send(joiErr.message)); + + course.name = req.body.name; + res.send(course); +}); + +``` +Our request: + +```js +const updateCourse = async (courseChange) => { + try { + const resp = await axios.put("http://localhost:3000/api/courses/1", { + name: courseChange.name, + }); + console.log(resp.data); + } catch (err) { + console.error(err); + } +}; + +updateCourse({ name: "A new course" }); +``` + +Returns: + +```js +{ id: 1, name: { name: 'A new course' } } +``` \ No newline at end of file diff --git a/Programming_Languages/NodeJS/REST_APIs/Validation.md b/Programming_Languages/NodeJS/REST_APIs/Validation.md index d16acf4..705541d 100644 --- a/Programming_Languages/NodeJS/REST_APIs/Validation.md +++ b/Programming_Languages/NodeJS/REST_APIs/Validation.md @@ -14,14 +14,14 @@ One of the most popular schema validators for NodeJS is [joi](https://www.npmjs. Let's say we have a POST request that expects a single field as the body that must be a string and greater than two characters long. First we define our schema: -````js +```js const schema = Joi.object({ name: Joi.string().min(3).required(), }); const { error } = schema.validate(req.body); -```` +``` The `schema` variable is an object whose keys should match those of the intended request body. Instead of actual values we provide Joi's in-built validators, concatenated as necessary. We then store the results of the validation in a variable.