Coding Bootcamp Week 5: HTTP, Express, Model-View-Controller (MVC) Pattern & SQL

Backend development

Reem Dalvi
6 min readFeb 12, 2023

I was slightly apprehensive starting week 5, mainly because of my limited experience in backend development, though the uncertainty made it all the more exciting.

HTTP

We first started with building a server from scratch by using .createServer() method and used .listen() on the desired port.

const http = require('http')

const server = http.createServer((request, response) => {
response.setHeader('Content-Type', 'application/json');
response.statusCode = 200;
response.write(JSON.stringify({ msg: 'hello world' }));
response.end();
if (url === '/users' && method === 'GET') {
// logic to retrieve users data and send back to the client on the response body
}
if (url === '/users' && method === 'POST') {
// logic to add the new user from the request body to the data and send the appropriate response
}
});

server.listen(9090, (err) => {
if (err) console.log(err);
else console.log('Server listening on port: 9090');
});

Insomnia was used for testing and debugging HTTP requests. The app allows to create and send requests to web servers, view responses, and analyse the results. It is commonly used in web development and API testing.

A lot of code has to be written in order to send a response to the client/application and also needs to ‘end’ so the client is not left hanging. We also need to state url paths and type of method used.

Additionally when dealing with post/patch/put requisitions, the body of the request needs to be pieced together as data is received in packets, similar to collecting the packets of data that form the body of a response when making requests using http.

But express abstracts away a lot of the above, presenting cleaner and concise code.

Express

Express.js is a popular open-source web application framework for Node.js. It provides a set of features and tools for building web applications and APIs, including middleware, routing, and templating.

const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.status(200).send({ msg: 'Welcome' });
});

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

In the code above, the second argument passed to the app.get() method is referred to as a middleware function.

Middleware functions in Express.js are functions that have access to the request and response objects in the application’s request-response cycle. They can perform various operations on the request and response objects or modify them in some way.

The code is far more succinct than using http.createServer routing.

REST (Representational State Transfer) is a software architectural style that defines a set of constraints and principles for building web services.

RESTful routing typically follows a convention over configuration approach, where the URL structure and HTTP methods used for each resource follow a consistent pattern that is easy to understand and maintain.

Example: instead of having /fetch-cats and /add-cats, /cats can use both a GET and a POST method on the same route.

// get
app.get('/cats', (req, res) => {
const { cheeky } = req.query;
// we would then get our cheeky or not cheeky cats from the data
// and then send the response
});

app.use(express.json());

//post
app.post('/cats', (req, res) => {
console.log(req.body);
});

In order to access the body of the request that is made to the sever, we need to use application-level middleware.

express.json() is a built in middleware function that will parse incoming request JSON bodies, making them available under the req.body property in the controller functions.

The next function is used to pass control to the next middleware function in the stack. Middleware functions are executed in the order in which they are defined, and the next function is used to pass control to the next middleware function in the stack.

** You can add nodemon which restarts the server automatically anytime the JS file is modified. **

MVC architecture

Writing different endpoints with different routers can make the code very lengthy and hard to debug but MVC pattern can make servers more manageable by handling different aspects of the application with different functions.

  • Model — represents the data and business logic of the application. It manages the data, defines how the data should be stored, and provides methods for accessing and modifying the data.
  • View — represents the presentation of the data to the user. It defines the layout and appearance of the user interface and displays the data to the user in a way that is understandable and visually appealing.
  • Controller — acts as an intermediary between the Model and View. It receives input from the user and updates the Model and View accordingly. It also contains the business logic for handling user input and controlling the flow of the application.
// app.js - our server
app.get('/api/cats/:catId', getCatById);

// controllers.js - responsible for handling the request, invoking the model, and sending the response
exports.getCatById = (req, res) => {
const { catId } = req.params;
selectCatById(catId).then((cat) => {
res.status(200).send({ cat });
});
};

// models.js - responsible for interacting with the data and sending data back to the controller (in this case using return). It then catches any error and returns it by using a 'catch' block.
const { readFile } = require('fs/promises')
exports.selectCatById = (catId) => {
return readFile(`data/cats/${catId}.json`, 'utf8').then((catString, err) => {
const parsedCat = JSON.parse(catString);
return parsedCat
}).catch((err) => {
return err
})
};;

The benefits of using the MVC pattern include increased maintainability, reusability, and modularity of the code.

MVC Flow

SQL

I have experience with SQL from doing a course on Codecademy and through CS50x, it was a good recap and reminder how tedious SQL can be.

But we looked at the difference between Relational vs Non-Relational Databases, used PostgreSQL CLI to create/delete databases, CRUD operations on SQL tables, SQL relations and join/aggregate functions.

Links for the Week

Emotional check ⭕️

All’s well and good, with the abundance of work provided by the bootcamp, concepts eventually solidifies in one’s mind. I am enjoying the intensity akin to progressive overload during weight training, the brain’ plasticity seems to be well adjusted to any increase in complexity.

Pair programming, despite its challenges, has proven to serve as a valuable source of social interaction. Rather than solely focusing on productivity, it provides an opportunity to learn how to effectively collaborate on code with another individual. Even if it can be frustrating at times, it can help improve emotional intelligence.

However, I do find myself longing for structured deep work sessions, where distractions are minimized, and focus is solely on the task at hand.

Revisited deep work by Cal Newport over the weekend

Leap through time

--

--

Reem Dalvi

I like finding parallels between biological and computer science