Vaccination API — MERN

Cris Ferreira Pires
2 min readMay 17, 2021

Imagine a phone app that would tell you if the people around you (who would also have the app) are or not vaccinated. This API would help the app off load some of the processing, and ease the deployment of new features.

For the preparation steps we are going to need an account on mongodb.

Then in its dashboard go to connection and allow all ips to access it with 0.0.0.0 later when you put it into a specific server you can change it to the servers ip, for testing purposes this will be helpful as you won’t be locked out by a simple network change.

Now the packages we are going to need:

npm i -s express swagger-ui-express cors mongoose

Now we will start up a nodejs server as usual, then we will add the mongodb connector (mongoose) into the listen() middleware.

Like so:

We will use 2 collections, one for the users (Authentication) and another for the actual data.

For that we will need two models:

Both models need their middleware exposed so at the end we need to had the equivalent of the following for each model:

We will be using a custom token authentication method.

For that we will create a file named classes and there we will add 2 functions and a class with some more functions.

The class will be responsible for creating said token and comparing it to the data on the db when logging in.

This will not be the most secure as it will be prone to sniffer attacks while sending the passwords in plain text to the server. Although this is a problem on the client side meaning its up to the client to keep is own network free from sniffers it can be solved with a two factor authenticator. But for the purpose of this we don’t need to go that far.

So here is the code for that class and functions.

We will be calling this on their separate public endpoints.

Expecting that you can already create the server and connect it to your mongodb.com account using mongoose we will skip this part. (github link in the end if you need it)

I have already explained how to use swagger with the swaggerJSdoc module, but if you use the online swagger editor and then export the contents in json you skip this module entirely.

We will still be needing the swagger-ui-express module to create in-browser testing tool.

This example there is a couple of function that almost every endpoint uses.

They are functions that grab data from the db.

Now the actual authentication endpoint:

Now an example of a endpoint that uses those “main” functions:

So the endpoint dayX (vaccines on a certain day), it returns the ammount of vaccines in a specified and an array of all the vaccines.

If need to look at the rest of the code, it can be found here.

--

--