Skip to content
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

Oleksandr week 2 Node JS #18

Open
wants to merge 2 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
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ npm-debug.log
package-lock.json
yarn-error.log
*.bkp

week3/prep-exercise/server-demo/
/assignments/hackyourtemperature/sources/keys.js
week3/prep-exercise/server-demo/
66 changes: 66 additions & 0 deletions assignments/hackyourtemperature/__tests__/app.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import app from "../app.js";
import supertest from "supertest";
import { API_KEY } from "../sources/keys.js";
import nock from "nock";
Copy link

Choose a reason for hiding this comment

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

Nice that you are using a mocking library!

const request = supertest(app);

describe("POST /", (done) => {
afterEach(() => {
nock.cleanAll();
});

it("App returns 200 status on the main page.", async () => {
await request
.get("/")
.expect(200)
.then((res) => {
expect(res.text).toBe("hello from backend to frontend!");
});
});

it("App returns 200 status when the city name is correct.", async () => {
const mockCity = "Amsterdam";
const mockTemp = 15;

nock("https://api.openweathermap.org")
.get("/data/2.5/weather")
.query({ q: mockCity, APPID: API_KEY, units: "metric" })
.reply(200, { name: "Amsterdam", main: { temp: 15 } });

const res = await request
.post("/weather")
.send({ cityName: "Amsterdam" })
.expect(200);

expect(res.body).toEqual({
Amsterdam: 15,
});
});

it("App returns 400 status when the city name is missing.", async () => {
await request
.post("/weather")
.send()
.set("Content-type", "application/json")
.set("Accept", "application/json")
.expect(400, {
weatherText: "City name is required!",
});
});

it("App returns 404 status when the city name is gibberish.", async () => {
nock("https://api.openweathermap.org")
.get("/data/2.5/weather")
.query({ q: "abcdefg", APPID: API_KEY, units: "metric" })
.reply(404, { message: "city not found" });

await request
.post("/weather")
.send({ cityName: "abcdefg" })
.set("Content-type", "application/json")
.set("Accept", "application/json")
.expect(404, {
weatherText: "City is not found!",
});
});
});
33 changes: 33 additions & 0 deletions assignments/hackyourtemperature/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import express from "express";
import fetch from "node-fetch";
import { API_KEY } from "./sources/keys.js";

const app = express();

app.use(express.json());
const baseUrl = "https://api.openweathermap.org/data/2.5/weather";

app.get("/", (req, res) => {
res.send("hello from backend to frontend!");
});

app.post("/weather", async (req, res) => {
if (!req.body.cityName) {
return res.status(400).send({ weatherText: "City name is required!" });
}

const cityName = req.body.cityName;
const url = `${baseUrl}?q=${cityName}&APPID=${API_KEY}&units=metric`;

const response = await fetch(url);

if (!response.ok) {
return res.status(404).send({ weatherText: "City is not found!" });
}

const data = await response.json();

res.status(200).send({ [data.name]: data.main.temp });
});

export default app;
13 changes: 13 additions & 0 deletions assignments/hackyourtemperature/babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
presets: [
[
// This is a configuration, here we are telling babel what configuration to use
"@babel/preset-env",
{
targets: {
node: "current",
},
},
],
],
};
8 changes: 8 additions & 0 deletions assignments/hackyourtemperature/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export default {
// Tells jest that any file that has 2 .'s in it and ends with either js or jsx should be run through the babel-jest transformer
transform: {
"^.+\\.jsx?$": "babel-jest",
},
// By default our `node_modules` folder is ignored by jest, this tells jest to transform those as well
transformIgnorePatterns: [],
};
27 changes: 27 additions & 0 deletions assignments/hackyourtemperature/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "node",
"version": "1.0.0",
"description": "> If you are following the HackYourFuture curriculum we recommend you to start with module 1: [HTML/CSS/GIT](https://github.com/HackYourFuture/HTML-CSS). To get a complete overview of the HackYourFuture curriculum first, click [here](https://github.com/HackYourFuture/curriculum).",
"main": "index.js",
"type": "module",
"scripts": {
"test": "jest",
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.21.0",
"express-handlebars": "^8.0.1",
"nock": "^13.5.5",
"node-fetch": "^3.3.2",
"nodemon": "^3.1.7"
},
"devDependencies": {
"@babel/preset-env": "^7.25.4",
"babel-jest": "^29.7.0",
"jest": "^29.7.0",
"supertest": "^7.0.0"
}
}
7 changes: 7 additions & 0 deletions assignments/hackyourtemperature/server.js
Copy link

Choose a reason for hiding this comment

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

Note the section 3.2.1. in the project instructions. When running the Jest tests, you import the app module, and at the moment that also means starting the server which will fail if the port is already occupied by you running your server there.

Can you think of a way of breaking out only the code necessary to start the server? You should end up with two files:

  • app.js where you define your application, including all the ednpoints. etc. Export the app module from this file.
  • server.js where you import the app module and start the server on a particular port.

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import app from "./app.js";

const PORT = 3004;

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});