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

Week2 assignment #343

Open
wants to merge 5 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
145 changes: 143 additions & 2 deletions 02-nodejs/authenticationServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,150 @@
Testing the server - run `npm run test-authenticationServer` command in terminal
*/

const express = require("express")
const express = require("express");
const bodyParser = require("body-parser");
const PORT = 3000;
const app = express();
let users = [];

app.use(bodyParser.json());

app.post("/signup", (req, res) => {
const user = req.body;
let userAlreadyExists = false;
for (let i = 0; i < users.length; i++) {
if (users[i].email === user.email) {
userAlreadyExists = true;
break;
}
}
if (userAlreadyExists) {
res.sendStatus(400);
} else {
users.push(user);
res.status(201).send("Signup successful");
}
});

app.post("/login", (req, res) => {
const user = req.body;
let userfound = null;
for (let i = 0; i < users.length; i++) {
if (users[i].email === user.email && users[i].password === user.password) {
userfound = users[i];
break;
}
}
if (userfound) {
res.json({
firstname: userfound.firstname,
lastname: userfound.lastname,
id: userfound.id
});
}
else {
res.sendStatus(401);
}
});

app.get("/data", (req, res) => {
let email = req.headers.email;
let password = req.headers.password;
let userfound = false;
for(let i = 0 ; i < users.length; i++){
if(users[i].email === email && users[i].password === password){
userfound = users[i];
break;
}
}
if(userfound){
res.json(userfound);
}
else{
res.sendStatus(401);
}
});
// write your logic here, DONT WRITE app.listen(3000) when you're running tests, the tests will automatically start the server

module.exports = app;
app.use((req, res) => {
res.sendStatus(404);
});

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


// const express = require("express");
// const bodyParser = require("body-parser");
// const PORT = 3000;
// const app = express();
// let users = [];

// app.use(bodyParser.json());

// app.post("/signup", (req, res) => {
// const user = req.body;
// let userAlreadyExists = false; // Fixed typo here
// for (let i = 0; i < users.length; i++) {
// if (users[i].email === user.email) {
// userAlreadyExists = true;
// break;
// }
// }
// if (userAlreadyExists) {
// res.sendStatus(400);
// } else {
// users.push(user);
// res.status(201).send("Signup successful");
// }
// });

// app.post("/login", (req, res) => {
// const user = req.body;
// let userFound = null; // Improved variable naming consistency
// for (let i = 0; i < users.length; i++) {
// if (users[i].email === user.email && users[i].password === user.password) {
// userFound = users[i];
// break;
// }
// }
// if (userFound) {
// res.json({
// firstname: userFound.firstname,
// lastname: userFound.lastname,
// id: userFound.id
// });
// } else {
// res.sendStatus(401);
// }
// });

// app.get("/data", (req, res) => {
// let email = req.headers.email;
// let password = req.headers.password;
// let userFound = false;
// for (let i = 0; i < users.length; i++) {
// if (users[i].email === email && users[i].password === password) {
// userFound = users[i];
// break;
// }
// }
// if (userFound) {
// res.json(userFound);
// } else {
// res.sendStatus(401);
// }
// });

// // Correctly placing the 404 handler
// app.use((req, res) => {
// res.sendStatus(404);
// });

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

// module.exports = app;
33 changes: 33 additions & 0 deletions 02-nodejs/fileServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,40 @@
const express = require('express');
const fs = require('fs');
const path = require('path');
const port = 3000;
const app = express();

app.get('/files', (req,res) => {
const directoryPath = path.join( __dirname, 'files');
fs.readdir(directoryPath,(err, files) => {
// err? res.status(500).send() : res.status(200).json(files);
if(err){
res.status(500).send();
} else{
res.status(200).json(files);
}
})
})


app.get('/files/:filename',(req,res) =>{
const filename = req.params.filename;
fs.readFile(path.join( __dirname,'./files',filename), 'utf8', (err, data) => {
if(err){
res.status(404).send('File not found');
} else{
res.status(200).send(data);
}
})
})

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

app.use((req, res) =>{
res.status(404).send();
})

module.exports = app;

Empty file removed 02-nodejs/solutions/todos.json
Empty file.
113 changes: 112 additions & 1 deletion 02-nodejs/todoServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,122 @@

Testing the server - run `npm run test-todoServer` command in terminal
*/
const bodyParser = require('body-parser');
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const port = 3000;

const app = express();
// Adjust the path to include the 'solutions' directory
const filePath = path.join(__dirname, 'todos.json');

app.use(bodyParser.json());
let todos = [];

function findIndex(arr, id){
for(let i = 0; i < arr.length; i++){
if(arr[i].id === id) return i;
}
return "Error: Something went wrong!";
}

function removeIndex(arr, id){
let newArray = [];
for(let i = 0; i <arr.length; i++){
if(arr[i].id !== id) return newArray.push(arr[i]);
}
return "Error: Something went wrong!";
}

app.get('/todos', (req, res) => {
console.log(filePath);
fs.readFile(filePath, 'utf8', (err, data) => {
if(err) throw err;
res.json(JSON.parse(data));
})
});

app.get('/todos/:id', (req, res) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if(err) throw err;
const todos = JSON.parse(data);
const todoIndex = findIndex(todos, parseInt(todos, parseInt(req.params.id)));
if(todoIndex === -1){
res.status(404).send();
}
else{
res.json(todos[todoIndex]);
}
})
})

app.post('/todos', (req, res) => {
const newTodo = {
id: Math.floor(Math.random() * 1000000),
title: req.body.title,
description: req.body.description
}
fs.readFile(filePath, 'utf8', (err, data) => {
if(err) throw err;
const todos = JSON.parse(data);
todos.push(newTodo);
fs.writeFille(filePath, JSON.stringify(todos), (err) => {
if(err) throw err;
res.status(201).json(newTodo);
})
})
});

app.put('/todos/:id', (req, res) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if(err) throw err;
const todos = JSON.parse(data);
const todoIndex = findIndex(todos, parseInt(req.params.id));
if(todoIndex === -1){
res.status(404).send();
}
else{
const updatedTodo = {
id : todos[todoIndex].id,
title: req.body.title,
description: req.body.description
}
todos[todoIndex] = updatedTodo;
fs.writeFile(filePath, JSON.stringify(todos), (err) => {
if(err) throw err;
res.json(updatedTodo);
});
}});
});


app.delete('/todos/:id', (req, res) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if(err) throw err;
const todos = JSON.parse(data);
const todoIndex = findIndex(todos, pareseInt(req, res.params.id));
if(todoIndex === -1){
res.status(404).send();
}
else{
todos = removeIndex(todos, todoIndex);
fs.writeFile(filePath, Json.stringify(todos), (err) => {
if(err) throw err;
res.status(200).send();
})
}
})
})



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

app.use((req, res) =>{
res.status(404).send();
});

module.exports = app;
12 changes: 12 additions & 0 deletions 02-nodejs/todos.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[
{ "name": "John Doe", "age": 30, "city": "New York" },
{ "name": "Jane Smith", "age": 25, "city": "San Francisco" },
{ "id": 872413, "title": "jbvbfib", "description": "khhvi" },
{
"id": 143363,
"title": "Sample Todo",
"description": "This is a updated sample todo item."
},
{ "id": 566104, "title": "", "description": "" },
{ "id": 856526, "title": "", "description": "" }
]