DEV Community

Cover image for Day two - envs, directory structure and db connections
Rhymes Toasterface
Rhymes Toasterface

Posted on • Edited on • Originally published at triplejdeveloping.com

Day two - envs, directory structure and db connections

4/5/20 Step one. Still

This evening, I did a bit more work - I started on the database connection and functions. Brave, huh?

First things first - I found the connection details from Mongo Atlas for the new cluster I had created previously. Then, I set up some environment variables in my server terminal:

I edited the .bash_profile using the text editor of my choice (nano, what of it?). I added a few exported variables in there:

  • export MONGO_USER=<user name from mongo>
  • export MONGO_PASSWORD=<password from mongo>
  • export MONGO_PREFIX=<from the connection string>

If you choose this route (I chose it because it is slightly more secure than plain text strings in my code base - I imagine it will go up to github at some point), don't forget to source ~/.bash_profile after you have updated and saved it - this will make these new environment variables available to you on the server.

Next, I created a bit of a file structure. By the way, it is probably time to mention I decided to use TypeScript for this project. We use it at work, I like it, maybe you will too! Anyway, I have a main index.ts in the root directory. I then have a src directory as well. Within that, I have a db directory, recipes directory and an interfaces.ts file.

Inside the db directory, I have an index.ts and a client.ts. In a brave move, I am going to introduce some images. This will give you a better idea of the starting structure (this may be refactored later, but I am making hay while the mental sun is shining):

structure

You can see I also added a recipes directory with an index of its own as well.

Inside the client file, I set up a Mongo connection using those environment variables I set in the server earlier:

connection

There is nothing out of the ordinary here - I followed the Mongo docs for connecting with the nodejs driver.

I guess the only sadness is not using async/await, but I am too tired to think about that. This works, and a refactor later won't hurt as both will still return a promise-y value. Let's just be happy there are no callbacks...

I did it this way because I would have a reusable connection that I could use without having to reference the variables etc. every time. You might want to do it a different way, but I have written and reusable connection this way before and like it. shrugs

You can see the db functions I added to use this connection in the next instalment. Same Bat-time, same Bat-channel.

Top comments (0)