Agenda

<aside> 📌 Reminders


Introducing Node.js

<aside> 💡

Node.js: a runtime environment for executing JavaScript code outside of the browser. It allows you to build server-side applications with JavaScript.

</aside>

<aside> 💡

npm: the default package manager for Node.js. You'll use it to manage project dependencies like Express, Mocha, and Chai.

</aside>

Example: Initializing a Node.js Project and Installing Dependencies

# Initialize the project and create a package.json file
$ npm init

# Install Express.js
$ npm install --save express

# Install development dependencies like Mocha, Chai, and Chai-HTTP for testing
$ npm install --save-dev mocha chai chai-http

Express.js Framework

<aside> 💡

Express.js: a minimal and flexible Node.js framework used for building web applications and APIs. It simplifies HTTP request handling, routing, and middleware integration.

</aside>

Example: Basic Express.js Setup

// Import the express package
const express = require('express');

// Create an instance of Express
const app = express();

// Middleware to parse JSON bodies
app.use(express.json());

// Define a sample GET route
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// Start the server on port 3000
app.listen(3000, () => {
  console.log('Server running on <http://localhost:3000>');
});

REST Architecture

<aside> 💡

REST (Representational State Transfer): an architectural style for designing networked applications. In RESTful APIs, resources (like messages) are identified via URLs, and actions are performed using HTTP methods (like GET, POST, DELETE).

</aside>

Example: Defining RESTful Routes in Express

// Define an array to store messages
let messages = [];

// POST request to create a new message
app.post('/api/messages', (req, res) => {
  const newMessage = {
    id: messages.length + 1,
    content: req.body.content,
    author: req.body.author,
    upvote: 0,
    downvote: 0
  };
  messages.push(newMessage);
  res.status(201).json(newMessage);
});

// GET request to fetch all messages
app.get('/api/messages', (req, res) => {
  res.json({ messages });
});

// DELETE request to remove a specific message by ID
app.delete('/api/messages/:id', (req, res) => {
  const messageId = parseInt(req.params.id);
  messages = messages.filter(msg => msg.id !== messageId);
  res.json({ messageId, status: 'deleted' });
});

Additional Tools

Mocha and Chai:

Example: Writing and Running Tests with Mocha and Chai