Skip to content
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
7 changes: 4 additions & 3 deletions chat-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
"description": "A simple Node app built on Express, instantly up and running.",
"type": "module",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"scripts": {
"start": "node server.js",
"dev": "node server.js"
},
"dependencies": {
"cors": "^2.8.5"
},
Expand Down
70 changes: 63 additions & 7 deletions chat-server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,80 @@ import { fileURLToPath } from "url";
const app = express();

app.use(cors());
app.use(express.json());

// Get __dirname in ES module
// Obtendo __dirname em um módulo ES
const __dirname = path.dirname(fileURLToPath(import.meta.url));

const welcomeMessage = {
id: 0,
from: "Bart",
text: "Welcome to CYF chat system!",
from: "Maria",
text: "Bem-vindo ao sistema de chat!",
};

//This array is our "data store".
//We will start with one message in the array.
const messages = [welcomeMessage];
// Este array é nosso "data store".
// Começaremos com uma mensagem no array.
let messages = [welcomeMessage];
let count = 0;

app.get("/", (request, response) => {
response.sendFile(__dirname + "/index.html");
});

app.get("/messages", (req, res) => {
res.send(messages);
});

app.get("/messages/search", (req, res) => {
const searchTerm = req.query.text.toLowerCase();
const filteredMessages = messages.filter((message) =>
message.text.toLowerCase().includes(searchTerm)
);
res.send(filteredMessages);
});

app.get("/messages/latest", (req, res) => {
const lastTenMessages = messages.slice(messages.length - 10);
res.send(lastTenMessages);
});

app.get("/messages/:id", (req, res) => {
const messageId = Number(req.params.id);
const foundMessage = messages.find((message) => message.id === messageId);
res.send(foundMessage);
});

app.put("/messages/:id", (req, res) => {
const findIndex = messages.findIndex(
(message) => message.id === Number(req.params.id)
);
const updatedMessage = { ...messages[findIndex], ...req.body };
messages.splice(findIndex, 1, updatedMessage);
res.status(200).send({ success: true });
});

app.use(express.urlencoded({ extended: true }));
app.post("/messages", (req, res) => {
const newMessage = req.body;
if (newMessage.from === "" || newMessage.text === "") {
res.status(400);
} else {
count++;
const id = { id: count };
const currentTime = new Date().toLocaleTimeString();
const timeSent = { timeSent: currentTime };
messages.push(Object.assign(id, newMessage, timeSent));
res.send("Sua mensagem foi adicionada com sucesso!");
}
});

app.delete("/messages/:messageId", (req, res) => {
const messageId = Number(req.params.messageId);
messages = messages.filter((message) => message.id !== messageId);
res.status(204).send();
});


app.listen(process.env.PORT, () => {
console.log(`listening on PORT ${process.env.PORT}...`);
console.log(`Escutando na porta ${process.env.PORT}...`);
});
7 changes: 5 additions & 2 deletions quote-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
"type": "module",
"main": "server.js",
"scripts": {
"start": "node --no-warnings=ExperimentalWarning server.js"
"start": "nodemon --no-warnings=ExperimentalWarning server.js"
},
"license": "MIT",
"keywords": [
"node",
"glitch",
"express"
]
],
"dependencies": {
"express": "^4.19.2"
}
}
41 changes: 16 additions & 25 deletions quote-server/server.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,23 @@
// server.js
// This is where your node app starts

//load the 'express' module which makes writing webservers easy
import express from "express";
//load the quotes JSON
import quotes from "./quotes.json" assert { type: "json" };
import express from 'express';
import quotes from './quotes.json' assert { type: "json" }; // Assuming quotes.json is in the same directory

const app = express();
// Now register handlers for some routes:
// / - Return some helpful welcome info (text)
// /quotes - Should return all quotes (json)
// /quotes/random - Should return ONE quote (json)
app.get("/", (request, response) => {
response.send("Neill's Quote Server! Ask me for /quotes/random, or /quotes");
});

//START OF YOUR CODE...
const PORT = 3000;

//...END OF YOUR CODE
// Route to return all quotes
app.get('/quotes', (req, res) => {
res.json(quotes);
});

//You can use this function to pick one element at random from a given array
//example: pickFromArray([1,2,3,4]), or
//example: pickFromArray(myContactsArray)
//
const pickFromArray = (arrayofQuotes) =>
arrayofQuotes[Math.floor(Math.random() * arrayofQuotes.length)];
// Route to return a random quote
app.get('/quotes/random', (req, res) => {
const randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
res.json(randomQuote);
});

//Start our server so that it listens for HTTP requests!
const listener = app.listen(3001, () => {
console.log("Your app is listening on port " + listener.address().port);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});