-
Notifications
You must be signed in to change notification settings - Fork 6
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
base: main
Are you sure you want to change the base?
Changes from all commits
ae15d8f
21cb19e
e223aa0
793c124
d0bc139
872594c
abff4fc
77de5cb
475c58d
5fa7525
03c1982
1150684
bcfc24d
9736335
fc8904e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
PORT=3000 | ||
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
node_modules/ | ||
.env | ||
.vscode | ||
npm-debug.log |
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 () => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
---|---|---|
@@ -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" | ||
} | ||
} |
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; |
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()) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 }); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
} catch (err) { | ||
if (err.status === 404) { | ||
const notFoundMessage = new Error(`${cityName} not found`); | ||
notFoundMessage.status = 404; | ||
return next(notFoundMessage); | ||
} | ||
|
||
next(err); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export const API_WEATHER_KEY = "007dd5ca6a8f91773d26bde4f0099937"; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; |
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}`); | ||
}); |
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; | ||
} |
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(); | ||
} |
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, "_"))); |
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, "_"))); |
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" | ||
} | ||
} |
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> | ||
|
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}/`); | ||
}); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
#content{ | ||
color: green; | ||
} |
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.
Nice job on using a env file! However your
.env
should never be pushed to git!