Part 4: Let's save data to a database!
Recap of Last Time
- We built a Node.js app utilising the built-in http.createServer
- Starts an HTTP server and serves static files out of the ./public directory
- We implemented dynamic routing with a handy easy to define syntax
- Our routes use Handlebars template files to display content that's not static
- We also wrote a super simple form data parser that will allow us to capture user data
A reminder what we're doing
Ever wanted to remind yourself of something, out of the blue? Well, we're building a quick tool to do that!
form parser package is released!
Let's implement the package then!
* also, delete the lib/formdata.js file
Time for the main event!
We're going to be using PostgreSQL in our app.
Look at these awesome logos...
⬅️ ⬅️ ⬅️ Slonik
A few more things...
- Adding package-lock.json to .gitignore
- We're going to write queries in *.sql files, so let's add that to the npm run start command
Just one more dependency...😉
- Brian Carlson's "pg" module is how we're going to access Postgres
- The module also comes with connection pools built in!
An initialiser + env variable
Get a PSQL database (Heroku, local, etc) + plug it in here:
Let's make sure it gets initialised!
We want to use the db throughout our app's routes, so let's make sure it gets initialised and passed into the server!
Pass the db object around
We are mostly going to use this "db" object in routes, so it needs to be able to access them!
A db needs a schema!
No ORM models, let's just write some SQL:
We need to init the db...
We should write a runnable script to do this for ourselves:
An executable file with no extension is fine, as long as the first line contains a "hashbang" telling your shell how to execute it. We want Node.js to run it, so here's the Node hashbang:
...And the rest of our db init script
let's capture forms!
Forms are also a bit of a rabbit hole:
Db actions as...actions 😉
- An "action" (in my own terms) is a database activity (create/read/update/delete).
- We should separate our db logic from the rest of our app, or else things are going to get messy fast!
Creating a reminder action
Note we're using parameterised queries to avoid SQL injection:
Use the action in your route
That's all, let's stop here...
Before our brains melt!
Well done, you made it! 👏👏👏
See you next time where we look at The frontend and serving assets in a pipeline.
Please don't hesitate to contact me or leave feedback on the course:
See today's code: https://github.com/frameworkless-js/remind.ist/tree/stage/4
See today's lesson running live: https://part4.remind.ist
frameworkless.js -> Part 4
By Mike Timofiiv