Skip to content

Commit 0caae9d

Browse files
committed
chore: move week2 to a separate PR
1 parent ac52ef9 commit 0caae9d

File tree

7 files changed

+6
-320
lines changed

7 files changed

+6
-320
lines changed

courses/backend/node/README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ This module is part of the Backend specialism and focuses on using Node.js to bu
44

55
## Contents
66

7-
| Week | Topic | Preparation | Lesson Plan | Assignment |
8-
| ---- | ------------------------ | ----------------------------------- | ------------------------------------ | ----------------------------------- |
9-
| 1. | Express | [Preparation](week1/preparation.md) | [Homework](week1/homework/README.md) | [Lesson plan](week1/lesson-plan.md) |
10-
| 2. | Database connection; API | [Preparation](week2/preparation.md) | [Homework](week2/homework/README.md) | [Lesson plan](week2/lesson-plan.md) |
7+
| Week | Topic | Preparation | Lesson Plan | Assignment |
8+
| ---- | ------------------------ | ----------------------------------- | ----------------------------------- | ------------------------------------- |
9+
| 1. | Express | [Preparation](week1/preparation.md) | [Assignment](./week1/assignment.md) | [Session plan](week1/session-plan.md) |
10+
| 2. | Database connection; API | [Preparation](week2/preparation.md) | [Assignment](./week1/assignment.md) | [Session plan](week2/session-plan.md) |
1111

1212
## Module Learning Goals
1313

courses/backend/node/week1/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,8 @@ There are a few good extensions or middleware that is easy to plug into express
6464
### Relevant links
6565

6666
- [Preparation](preparation.md)
67-
- [Homework](homework/README.md)
68-
- [Lesson plan](lesson-plan.md)
67+
- [Assignment](./assignment.md)
68+
- [Session plan](./session-plan.md)
6969

7070
### Express.js
7171

courses/backend/node/week1/assignment.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,4 +197,3 @@ Your usage of Knex should be getting a bit more advanced now. You will move from
197197
- `.del` (for deletion)
198198

199199
Check out the [Knex cheatsheet](https://devhints.io/knex)!
200-
Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +0,0 @@
1-
# Session plan (Week 2)
2-
3-
In this session we will focus on connecting to a database, building an API, and using Postman to test our API endpoints. We will also cover how to structure our code for better maintainability and scalability.
4-
5-
## Contents
6-
7-
- [Preparation](./preparation.md)
8-
- [Session Plan](./session-plan.md) (for mentors)
9-
- [Assignment](./assignment.md)
10-
11-
## Session Learning goals
12-
13-
By the end of this session, you will be able to:
14-
TODO - Format as `verb`
15-
16-
- [ ] Database interaction
17-
- [ ] Connecting to mysql using Knex
18-
- [ ] Environment variables
19-
- [ ] Executing queries using knex
20-
- [ ] API
21-
- [ ] REST
22-
- [ ] CRUD
23-
- [ ] Router verb `GET`, `POST`, `DELETE`, `PUT`
24-
- [ ] POST mention express.json middleware
25-
- [ ] Postman
26-
27-
TODO - Move this content somewhere else
28-
29-
### 1. What is Representational State Transfer (REST)?
30-
31-
Building software is like building houses: architecture is everything. The design of each part is just as important as the utility of it. REST is a specific architectural style for web applications. It serves to organise code in **predictable** ways.
32-
33-
The most important features of REST are:
34-
35-
- An application has a `frontend` (client) and a `backend` (server). This is called [separation of concerns](https://medium.com/machine-words/separation-of-concerns-1d735b703a60): each section has its specific job to do. The frontend deals with presenting data in a user friendly way, the backend deals with all the logic and data manipulation
36-
- The server is `stateless`, which means that it doesn't store any data about a client session. Whenever a client sends a request to the server, each request from the client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. This makes it possible to handle requests from millions of users.
37-
- Server responses can be temporarily stored on the client (a browser) using a process called `caching`: storing files like images or webpages in the browser to load the next time you enter a website (instead of getting them from the server, which generally takes longer to do).
38-
- Client-server communication is done through `Hypertext Transfer Protocol (HTTP)` (more on that later), which serves as the style (the how) of communication.
39-
40-
It's important to know about REST because it teaches us how web applications are designed and holds us to a standard that makes development and usage predictable. However, don't worry if you don't know what any of this means just yet. It's good to be exposed to it, and understanding will come with experience.
41-
42-
For more research, check the following resource:
43-
44-
- [What is REST: a simple explanation for beginners](https://medium.com/extend/what-is-rest-a-simple-explanation-for-beginners-part-1-introduction-b4a072f8740f)
45-
46-
- [@NoerGitKat (lots of web app clones/examples to learn from)](https://github.com/NoerGitKat)
Lines changed: 0 additions & 208 deletions
Original file line numberDiff line numberDiff line change
@@ -1,208 +0,0 @@
1-
# Assignment
2-
3-
Once again, you will deliver 2 pull requests:
4-
5-
- A pull request for the **Warmup** - in your regular hyf-homework repository
6-
- A pull request for the additional **meal sharing endpoints** - in the meal-sharing repository
7-
8-
In both repositories, create a `nodejs-week2` branch from `main` to work on the homework (`git checkout -b nodejs-week2` ).
9-
10-
## Warmup
11-
12-
For the warmup you will be handed a Contacts API with a single endpoint:
13-
14-
- `GET /api/contacts`
15-
16-
This endpoint accepts a query parameter `sort`. Here's how you can use it:
17-
18-
- `GET /api/contacts?sort=first_name%20ASC`
19-
- Sorts contacts by first name, ascending
20-
- `GET /api/contacts?sort=last_name%20DESC`
21-
- Sorts contacts by last name, descending
22-
23-
But this `sort` query parameter has been introduced with a SQL injection vulnerability and the goal is to demonstrate the issue and then fix and remove the vulnerability.
24-
25-
### Setup
26-
27-
TODO - Review assignment to work with sqlite.
28-
29-
Go to `nodejs/week2` in your `hyf-homework` repo:
30-
31-
```shell
32-
npm init -y
33-
npm i express sqlite3 knex
34-
npm set-script dev "node --watch app.js"
35-
```
36-
37-
Make sure you have `"type": "module"` in your `package.json`.
38-
39-
You should also ensure that the `node_modules/` folder is ignored by Git:
40-
41-
```shell
42-
echo node_modules/ >> .gitignore
43-
```
44-
45-
Create a database/schema called `hyf_node_week2_warmup` with a `contacts` table:
46-
47-
```sql
48-
CREATE TABLE `contacts` (
49-
`id` int unsigned NOT NULL AUTO_INCREMENT,
50-
`first_name` varchar(255) NOT NULL,
51-
`last_name` varchar(255) NOT NULL,
52-
`email` varchar(255) DEFAULT NULL,
53-
`phone` varchar(255) DEFAULT NULL,
54-
PRIMARY KEY (`id`)
55-
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
56-
57-
-- Sample data
58-
insert into contacts (id, first_name, last_name, email, phone) values (1, 'Selig', 'Matussov', 'smatussov0@pinterest.com', '176-630-4577');
59-
insert into contacts (id, first_name, last_name, email, phone) values (2, 'Kenny', 'Yerrington', null, null);
60-
insert into contacts (id, first_name, last_name, email, phone) values (3, 'Emilie', 'Gaitskell', null, null);
61-
insert into contacts (id, first_name, last_name, email, phone) values (4, 'Jordon', 'Tokell', null, null);
62-
insert into contacts (id, first_name, last_name, email, phone) values (5, 'Sallyann', 'Persse', 'spersse4@webnode.com', '219-157-2368');
63-
insert into contacts (id, first_name, last_name, email, phone) values (6, 'Berri', 'Bulter', null, null);
64-
insert into contacts (id, first_name, last_name, email, phone) values (7, 'Lanni', 'Ivanilov', 'livanilov6@fda.gov', null);
65-
insert into contacts (id, first_name, last_name, email, phone) values (8, 'Dagny', 'Milnthorpe', null, null);
66-
insert into contacts (id, first_name, last_name, email, phone) values (9, 'Annadiane', 'Bansal', null, null);
67-
insert into contacts (id, first_name, last_name, email, phone) values (10, 'Tawsha', 'Hackley', null, null);
68-
insert into contacts (id, first_name, last_name, email, phone) values (11, 'Rubetta', 'Ozelton', null, null);
69-
insert into contacts (id, first_name, last_name, email, phone) values (12, 'Charles', 'Boughey', 'cbougheyb@senate.gov', '605-358-5664');
70-
insert into contacts (id, first_name, last_name, email, phone) values (13, 'Shantee', 'Robbe', null, null);
71-
insert into contacts (id, first_name, last_name, email, phone) values (14, 'Gleda', 'Peat', null, null);
72-
insert into contacts (id, first_name, last_name, email, phone) values (15, 'Arlinda', 'Ethersey', 'aetherseye@biglobe.ne.jp', '916-139-1300');
73-
insert into contacts (id, first_name, last_name, email, phone) values (16, 'Armando', 'Meachem', 'ameachemf@oaic.gov.au', '631-442-5339');
74-
insert into contacts (id, first_name, last_name, email, phone) values (17, 'Codi', 'Redhouse', null, '401-953-6897');
75-
insert into contacts (id, first_name, last_name, email, phone) values (18, 'Ann', 'Buncombe', 'abuncombeh@ow.ly', '210-338-0748');
76-
insert into contacts (id, first_name, last_name, email, phone) values (19, 'Louis', 'Matzkaitis', 'lmatzkaitisi@ebay.com', '583-996-6979');
77-
insert into contacts (id, first_name, last_name, email, phone) values (20, 'Jessey', 'Pala', null, null);
78-
insert into contacts (id, first_name, last_name, email, phone) values (21, 'Archy', 'Scipsey', 'ascipseyk@ask.com', '420-983-2426');
79-
insert into contacts (id, first_name, last_name, email, phone) values (22, 'Benoit', 'Mould', 'bmouldl@bing.com', '271-217-9218');
80-
insert into contacts (id, first_name, last_name, email, phone) values (23, 'Sherm', 'Girardey', 'sgirardeym@guardian.co.uk', '916-999-2957');
81-
insert into contacts (id, first_name, last_name, email, phone) values (24, 'Raquel', 'Mudge', 'rmudgen@slate.com', '789-830-7473');
82-
insert into contacts (id, first_name, last_name, email, phone) values (25, 'Tabor', 'Reavey', null, null);
83-
```
84-
85-
Create `app.js`:
86-
87-
```js
88-
import knex from "knex";
89-
import express from "express";
90-
91-
const dbFile = "PATH_TO_YOUR_SQLITE_DB";
92-
93-
const knexInstance = knex({
94-
client: "sqlite3",
95-
connection: {
96-
filename: dbFile,
97-
},
98-
});
99-
100-
const app = express();
101-
const port = process.env.PORT || 3000;
102-
103-
app.use(express.json());
104-
105-
const apiRouter = express.Router();
106-
app.use("/api", apiRouter);
107-
108-
const contactsAPIRouter = express.Router();
109-
apiRouter.use("/contacts", contactsAPIRouter);
110-
111-
contactsAPIRouter.get("/", async (req, res) => {
112-
let query = knexInstance.select("*").from("contacts");
113-
114-
if ("sort" in req.query) {
115-
const orderBy = req.query.sort.toString();
116-
if (orderBy.length > 0) {
117-
query = query.orderByRaw(orderBy);
118-
}
119-
}
120-
121-
console.log("SQL", query.toSQL().sql);
122-
123-
try {
124-
const data = await query;
125-
res.json({ data });
126-
} catch (e) {
127-
console.error(e);
128-
res.status(500).json({ error: "Internal server error" });
129-
}
130-
});
131-
132-
app.listen(port, () => {
133-
console.log(`Listening on port ${port}`);
134-
});
135-
```
136-
137-
As mentioned above, the `sort` query parameter has been introduced with a SQL injection vulnerability.
138-
139-
First, you should demonstrate the SQL injection and that it for instance is possible to drop/delete the `contacts` table with the `sort` query parameter.
140-
You can for instance demonstrate this with a screen recording and include it in the PR description.
141-
142-
After having demonstrated the SQL injection vulnerability, the goal is then to fix the issue by updating `app.js`.
143-
144-
**Hint:** the `multipleStatements: true` part in the configuration indicates how you can use the vulnerability. The configuration should not be changed though, the SQL injection should be fixed by making changes in the `/api/contacts` route.
145-
146-
## Meal sharing endpoints
147-
148-
You will continue working in the meal-sharing repository for this task.
149-
150-
You should have the basic [CRUD](https://www.freecodecamp.org/news/crud-operations-explained/) endpoints for **meals** and **reservations** as the result of last week's homework. This week, you will add **query parameters**, that will allow you to **sort** and **filter** the information retrieved from the database.
151-
152-
### Routes
153-
154-
#### Meals
155-
156-
Work with your `GET api/meals` route to add the query parameters.
157-
Make sure that the query parameters can be combined, f.x. <nobr>`?limit=4&maxPrice=90`.<nobr/>
158-
159-
| Parameter | Data type | Description | Example |
160-
| ----------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
161-
| `maxPrice` | Number | Returns all meals that are cheaper than `maxPrice`. | <nobr>`api/meals?maxPrice=90`<nobr/> |
162-
| `availableReservations` | Boolean | Returns all meals that still have available spots left, if `true`. If `false`, return meals that have no available spots left.[^1] | <nobr>`api/meals?availableReservations=true`<nobr/> |
163-
| `title` | String | Returns all meals that partially match the given title. `Rød grød` will match the meal with the title `Rød grød med fløde`. | <nobr>`api/meals?title=Indian%20platter`<nobr/> |
164-
| `dateAfter` | Date | Returns all meals where the date for `when` is after the given date. | `api/meals?dateAfter=2022-10-01` |
165-
| `dateBefore` | Date | Returns all meals where the date for `when` is before the given date. | `api/meals?dateBefore=2022-08-08` |
166-
| `limit` | Number | Returns the given number of meals. | `api/meals?limit=7` |
167-
| `sortKey`[^2] | String | Returns all meals sorted by the given key. Allows `when`, `max_reservations` and `price` as keys. Default sorting order is asc(ending). | `api/meals?sortKey=price` |
168-
| `sortDir`[^3] | String | Returns all meals sorted in the given direction. Only works combined with the `sortKey` and allows `asc` or `desc`. | <nobr>`api/meals?sortKey=price&sortDir=desc`<nobr/> |
169-
170-
[^1]: `availableReservations` requires you to work with several database tables at once. Try practicing the right query in MySQL Workbench first (you might have it from Database week2 homework) and once you have it working, build it with `knex`.
171-
172-
[^2]: This used to be `sort_key` in a previous version of the homework text.
173-
174-
[^3]: This used to be `sort_dir` in a previous version of the homework text.
175-
176-
#### Reviews
177-
178-
By now, you have the basic set of endpoints for **meals** and **reservations** and even a collection of query parameters for **meals**. To practice a bit more and finalize the basic backend functionality, create the set of routes for **reviews**:
179-
180-
| Route | HTTP method | Description |
181-
| ----------------------------- | ----------- | ---------------------------------------- |
182-
| `/api/reviews` | GET | Returns all reviews. |
183-
| `/api/meals/:meal_id/reviews` | GET | Returns all reviews for a specific meal. |
184-
| `/api/reviews` | POST | Adds a new review to the database. |
185-
| `/api/reviews/:id` | GET | Returns a review by `id`. |
186-
| `/api/reviews/:id` | PUT | Updates the review by `id`. |
187-
| `/api/reviews/:id` | DELETE | Deletes the review by `id`. |
188-
189-
#### Knex
190-
191-
You should try to avoid using `knex.raw` and instead use the different `knex` functions, for example:
192-
193-
- `.select`, `.from`, `.where`, `join`, `leftJoin`
194-
- `.insert`
195-
- `.update`
196-
- `.del` (for deletion)
197-
198-
Check out the [Knex cheatsheet](https://devhints.io/knex)!
199-
200-
## Hand in homework
201-
202-
Need to brush up on the homework hand-in process?
203-
204-
Check [this resource](https://github.com/HackYourFuture-CPH/Git/blob/main/homework-submission.md) to remember how to hand in the homework correctly!
205-
206-
## Feedback
207-
208-
And finally, please take two minutes to answer the survey [here](https://forms.gle/YG5KCnSCPhb8dJAL9) to give feedback to the staff and mentors.
Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +0,0 @@
1-
# Preparation
2-
3-
- [NodeJS Web API with KNEX and Express](https://www.youtube.com/watch?v=QNw9q4YXR4E) (15 min)
4-
- <https://fullstackopen.com/en/part3/node_js_and_express#rest> up until the `The Visual Studio Code REST client` section (15 min)
5-
- <https://jsonplaceholder.typicode.com/> - Free API for testing and prototyping. (5 min)
Lines changed: 0 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +0,0 @@
1-
# Lesson plan
2-
3-
- Focus on having lots of in class exercises.
4-
- DON'T teach everything, let the students investigate topics on their own as well!
5-
- Focus on how to read documentation, google answers and google errors!!
6-
- Teach towards the students being able to solve the homework.
7-
8-
Remember to add the code you wrote in the class to the relevant class branch's class work folder. If the branch has not been created just create and push it :) If you don't have access, write to one from the core team. You can see an example below!
9-
10-
If you find anything that could be improved then please create a pull request! We welcome changes, so please get involved if you have any ideas!!!
11-
12-
---
13-
14-
- Database interaction
15-
- Connecting to mysql using knex
16-
- Executing queries
17-
- `select`, `create`. You could let the students figure out how `delete` and `update` works
18-
- [Code inspiration](#phonebook-database) especially focus on the promise and query part
19-
- API
20-
- REST
21-
- CRUD
22-
- Router verb `GET`, `POST`, `DELETE`, `PUT`
23-
- Especially focus on post with `app.use(express.urlencoded({ extended: true }));` and `app.use(express.json());`
24-
- [Code inspiration](#phonebook-api)
25-
- Postman
26-
- `POST`, `DELETE`, `PUT` requests
27-
- Exercise finish concerts api
28-
29-
## Code inspiration
30-
31-
### Phonebook database
32-
33-
- Go to the `teacher-live-coding` [repo](https://github.com/HackYourFuture-CPH/teacher-live-coding), to the relevant folder
34-
- Copy the `.env.example` and rename the copied file to `.env`
35-
- Run `npm install`
36-
- Start the application by running `node --watch ./src/backend/phonebook-database-queries.js`
37-
38-
Try and implement this functionality from the bottom while explaining.
39-
40-
### Phonebook api
41-
42-
Start the application by running `node --watch ./src/backend/create-an-api.js`.
43-
44-
The following two routes have been created, get help by the students to create some of the other routes.
45-
46-
| Url | Verb | Functionality | Example |
47-
| ------------------- | ------ | --------------------------- | -------------------- |
48-
| `api/contacts/` | GET | Returns all contacts | `GET api/contacts/` |
49-
| `api/contacts/` | POST | Adds a new contact | `POST api/contacts/` |
50-
| `api/contacts/{id}` | GET | Returns contact by `id` | `GET api/contacts/2` |
51-
| `api/contacts/{id}` | PUT | Updates the contact by `id` | `PUT api/contacts/2` |
52-
| `api/contacts/{id}` | DELETE | Deletes the contact by `id` | `DELETE contacts/2` |
53-
54-
Thank you very much for teaching NodeJS. Please don't hesitate to give feedback by clicking [here](https://forms.gle/sAuVhsTmJ1qSmjgJ6) (teachers and teacher assistants). For homework reviewers, please access the survey [here](https://forms.gle/nVbX9ShusF2a5Aa87).

0 commit comments

Comments
 (0)