DEV Community

alexandertrout
alexandertrout

Posted on

Coding Bootcamp - Backend #2 - Servers, Express & Promises

What is a server?

Servers will deal with requests made by clients to your API over the internet, requests being made by using standard web http protocols. Different 'endpoints' on the API are made avaliable to users, and methods like GET, POST, and DELETE are used on these different endpoints. RESTful servers will follow this pattern, with multiple methods being allowed on each endpoint instead of having a different endpoint for each method. For example, a GET request on the /api/users endpoint should simply respond to the client with information about all the users. However, this endpoint may also allow a POST request, to insert a new user to the database. This ability to have multiple methods allowed on one endpoint is important, and can be implemented by using express to build your server...

Express

How do I build a server using express?

Express is a web framework for Node.js which allows users to create apps which will listen for requests from clients and will send responses. More information on express and getting started can be found here https://expressjs.com/. Using express to build a simple server can be done quickly, and then scaled up to add routers and multiple endpoints, each allowing different methods.

MVC or Model - Controller - View is the software design pattern I've been following. Essentially, once routing has been used to reach an endpoint a 'controller' will handle the request and response, and a 'model' will handle contacting another API or the database, perform any necessary logic, and will return a promise to the controller to be handled. The V in MVC stand for 'view' - this is the point where pages can be served to the user containing the data they requested, and is achieved through using EJS, PUG or similar to inject the data into a HTML file. This approach is still used by many companies, but it has become more popular to remove this presentation aspect to a front-end framework such as react instead.

Servers can look complicated at first...

How servers work

So I'd recommend following a tutorial for a simple server to begin with and build upon that, adding more complexity slowly. Heres one I've made reference to a few times that will explain the basic concepts well.

https://www.youtube.com/watch?v=L72fhGm1tfE&t=1527s

How do promises make async programming easier?

As mentioned in the last post, async programming must be used to avoid blocking when writing code. This was managed previously by using callback functions for any of our asynchronous code. Promises simplify this process by returning what is essentially a 'black box' from a function. This returned 'promise' can be in one of three states:

  • Fulfilled: resolve() was called (Some data is returned inside the promise).

  • Rejected: reject() was called (Something went wrong and an error was returned inside the promise).

  • Pending: not yet fulfilled or rejected.

Promises can wrap functionality in the same way that asynchronous callbacks do, and gaining access to the values within the promises is possible by using the .then() and .catch() methods, once the promise has resolved or rejected.

Example:

getData = (req, res, next) => {
    return (/* data request from an external source */);
};
Enter fullscreen mode Exit fullscreen mode

.then()
Using a .then() after a promise allows us to gain access to the promises return value within the parentheses, shown below is an example where the promise has fulfilled and our data would be output to the console. In place of this console log is where we could place functionality regarding that data including returning that data from our API to a client.

getData().then((data) => {
    console.log(data);
});
Enter fullscreen mode Exit fullscreen mode

.catch()
Similarly to using an error first callback, a .catch(next) after a promise will invoke the next error handling middleware function in the chain and respond with an error message explaining what went wrong. So using the example below, if there was an error getting the data the promise would be rejected with an error, and next would invoke the next error handler with that error.

getData().then((data) => {
    console.log(data);
}).catch(next);
Enter fullscreen mode Exit fullscreen mode

So using promises can streamline building a server using express, and will hopefully make your code easier to follow. Once you've got a grip on using promises regularly they become easy to implement and will ultimately make your backend code better.

Examples of some of my apis can be found on my gitHub:

https://github.com/alexandertrout/songgame - A song guessing game that uses express and EJS to present views to the user. This game is also hosted on heroku and can be played at https://pickthefakesong.herokuapp.com/.

https://github.com/alexandertrout/alex-be-nc-news - A more complex, reddit style backend that will allow users to post articles, comments and votes.

Top comments (0)