Skip to content

Abdul kader w3 prep node #23

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 10 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
31 changes: 31 additions & 0 deletions assignments/hackyourtemperature/_tests_/app.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { app } from '../app.js';
import supertest from 'supertest';

const request = supertest(app);

describe('POST /weather', () => {
it('should get 400 if cityName is empty', async () => {
const response = await request.post('/weather').send({});
expect(response.status).toBe(400);
expect(response.body).toEqual({
weatherText: 'City name is required!'

Choose a reason for hiding this comment

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

Fix the match in API response:

Update it to:

error: 'City name is required!'

});
});

it('should get 404 if cityName is gibberish', async () => {
const response = await request
.post('/weather')
.send({ cityName: 'nonesence123' });
expect(response.status).toBe(404);
expect(response.body).toEqual({ error: 'City name is required!' });
});

it('should get 200 if correct cityName is sent', async () => {
const response = await request
.post('/weather')
.send({ cityName: 'Amsterdam' });

expect(response.status).toBe(200);
expect(response.body.weatherText).toContain('Amsterdam');
});
});
41 changes: 41 additions & 0 deletions assignments/hackyourtemperature/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import express from 'express';
import { keys } from './sources/keys.js';
import fetch from 'node-fetch';

const app = express();

app.use(express.json());

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

app.post('/weather', async (req, res) => {
try {
const { cityName } = req.body;

if (!cityName ) {
return res
.status(400)
.json({ weatherText: 'City name is required!' });
}

const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${cityName }&appid=${keys.API_KEY}`
);

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

const jsonData = await response.json();
const temperature = jsonData.main.temp;
res.status(200).json({
weatherText: `${cityName }: ${temperature}`
});
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});

export { 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: []
};
26 changes: 26 additions & 0 deletions assignments/hackyourtemperature/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "hackyourtemperature",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"test": "jest",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"express": "^4.21.1",
"express-handlebars": "^8.0.1",
"node-fetch": "^3.3.2"
},
"type": "module",
"devDependencies": {
"@babel/core": "^7.26.0",
"@babel/preset-env": "^7.26.0",
"babel-jest": "^29.7.0",
"jest": "^29.7.0",
"supertest": "^7.0.0"
}
}
7 changes: 7 additions & 0 deletions assignments/hackyourtemperature/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { app } from './app.js';

const port = 3001;

app.listen(port, () => {
console.log(`App listening on port ${port}`);
});
4 changes: 4 additions & 0 deletions assignments/hackyourtemperature/sources/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const keys = {
API_KEY: '7fd63ddde6d16bb3769e4d483716e57a'
};

17 changes: 17 additions & 0 deletions week2/practice-exercises/1-joke-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "week2",
"version": "1.0.0",
"description": "## Agenda",
"main": "script.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.21.1",
"node-fetch": "^2.7.0"
}
}
27 changes: 20 additions & 7 deletions week2/practice-exercises/1-joke-api/script.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
/**
* 1. Chuck Norris programs do not accept input
*
*
* `GET` a random joke inside the function, using the API: http://www.icndb.com/api/
* (use `node-fetch`) and print it to the console.
* (use `node-fetch`) and print it to the console.
* Make use of `async/await` and `try/catch`
*
*
* Hints
* - To install node dependencies you should first initialize npm
* - Print the entire response to the console to see how it is structured.
*/

function printChuckNorrisJoke() {
import fetch from "node-fetch";
async function printChuckNorrisJoke() {
// YOUR CODE GOES IN HERE

try {
const url = "https://api.chucknorris.io/jokes/random";
const response = await fetch(url);
if (!response.ok) {
throw new Error("Invalid URL");
}
const data = await response.json();
if (!data || !data.value) {
throw new Error("Error: Joke data not found ");
}
console.log("Joke: ", data.value);
} catch (error) {
throw new Error(`Fetching data failed: ${error.message}`);
}
}

printChuckNorrisJoke();
printChuckNorrisJoke();
15 changes: 15 additions & 0 deletions week2/practice-exercises/2-party-time/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "2-party-time",
"version": "1.0.0",
"description": "Are you excited for the biggest party on the planet? We are and we would like to invite everyone, but there is only a limited number of seats.",
"main": "script.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"node-fetch": "^3.3.2"
}
}
20 changes: 19 additions & 1 deletion week2/practice-exercises/2-party-time/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,27 @@
* Hints:
* - make sure to use the correct headers and http method in the request
*/
import fetch from 'node-fetch';

function makeReservation() {
async function makeReservation() {
try{
const url = "https://reservation100-sandbox.mxapps.io/rest-doc/api";
const response = await fetch(url);
if(!response.ok){
throw new Error("URL: Not found");
}
const data = await response.json();
if(!data){
throw new Error("Data: Not found");

}
console.log(data);
}catch(error){
console.log(error);

}
// YOUR CODE GOES IN HERE

}

makeReservation();
1 change: 1 addition & 0 deletions week2/prep-exercises/1-blog-API/my-blog
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Lorem ipsu13311m
78 changes: 69 additions & 9 deletions week2/prep-exercises/1-blog-API/server.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,70 @@
const express = require('express')
const express = require("express");
const app = express();


// YOUR CODE GOES IN HERE
app.get('/', function (req, res) {
res.send('Hello World')
})

app.listen(3000)
const fs = require("fs");

app.get("/blogs/:title", (req, res) => {
const { title } = req.params;

try {
if (fs.existsSync(title)) {
const content = fs.readFileSync(title, "utf-8");
res.send(content);
} else {
res.status(404).send("Blog not found");
}
} catch (err) {
res.status(500).send("Error reading file: " + err.message);
}
});

app.use(express.json());
app.post("/blogs", function (req, res) {
const { title, content } = req.body;
if (!title || !content) {
return res.status(400).send("Title and content are required");
}
try {
fs.writeFileSync(title, content);
res.status(201).send("Blog created successfully");
} catch (err) {
res.status(500).send("Error writing file: " + err.message);
}
});

app.put("/posts/:title", function (req, res) {
const { title } = req.params;
const { content } = req.body;
if (!content) {
return res.status(400).send("Content is required to update the blog");
}

try {
if (fs.existsSync(title)) {
fs.writeFileSync(title, content);
res.send("Blog updated successfully");
} else {
res.status(404).send("Blog not found");
}
} catch (err) {
res.status(500).send("Error updating file: " + err.message);
}
});

app.delete("/blogs/:title", (req, res) => {
const { title } = req.params;

try {
if (fs.existsSync(title)) {
fs.unlinkSync(title);
res.send("Blog deleted successfully");
} else {
res.status(404).send("Blog not found");
}
} catch (err) {
res.status(500).send("Error deleting file: " + err.message);
}
});

app.listen(3001, () => {
console.log("Server running on port 3001");
});
5 changes: 2 additions & 3 deletions week3/prep-exercise/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@
"dependencies": {
"bcrypt": "^5.1.1",
"express": "^4.18.2",
"lokijs": "^1.5.12",
"jsonwebtoken": "^9.0.2",
"lokijs": "^1.5.12",
"uuid": "^9.0.1"
},
"devDependencies": {
"nodemon": "^3.1.0"
"nodemon": "^3.1.9"
}
}

24 changes: 15 additions & 9 deletions week3/prep-exercise/server/app.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import express from 'express';
// TODO Use below import statement for importing middlewares from users.js for your routes
// TODO import { ....... } from "./users.js";
import express from "express";
import { register, login, getProfile, logout } from "./controllers.js";

let app = express();
const app = express();

app.use(express.json());
// TODO: Create routes here, e.g. app.post("/register", .......)
// Register Endpoint
app.post("/register", register);

// Serve the front-end application from the `client` folder
app.use(express.static('client'));
// Login Endpoint
app.post("/login", login);

// Get Profile Endpoint
app.get("/profile", getProfile);

// Logout Endpoint
app.post("/logout", logout);

// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
console.log("Server is running on port 3000");
});
Loading