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

Done with all week 2 assignments #342

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

const express = require("express")
const PORT = 3000;
const app = express();
// write your logic here, DONT WRITE app.listen(3000) when you're running tests, the tests will automatically start the server
const express = require("express")
const PORT = 3000;
const app = express();
// write your logic here, DONT WRITE app.listen(3000) when you're running tests, the tests will automatically start the server

var users = [];

app.use(express.json());
app.post("/signup", (req, res) => {
var user = req.body;
let userAlreadyExists = false;
for (var 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) => {
var user = req.body;
let userFound = null;
for (var 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,
email: userFound.email
});
} else {
res.sendStatus(401);
}
});

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

if (userFound) {
let usersToReturn = [];
for (let i = 0; i<users.length; i++) {
usersToReturn.push({
firstName: users[i].firstName,
lastName: users[i].lastName,
email: users[i].email
});
}
res.json({
users
});
} else {
res.sendStatus(401);
}
});

module.exports = app;
module.exports = app;
29 changes: 29 additions & 0 deletions 02-nodejs/fileServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,34 @@ const fs = require('fs');
const path = require('path');
const app = express();

const port = 3000

app.get('/files', (req, res) => {
fs.readdir(path.join(__dirname, './files/'), (err, files) => {
if (err) {
return res.status(500).json({ error: 'Failed to retrieve files' });
}
res.json(files);
});
})

app.get('/file/:filename', (req, res) => {
const filepath = path.join(__dirname, './files/', req.params.filename);

fs.readFile(filepath, 'utf8', (err, data) => {
if (err) {
return res.status(404).send('File not found');
}
res.send(data);
});
});

app.all('*', (req, res) => {
res.status(404).send('Route not found');
});

// app.listen(port, () => {
// console.log(`App listening on port ${port}`)
// })

module.exports = app;
73 changes: 73 additions & 0 deletions 02-nodejs/todoServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,82 @@
*/
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');

const port = 3000;

const app = express();

function middleware1 (req, res, next){
fs.readFile('todos.json', 'utf8', (err, data) => {
if (err) throw err;
req.todos = JSON.parse(data);
next();
})
}

app.use(bodyParser.json());

app.get('/todos', middleware1, (req, res) => {
return res.send(req.todos)
})

app.get('/todos/:id',middleware1, (req, res) => {
const todoIndex = parseInt(req.params.id);
const todo = req.todos.find(todo => todo.id === todoIndex);
if (!todo)
return res.status(404).send();
return res.json(todo);
})

app.post('/todos', middleware1, (req, res) => {
const newTodo = {
id: req.todos.length + 1,
title: req.body.title,
completed: req.body.completed,
description: req.body.description
};
req.todos.push(newTodo);
fs.writeFile('todos.json', JSON.stringify(req.todos), (err) => {
if(err) throw err;
res.status(201).json(newTodo);
})
})

app.put('/todos/:id', middleware1, (req, res) => {
const todoIndex = parseInt(req.params.id);
if (!req.todos[todoIndex - 1])
return res.status(404).json({ error: 'Todo not found' });

req.todos[todoIndex-1].title = req.body.title;
req.todos[todoIndex-1].completed = req.body.completed;
req.todos[todoIndex-1].description = req.body.description;

fs.writeFile('todos.json', JSON.stringify(req.todos), (err) => {
if (err)
return res.status(500).json({ error: 'Internal server error' });
return res.status(200).json({ message: 'Todo updated successfully' });
});
})

app.delete('/todos/:id', middleware1, (req,res) => {
const todoIndex = parseInt(req.params.id);
if (!req.todos[todoIndex - 1])
return res.status(404).json({ error: 'Todo not found' });

req.todos.splice(todoIndex-1,1);
fs.writeFile('todos.json', JSON.stringify(req.todos), (err) => {
if(err) throw err;
return res.status(200).json({ message: 'Todo deleted successfully' });
});
})

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

module.exports = app;

// app.listen(port, () => {
// console.log(`App listening on port ${port}`)
// })
1 change: 1 addition & 0 deletions 02-nodejs/todos.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]