C.R.U.D.

beComing the most Rad, Ultimate Developer

CRUD apps. What are they? Are they difficult to create?
Backend development can seem scary at first, but once you have a grasp on JavaScript it can be really fun!
Click here to clone the GitHub repo!

WHY CRUD?

CRUD operations are used to make requests for an app or project. They are the way we speak to our database. This article will not cover databases, instead we will be using a local JSON file that we will write to via a NodeJS core module “fs”. This allows for less setup time and quicker learning of CRUD.

HTTP

Hypertext Transfer Protocol is the way we transmit our data/media. This is the root of our CRUD operations and is the way we make our requests.
Click here for more info!

BACKEND BASICS

JavaScript is run in the browser and helps make our websites pop. However, you can use NodeJS as a backend language to communicate with databases. Since databases typically work with objects we’ll need to be sure that we’re comfortable on navigating our way through an object. This includes accessing specific keys/values and creating new objects.
You don’t need to know everything about JavaScript to create a backend project. We’ll be creating functions, using built-in methods, and using conditions!

C.R.U.D. DEFINITIONS

CREATE

The “C” stands for create. This is where we create a new object and add it to our database. We use the POST request to make the call to our database and set our new data.
Click here for more info on POST!

READ

The “R” stands for read. This is where we read the data that we have in our database. We use the GET request to make this call to our database to retrieve this data.
Click here for more info on GET!

UPDATE

The “U” stands for update. This is where we can edit existing objects in our database. We use the PUT request to make the call to our database.
Click here for more info on PUT!

DELETE

The “D” stands for delete. This is where we can delete existing objects in our database. We use the DELETE request to make the call to our database.
Click here for more info on DELETE!

BASIC PROJECT SETUP

I won’t go over every detail of the project setup, but we will need to get a simple server running so that we can write to a local JSON file. We will be using the NodeJS core modules “fs” and “http” which allow us to easily start a local server (http) and write to our local JSON file (fs) instead of setting up an external database.

Step 1)
- create a folder to house all of our files

Step 2)
- create the app.js file

// app.jsconst http = require('http')
const express = require('express')
const fs = require('fs')
const app = express()const server = http.createServer(app)
const port = 3001
// simple function to create a random id
const generateId = () => {
return Math.round(Math.random() * 100000000)
}
// this line is required to parse the request body
app.use(express.json())
/* util functions */
// read the people data from the json file
const savePeopleData = (data) => {
const stringifyData = JSON.stringify(data)
fs.writeFileSync('people.json', stringifyData)
}
// get the people data from json file
const getPeopleData = () => {
const jsonData = fs.readFileSync('people.json')
return JSON.parse(jsonData)
}
/* CRUD Operations go here *
// Create
//
// Read
//
// Update
//
// Delete
//
/* CRUD Operations go here */
server.listen(port, () => console.log(`server is listening on port ${port}`))

Step 3)
- npm init the folder. This will create a package.json file.
- npm i express
— the express framework will allow us to more easily make our requests.

// package.json{
"name": "mod_13_article",
"version": "1.0.0",
"description": "these are not necessary",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "Your Name",
"license": "ISC",
"dependencies": {
"express": "^4.17.3"
}
}

We can now run npm start to run our local server.

Step 4)
- create the JSON file that we will write to whenever we make our requests
- I have called the one in this example “people.json”.
- add an empty array to the file

// people.json[]

We now have everything we need setup to learn the four requests that make up our CRUD app!

C.R.U.D. OPERATIONS

CREATE

We’ll first take a look at using the POST method to create a new Person.
We have to use the .post() method so that the data is being sent to be added to our database. We then use the url endpoint that defines our call, in this case we’re adding to our “people” so we’ll use ‘/people’.
The getPeopleData() function is called to retrieve all of our people.json data. We store this array in a variable so that we can push our new data into it later. The we check to see if the body of the request doesn’t have the “name” key. If it doesn’t then we send back an error. If it does then we’ll continue with the request and build our newPerson. This includes a unique id, the name provided in the request body, and the date it was created.
We finish by pushing our newPerson into the people array and saving our new array by passing it into the savePeopleData() function.

/* Create - POST method */app.post('/people', (req, res) => {
const people = getPeopleData()

if
(!req.body.name) {
return res.status(401).send({ error: true, message: 'Person data is missing name' })
}
const newPerson =
id: generateId(),
name: req.body.name,
createOn: new Date()
}
person.push(newPerson)
savePeopleData(person)
res.send({ success: true, message: 'Person added successfully'})
})

READ

The next request is the GET request! Probably one of the easiest requests to get going. We’ll use the .get() method to retrieve the data that we’re calling for. The url endpoint is going to be the same here with ‘/people’.
Finally, on this one we just call the getPeopleData() function and return the result.

/* Read - GET method */app.get('/people', (req, res) => {
const people = getPeopleData()
res.send(people)
})

UPDATE

Next up is the PUT request. We’ll be adding the “id” parameter to our url endpoint, which will be “/people/:id”. The “:id” allows us to target that specific parameter in our request so that we can find that person.
We make our usual call to get all the people.
The we find the specific person whose data we are trying to update. We check to make sure that they exist. If they don’t we send a 404 response. If they do then we continue and build our request body.
The body includes: the person’s id, their name, and the date they were created. In this example we can update the “name” or the “createdOn” values.
The last part of the request finds that person’s index in the “people.json” array and replaces their values with our updated body. Then we save the updated people data.

/* Update - PUT method */app.put('/people/:id', (req, res) => {
const people = getPeopleData()
const person = people.find(person => person.id === req.params.id)
if (person) {
const updated = {
id: person.id,
name: req.body.name || person.name,
createdOn: req.body.createdOn || person.createdOn
}
const targetIndex = people.indexOf(person)people.splice(targetIndex, 1, updated)
savePeopleData(people)
res.send({ success: true, message: 'People updated successfully!'})
} else {
res.send(404)
}
})

DELETE

Finally we’ll go over the DELETE request. This request is made by using the .delete() method. Once again we’ll be using the same url endpoint with the id.
The next part may take some explanation, but it’ll make plenty of sense afterwards! The filteredPeople variable is created by running the .filter() method on our people array. We then filter out any people (person) that matches the id from our url parameters and add anyone that doesn’t match the id to the new filtered array.
If the original array length and the filtered array length are equal that means that no one was filtered out. This means that the id passed in the url parameters does not exist in our list. We’ll then return a 409 error and let them know that the person does not exist.
Otherwise we just save our new filtered array as our people data.

/* Delete - DELETE method */app.delete('/people/:id', (req, res) => {
const people = getPeopleData()
const id = req.params.id

const filteredPeople = people.filter(person => person.id !== id)
if (people.length === filteredPeople.length) {
return res.status(409).send({ error: true, message: 'Person does not exist'})
}
savePeopleData(filteredPeople)
res.send({ success: true, message: 'Person removed successfully'})
})

C.R.U.D. Apps

I’d venture to say that some of, if not ALL of your favorite apps are CRUD applications. This just goes to show that being able to work with a database is an integral part of having a good, usable app.
This introduction should get you off to a good start or help you understand a concept that you were having trouble with before!

Tip or Quote from Brandon:

Today I have a quote!

“Show me your friends and I’ll show you your future.”

-Unknown

This quote is where my last tip came from. Surround yourself with good people and your future will be good, surround yourself with bad people and your future will be bad.
I wouldn’t recommend you take it 100% literally, but use it as a guide to fill your life with those you believe to be good. Like my last tip, I said we should spend 1/3 of our time with different types of people. Sometimes you can be the good that someone “bad” needs.
You can read more about leadership and how this quote fits in here!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store