GetCoding
  • Home
  • Courses
  • Contact
Category:

JavaScript

BlogFeaturedJavaScriptNodeJSProgrammingTutorial

Create a RESTful API in NodeJS

by Matt Heff 11 months ago
written by Matt Heff

Ever wanted to create your very own API or do you just need some syntax for something that you are currently working on? Well we have you covered!

Tools you will need

  • Visual Code
  • Command line
  • Node / npm installed
  • Postman ( or some way to interact with the API)

Navigate to the directory you want to set up this project in

cd /home/heff/Code/NodeJS/ApiTutorial-Simple
npm init
npm install express cors
code .

Create Products.JSON

Create a file name products.json in the root directory and put the following JSON into it, this is a simple product database that we will read/update/create/delete ( get, put, post, delete ).

I have no intention of permanently altering this data, we will load it into the memory of the service and then modify it but after the service is terminated nothing will be retains. This is especially helpful once we start deleting.

[
  {
    "id": "Prod1",
    "name": "Online Product #1",
    "type": "online",
    "qty": null,
    "price": 10.5
  },
  {
    "id": "Prod2",
    "name": "Shipping Product #2",
    "type": "physical",
    "qty": 55,
    "price": 17.5,
    "shipping_price": 10
  },
  {
    "id": "Prod3",
    "name": "Online Course Product #3",
    "type": "physical",
    "qty": 55,
    "price": 17.5,
    "shipping_price": 10
  }
]

Create a Server.js file

Create a server.js file and this is the one we will be having node execute for us we will put together in sections and test along the way the sequence will be

  • Load the Products Data
  • Initialise the API Service
  • Create GET
    • Get All
    • Get by ID
  • PUT
  • POST
  • DELETE

ok now we are ready to GetCoding!

Load the Products Data

Run: node server.js

let products = require("./products.json");

console.log(products)

use the command node sever.jsAfter that you should see the products JSON object written to the console like in the image below

Great! Now lets make a service that will listen to us

Initialise the API Service

Add the following code to your server.js file what we are doing here is getting our service setup and configured so it will sit and listen for instruction i have included some CORS handling incase anyone tries to do test this via their browser console instead of postman

const express = require("express");
const cors = require("cors");
const app = express();

var corsOptions = {
  origin: "http://localhost:9999",
};

app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));


////////////////////////////////////////
//Insert GET/PUT/POST/DELETE functions in this section

//Get functions
app.get("/product", function (req, res) {
  res.json(products);
});

app.get("/product/:id", function (req, res) {
  let item = products.find((product) => product.id === req.params.id);
  res.json(item);
});

//put functions

// post functions

// delete functions

////////////////////////////////////////


var server = app.listen(9999, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log(`Simple API listening on host: ${host} with port: ${port} `);
});

if you run this now you will have a service start up and sit there listening on port 9999, how cool is that!

You can use postman now to perform a get on

  • http://localhost:9999/product
  • http://localhost:9999/product/Prod1

Postman gives the following results,

At this stage you now have a very basic API! If this is your first time congratulations! I hope you remember me!

Try out looking for Prod2 & Prod3 even a Prod4 that does not exist to see what happens.

PUT

Add the following code under the comment //PUT functions

Here we need to make sure the data send to us is not empty, from there we look for where our item is in the product list and once we find it ( assuming we do ) we will update it with the JSON sent, the whole record must be sent, sending only partial data will result in data missing.

app.put("/product/:id", function (req, res) {
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!",
    });
  }
  console.log(req.body);
  //find the product by id and update it 
  let index = products.findIndex((x) => x.id == req.params.id);
  products[index] = req.body;

  console.log(products);
  res.json(products);
});

POST

Add the following code under the comment //POST functions

Here we need to make sure the data send to us is not empty, from there we look for where our item is in the product list and if we don’t find it we create a new one otherwise let them know one already exists.

app.post("/product", function (req, res) {
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!",
    });
  }
  // check to see if there is a product that exists with that id
  let index = products.findIndex((x) => x.id == req.body.id);
  if (index !== -1) {
    res.status(400).send({
      message: `Item already exists wth the ID: ${req.body.id}`,
    });
  }
  //add new product to the list 
  products.push(req.body);
  res.json(products);
});

DELETE

Add the following code under the comment //DELETE functions

The code below looks for a matching product with the value that was passed to it and if it finds one it will remove it from the product list.

app.delete("/product/:id", function (req, res) {
  //here we remove the product from our list if it is found
  let tmp = products.filter((item) => item.id !== req.params.id);
  products = tmp;
  console.log(products);
  res.send(products);
});

GITHUB

You can find the code for this in github as well as a collection from postman so you can test out the API

GitHub Repo

NodeJS.postman_collectionDownload
11 months ago 0 comment
TwitterLinkedin
BlogJavaScriptProgramming

How to Add Hours to a Date Object in JavaScript

by Matt Heff 11 months ago
written by Matt Heff 5 read

As if programming and dealing with dates did not have enough headaches that come from timezones, daylight savings, leap years the JavaScript Date API does not offer us a way to add hours to Date objects.

Fortunately with this tutorial we are going to do this ourselves and do it a couple of ways.

Method 1: Create a function ( use Date.setHours() )

function addHours(dateObj, hours){
   //We create a new Date Object so that we dont alter the one passed into the function (this is a pure function )
   const dateUpdated = new Date(dateObj.getTime());
   dateUpdated.setHours( dateUpdated.getHours() + hours);
   return dateUpdated;
}


const dateDemo = new Date('2022-06-22T12:00:00.000Z'); 
console.log(dateDemo); //2022-06-22T12:00:00.000Z

let dateModified = addHours(dateDemo,1)
console.log(dateModified); //2022-06-22T13:00:00.000Z

dateModified = addHours(dateDemo,3); //Original Date is not modified
console.log(dateModified); //2022-06-22T15:00:00.000Z

dateModified = addHours(dateModified,3)
console.log(dateModified); //2022-06-22T18:00:00.000Z


In the above function we create the variable dateUpdated and create a new Date Object so that the dateObj that is passed does not get modified. The Date.setHours() function updates the object, the above implementation is a pure state function, this will help prevent unexpected behaviours.

Method 2: Use NPM Package date-fns

If you are inclined to use NPM packages then this is a great one to make dates a little nicer in JavaScript or NodeJS

So this assumes you have NodeJS installed or an IDE where you can install NPM packages, you can install the package via the command below. We are only going to focus on demonstrating the addHours functionality.

npm install date-fns

import { addHours } from 'date-fns';

const date = new Date('2022-06-22T12:00:00.000Z');

//Add 1 hour to the existing date
let newDate = addHours(date, 1);
console.log(newDate); // 2022-06-22T13:00:00.000Z

//Add 2 hour to the already updated date
newDate = addHours(newDate, 2);
console.log(newDate); // 2022-06-22T15:00:00.000Z

//Original Date Object has not been modified
console.log(date); // 2022-05-15T12:00:00.000Z

The NPM package offers loads of date functions if you are in a situation to use this i would recommend it, anything that makes our lives easier with dates is worthwhile!

A few examples of date-fns functions

addDays, addHours, subHours, addMinutes, subMinutes, addSeconds, subSeconds, subDays, addWeeks, subWeeks, addYears, subYears,

Code Repo

Github: Example 1

Github: Example 2

11 months ago 0 comment
TwitterLinkedin
BlogJavaScriptProgrammingTutorial

Create your own JSON.stringify() function

by Matt Heff 11 months ago
written by Matt Heff

If you have been around the traps the JavaScript for a while you will know JSON.stringify(), you may have have even used it to compare objects, make clones of objects and arrays or even work with RESTful API’s. Using it is not enough of people like you and me, we must pull it apart, look under the hood and then make our own version of it.

This is a two way operation JSON.stringify() will turn objects into strings the inverse of that is JSON.parse() which will objectify strings. This is a good type of objectification.

Example of JSON.stringify() and JSON.parse()

const demoJsonObj = {
  mission: "CreateJsonStringify",
  timeToComplete: 10,
  useExistingFunction: false,
  reasons: ['Inquisitive','Masochist','Bragging Rights'],
  toolsAllowed:{
    language: "JavaScript",
    enhancer: "Coffee",
    motivation: "Binaural Beats",
    alternativeMethod: "Youtube - Check out my video tutorial"
  }
};

console.log(JSON.stringify(demoJsonObj));
// Output
//{"mission":"CreateJsonStringify","timeToComplete":10,"useExistingFunction":false,"reasons":["Inquisitive","Masochist","Bragging Rights"],"toolsAllowed":{"language":"JavaScript","enhancer":"Coffee","motivation":"Binaural Beats","alternativeMethod":"Youtube - Check out my video tutorial"}}


//Test the string is valid by parsing it back
console.log(JSON.parse(JSON.stringify(demoJsonObj)));

Ok that was nice and easy, we can pass the JavaScript Object and get a JSON String. Job done for 99% of folks out there. Not for us! Roll up your sleeves as we are only just about to GetCoding!

Where to begin?

Shall we jump in and start bashing out some code to start with? Or shall we have a think about what we are going to be doing here?

I’d start bashing on the keyboard, only to get 5 mins and and be like hmmmm. So here I am faced with the question how to we take a JSON Object and convert it into a JSON String?

What is a JSON Object? What can be in it? Do we need to cover all cases? Are there any weird things that could happen?

How do I go through each object item? What if it is an array of items? What if there is a object in the object? What if there is a array in the object or in the objects object array . . . . .does that even make sense?

Hmmm thats a lot of questions, Lets start with what is a JSON Object W3schools and MDN — I found the W3Schools page better it gave me a nice convenient list of what are valid JSON types

  • string
  • number
  • object
  • array
  • boolean
  • null

It also gave an example on how to loop through a JSON object. We are definitely going to need this!

//looping through the JSON Object using the object above
//variable is -- demoJsonObj -- just to remind you

for (const item in demoJsonObj) {
  console.log(item);
}

//This is handy, we can loop through the object and output each item. 

//Can you think how else we can use it?

This is excellent at least we have a starting point now, we know a bit about JSON and we definitely know that we need to handle these types. At some point we are going to need to check if the data we are looking at so lets make that code now.

Here your style preference can change how you write this, you could use if statements, switch or functions for each data type and return true/false.

function isStr(val){
    return typeof val === 'string';
}

function isNum(val){
 return typeof val === 'number';
}

// when checking a object we must ensure it is not null and not an array. Both null & Array has typeof object in JS
function isObj(val){
    return typeof val === 'object' && !Array.isArray(val) && val !== null;
};

// We need to check that it is an Array and also of type object

function isArray(val){
    return Array.isArray(val) && typeof val === 'object';
};

function isBool(val){
  return typeof val === 'boolean';
}

function isNull(val){
    return typeof val === 'string';
}

So that handles our Data types listed by W3Schools, there was a bit of knowledge I did have about type of for null and arrays returning as objects. If you didn’t have that you may get some weird results.

So now lets build out some code that will get a JSON Object and then loop through each item and check its type.

function CustomJsonStringify(obj){

 //check if it is string
  if(isStr(obj) ===true){
    return `"${obj}"`
  }
  if( isNum(obj) || isBool(obj)){
    return `${obj}`;
  }

  if(isArray(obj)){
    let arrayString = "";
    obj.forEach((val) => {
      arrayString += CustomJsonStringify;
      arrayString +=','
     });

    return `[${arrayString.replace(/,*$/, '')}]`;
  }




  // loop through each item in the object and handle it
  if(isObj(obj)){

        let objectString = ""; 
        let keys = Object.keys(obj);

    keys.forEach((key) => {
      let val = obj[key];
      objectString += `"${key}":${CustomJsonStringify(val)},`;

     });
     return `{${objectString.replace(/,*$/, '')}}`;

    }
  }


console.log(CustomJsonStringify(demoJsonObj));

//Pass string into JSON.parse() to check it is valid
console.log(JSON.parse(CustomJsonStringify(demoJsonObj)));

Conclusion

Here we have a basic stringify function , there are fringe cases which are not handled. and to make it more robust and a 1:1 equivalent we would need to add handling for

  • functions, undefined and Symbol values
  • Dates
  • NaN, Null and Infinity
  • Undefined

Hope this has been helpful to you, Ill have a youtube video going through this in the near future!

Code on GitHub

11 months ago 0 comment
TwitterLinkedin

Recent Posts

  • How to read environment variables with Node.js
  • AI – What is Natural Language Processing (NLP)
  • Web3 RPC Nodes
  • Drupal 9 – Custom module development – Simple Module
  • Create a RESTful API in NodeJS

About

About

GetCoding is a blog and tech educational resource specialized in programming, Web3, blockchain and everything in between. Follow us to help you understand and GetCoding!

Stay Connect

Twitter Linkedin Youtube Email

Popular Posts

  • 1

    Writing your first Ethereum Smart Contract

    12 months ago
  • 2

    Create your own JSON.stringify() function

    11 months ago
  • 3

    Introduction to JSON with Examples

    12 months ago
  • 4

    Install Metamask and get Testnet Tokens

    12 months ago
  • 5

    What is an AMM ( Automated Market Maker)

    12 months ago

Categories

  • Blockchain (4)
  • Blog (7)
  • Featured (3)
  • Learning (1)
  • Programming (5)
    • JavaScript (3)
    • NodeJS (1)
    • PHP (1)
  • Technologies (2)
    • Drupal (1)
  • Thought Provoking (1)
  • Tutorial (6)
  • Uncategorized (3)

Recent Posts

  • How to read environment variables with Node.js

    2 months ago
  • AI – What is Natural Language Processing (NLP)

    6 months ago
  • Web3 RPC Nodes

    10 months ago

Featured Posts

  • How to read environment variables with Node.js

    2 months ago
  • AI – What is Natural Language Processing (NLP)

    6 months ago
  • Web3 RPC Nodes

    10 months ago

Subscribe Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

  • Twitter
  • Linkedin
  • Youtube
  • Email
GetCoding
  • Home
  • Courses
  • Contact