Skip to content

Assignments week 2 YANA SENIUK #9

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

Open
wants to merge 15 commits into
base: main
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
1 change: 1 addition & 0 deletions assignments/hackyourtemperature/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PORT=3000

Choose a reason for hiding this comment

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

Nice job on using a env file! However your .env should never be pushed to git!

4 changes: 4 additions & 0 deletions assignments/hackyourtemperature/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
.env
.vscode
npm-debug.log
62 changes: 62 additions & 0 deletions assignments/hackyourtemperature/__tests__/app.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import app from "../src/app.js";
import supertest from "supertest";

const request = supertest(app);

describe("GET /", () => {
it("Should return text 'hello from backend to frontend'", async () => {
const response = await request.get("/");

expect(response.text).toBe("hello from backend to frontend!");
expect(response.status).toBe(200);
});
});

describe("POST /api/weather", () => {
it("Should response JSON with cityName and temperature properties", async () => {

Choose a reason for hiding this comment

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

Very good tests! I would also add a test/extended your happy flow test to check the response data. e.g.g cityName should match the city passed to the api call and for temperature (since of course you cant know what to expect) you can check the type!

const response = await request.post("/api/weather").send({
cityName: "Amsterdam",
});

expect(response.status).toBe(200);
expect(response.body).toHaveProperty("cityName");
expect(response.body).toHaveProperty("temperature");
});

it("Should response JSON with cityName not found", async () => {
const cityName = "andromeda";
const response = await request.post("/api/weather").send({
cityName: `${cityName}`,
});
expect(response.status).toBe(404);
expect(response.body).toEqual({ error: `${cityName} not found` });
});

it("Should response 'Request body is missing'", async () => {
const response = await request.post("/api/weather");

expect(response.status).toBe(400);
expect(response.body.error).toMatch(/request body is missing/i);
});

it("Should response 'Required parameter 'cityName' is missing'", async () => {
const response = await request
.post("/api/weather")
.send({ cityName: " " });

expect(response.status).toBe(400);
expect(response.body).toEqual({
error: "Required parameter 'cityName' is missing",
});
});
});

describe("Unknown routes", () => {
it("Should respond with 404 for undefined path", async () => {
const response = await request.get("/non-existing-path");

expect(response.status).toBe(404);
expect(response.body).toHaveProperty("error");
expect(response.body.error).toMatch(/not found/i);
});
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
module.exports = {
presets: [
[
// This is a configuration, here we are telling babel what configuration to use
"@babel/preset-env",
{
targets: {
Expand Down
23 changes: 23 additions & 0 deletions assignments/hackyourtemperature/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "hackyourtemperature",
"version": "1.0.0",
"description": "",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node src/server.js",
"dev": "node --watch --env-file=.env src/server.js",
"test": "jest"
},
"author": "yanaesher",
"license": "ISC",
"dependencies": {
"express": "^5.1.0"
},
"devDependencies": {
"@babel/preset-env": "^7.27.1",
"babel-jest": "^29.7.0",
"jest": "^29.7.0",
"supertest": "^7.1.0"
}
}
20 changes: 20 additions & 0 deletions assignments/hackyourtemperature/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import express from "express";
import weatherRouter from "./routes/temperature.route.js";

import { notFound } from "./middlewares/notFound.middleware.js";
import { errorHandler } from "./middlewares/error.middleware.js";

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use("/api/weather", weatherRouter);
app.get("/api", (req, res) => {
res.status(200).send("hello from backend to frontend!");
});

app.use(notFound);
app.use(errorHandler);

export default app;
2 changes: 2 additions & 0 deletions assignments/hackyourtemperature/src/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const BASE_WEATHER_URL =
"https://api.openweathermap.org/data/2.5/weather";
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { fetchCurrentWeather } from "../services/weather.service.js";

export async function getCityCurrentWeather(req, res, next) {
const { cityName } = req.body;

if (!cityName?.trim()) {

Choose a reason for hiding this comment

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

You dont need to trim before you check if cityName exists!

const error = new Error("Required parameter 'cityName' is missing");
error.status = 400;

return next(error);
}

try {
const { name, main } = await fetchCurrentWeather(cityName);
res.status(200).json({ cityName: name, temperature: main.temp });

Choose a reason for hiding this comment

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

Before returning, you should validate what your api returned. I would check if main.temp and name is defined before sending it!

} catch (err) {
if (err.status === 404) {
const notFoundMessage = new Error(`${cityName} not found`);
notFoundMessage.status = 404;
return next(notFoundMessage);
}

next(err);
}
}
1 change: 1 addition & 0 deletions assignments/hackyourtemperature/src/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const API_WEATHER_KEY = "007dd5ca6a8f91773d26bde4f0099937";

Choose a reason for hiding this comment

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

Since you are using env files, that would be a perfect place to store your API key! Putting your key on github is dangerous as it can be leaked leading to unauthorized access.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export function errorHandler(err, req, res, next) {

Choose a reason for hiding this comment

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

Really nice job on using a custom error handler!

const statusCode = err.status || 500;
const message = err.message || "Something went wrong";

res.status(statusCode).json({ error: message });
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function notFound(req, res, next) {
const error = new Error(`Not found`);
error.status = 404;
next(error);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function validateBody(req, res, next) {

Choose a reason for hiding this comment

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

I would change the name of this file to match the others or change the others to match this one! It doesnt really matter which one as long as you are consistent! I would personally not add .middleware in the file name as they are already in a middleware folder.

if (!req.body) {
const error = new Error("Request body is missing");
error.status = 400;
return next(error);
}

next();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Router } from "express";
import { validateBody } from "../middlewares/validateBody.js";
import { getCityCurrentWeather } from "../controllers/weather.controller.js";
const router = Router();

router.post("/", validateBody, getCityCurrentWeather);

export default router;
7 changes: 7 additions & 0 deletions assignments/hackyourtemperature/src/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import app from "./app.js";

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
console.log(`Server is running at http://127.0.0.1:${PORT}`);
});
10 changes: 10 additions & 0 deletions assignments/hackyourtemperature/src/services/weather.service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { fetchData } from "../utils/fetchHelper.js";
import { API_WEATHER_KEY } from "../keys.js";
import { BASE_WEATHER_URL } from "../constants.js";

export async function fetchCurrentWeather(cityName) {
const url = `${BASE_WEATHER_URL}?q=${cityName}&appid=${API_WEATHER_KEY}&units=metric`;

const weatherData = await fetchData(url);
return weatherData;
}
11 changes: 11 additions & 0 deletions assignments/hackyourtemperature/src/utils/fetchHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export async function fetchData(url) {
const response = await fetch(url);

if (!response.ok) {
const error = new Error(`Failed to fetch: ${response.status}`);
error.status = response.status;
throw error;
}

return response.json();
}
2 changes: 1 addition & 1 deletion week1/practice-exercises/1-pad-numbers/padLeft.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* e.g. padLeft('foo', 5, '_') -> '__foo'
* e.g. padLeft( '2', 2, '0') -> '02'
*/
function padLeft(val, num, str) {
export function padLeft(val, num, str) {
return '00000'.replace(/0/g, str).slice(0, num - val.length) + val;
}

Expand Down
19 changes: 10 additions & 9 deletions week1/practice-exercises/1-pad-numbers/script.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@

import { padLeft } from "./padLeft.js";
/**
** Exercise 1: Pad numbers
*
*
*
** Exercise 1: Pad numbers
*
* In this file use the padLeft function from padLeft.js to
* pad the numbers to exactly 5 spaces and log them to the console
*
*
* Expected output (replace the underscore with spaces):
*
*
* ___12;
* __846;
* ____2;
* _1236;
*
*
* Tips:
* where to use `exports` and where `require`?
*/

let numbers = [ "12", "846", "2", "1236" ];

// YOUR CODE GOES HERE
let numbers = ["12", "846", "2", "1236"];
numbers.forEach((num) => console.log(padLeft(num, 5, "_")));
2 changes: 0 additions & 2 deletions week1/practice-exercises/2-left-pad/padLeft.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,3 @@
function padLeft(val, num, str) {
return '00000'.replace(/0/g, str).slice(0, num - val.length) + val;
}

// YOUR CODE GOES HERE
14 changes: 3 additions & 11 deletions week1/practice-exercises/2-left-pad/script.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
/**
** Exercise 2: To the left, to the left...
*
* Copy and paste your code from the previous exercise.
* Replace the function `padLeft` to use
* this new NPM package called `left-pad` instead then
* Pad the numbers to 8 characters to confirm that it works correctly
*
*/
import padLeft from "left-pad";

let numbers = [ "12", "846", "2", "1236" ];
let numbers = ["12", "846", "2", "1236"];

// YOUR CODE GOES HERE
numbers.forEach((num) => console.log(padLeft(num, 8, "_")));
16 changes: 16 additions & 0 deletions week1/practice-exercises/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "practice-exercises",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"left-pad": "^1.3.0"
}
}
1 change: 1 addition & 0 deletions week1/prep-exercises/1-web-server/index.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>My First Web Server</title>
</head>
<body>
Expand Down
12 changes: 7 additions & 5 deletions week1/prep-exercises/1-web-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
"version": "1.0.0",
"description": "A simple express server",
"main": "server.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"author": "Andrej Gajduk",
"license": "MIT",
"dependencies": {
"express": "^4.17.1"
"author": "Yana Seniuk",
"license": "ISC",
"devDependencies": {
"nodemon": "^3.1.10"
}
}
52 changes: 42 additions & 10 deletions week1/prep-exercises/1-web-server/server.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,46 @@
/**
* Exercise 3: Create an HTTP web server
*/
import * as http from "node:http";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import * as fs from "node:fs/promises";

const http = require('http');
const PORT = 3000;

//create a server
let server = http.createServer(function (req, res) {
// YOUR CODE GOES IN HERE
res.write('Hello World!'); // Sends a response back to the client
res.end(); // Ends the response
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function handleRoute(file, contentType, status, req, res) {
try {
const filePath = path.join(__dirname, file);
const fileContent = await fs.readFile(filePath, "utf-8");

res.setHeader("Content-type", contentType);
res.statusCode = status;
res.end(fileContent);
} catch (err) {
res.setHeader("Content-type", "text/plain");
res.statusCode = 500;
res.end("Server Error");
}
}

const server = http.createServer((req, res) => {
const routes = {
"/": { file: "index.html", contentType: "text/html" },
"/index.js": { file: "index.js", contentType: "application/javascript" },
"/style.css": { file: "style.css", contentType: "text/css" },
};

const route = routes[req.url];
if (route) {
handleRoute(route.file, route.contentType, 200, req, res);
}

if (!route) {
res.statusCode = 404;
res.end("Not Found");
}
});

server.listen(3000); // The server starts to listen on port 3000
server.listen(PORT, () => {
console.log(`Server is running at http://127.0.0.1:${PORT}/`);
});
3 changes: 3 additions & 0 deletions week1/prep-exercises/1-web-server/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#content{
color: green;
}
Loading