Giter Site home page Giter Site logo

node's Introduction

Order API

Node/Mongo API in a Container
(based on: http://adrianmejia.com/blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/ and https://codeforgeek.com/2015/08/restful-api-node-mongodb/)

###### Install  Node with Brew:

1. If node is already installed manually (not using brew) uninstall as per https://gist.github.com/TonyMtz/d75101d9bdf764c890ef
	(NOTE: after uninstalling and reinstalling node i had issues with npm which I fixed by cleaning everything up based on http://stackoverflow.com/questions/11177954/how-do-i-completely-uninstall-node-js-and-reinstall-from-beginning-mac-os-x)

2.  Install with brew (if not already) by running

brew install node

	( I ran into some issues… following blog helped resolve: http://stackoverflow.com/questions/31374143/trouble-install-node-js-with-homebrew )

###### Install MongoDB (https://docs.mongodb.com/v3.0/tutorial/install-mongodb-on-os-x/)

4. Install mongodb with brew

brew install mongodb

5. Create directory needed by mongo process (mongod) to write data

mkdir -p /data/db

6. Change ownership so mongod can write to it

sudo chown -R luisweir:staff /data

7. Run mongo

mongod

###### Create MongoDB

8. Start mongo DB

mongod

9. Open a new terminal and run command to open mongo CLI

mongo

10. To create a new DB run

> use orders_db
> show dbs
> a = { "order" : { "order_id" : "1073459962", "status" : "created", "created_at" : "2016-04-01T12:00:10-02:00", "updated_at" : "2016-06-06T15:48:20-04:00", "total_price" : 50, "currency" : "EUR", "customer" : { "customer_id" : "76422323213", "first_name" : "Paul", "last_name" : "Norman", "phone" : "+44 (0) 5555-555-555", "email" : "[email protected]" }, "address" : [ { "type" : "billing, shipping", "city" : "Cambridge", "county" : "Cambridgeshire", "postcode" : "CB4 4SS", "country" : "Great Britain" } ], "line_items" : [ { "line_id" : "1245555432", "product_id" : "1071823172", "product_name" : "Billy Table White", "quantity" : 1, "price" : 50, "currency" : "EUR", "grams" : 8000, "sku" : "BILLY2009WHITE" } ] } }
> db.orders.insert()
> show dbs
> db.orders.find()
> db.orders.find({ "_id" : ObjectId("578639323179eba600803d19") })

NOTE: .save() can also be used which is basically an upsert

(Note: insert a record otherwise db won’t show info on: http://www.tutorialspoint.com/mongodb/mongodb_create_database.htm and http://www.tutorialspoint.com/mongodb/mongodb_drop_database.htm)

###### Create project package and set up server
11. Create project folder

mkdir <path>/<project> ie. mkdir -p $HOME/node/orders_api

11. Cd into project folder (ie. $HOME/node/first_api) and create Node project by running:

npm init

This will create a package.json, in my example like this:

{
  "name": “oders_system_api”,
  "version": "1.0.0",
  "description": “IKEA orders system API“,
  "main": "server.js",
  "scripts": {
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/luisw19/node.git"
  },
  "keywords": [
    "Node.js",
    "git"
  ],
  "author": "Luis Weir",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/luisw19/node/issues"
  },
  "homepage": "https://github.com/luisw19/node#readme"
}

###### Install required modules in project -not globally (express, mongoose, body-parser)

12. Install express locally on project (more info on https://codeforgeek.com/2014/10/express-complete-tutorial-part-1/)

npm install --save express

13. Install mongoose in project (more info on http://mongoosejs.com/)

npm install --save mongoose

(the --save is so mongoose is added to the dependencies in the package.json -otherwise is just temporarily added)

14. install body-parser

npm install --save body-parser

14. install modules by running (note sure why is this required??)

npm install

###### Test server

16. Create server.js and add basic code

var express     =   require("express");
var app         =   express();
var bodyParser  =   require("body-parser");
var router      =   express.Router();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));

router.get("/",function(req,res){
    res.json({"error" : false,"message" : "Hello World"});
});

app.use('/',router);

app.listen(3000);
console.log("Listening to PORT 3000");

17. Run to test node app

npm start

Open a new terminal and test URL with curl (or use postman or simply use the browser)

curl http://localhost:3000


###### Create API model including DB schema and connection

17. In project folder create a new folder called model

mkdir model

18. Inside the model folder create mongo.js

touch mongo.js

19. Add code accordingly. Of most important is that the mongoose schema is done properly… (see file in project)

20. Back in root project folder add the API code to server.js

###### Create docker container for API (based on https://nodejs.org/en/docs/guides/nodejs-docker-webapp/)

20. install docker. As am using Mac and "brew cask" installation is simple

brew cask install docker

(alternatively docker can be downloaded from the official website https://docs.docker.com/engine/installation/)

21. Create a docker file inside the node application directory

touch Dockerfile

22. Edit the file as following:

FROM node:argon

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 8080
CMD [ "npm", "start" ]

23. Build the container

docker build -t luisw19/orders_api

24. Push the docker image to docker hub

docker login --username=<username>
docker push <image name>

###### Install docker compose and create compose file

23. Install docker compose (am using mac so it's straight forward. This can also be downloaded from official page: https://docs.docker.com/compose/)

brew install docker-compose

24. Create docker compose file in the parent directory

touch docker_compose.yml

25. Add content as following:

version: '2'
services:
  order_api:
			#Uncomment next line if you wish to build from docker-compose
			#build: ./orders_api
			image: luisw19/orders_api
      depends_on:
        - mongo_db
      ports:
        - "3000:3000"
      command: npm start
      links:
        - mongo_db

  mongo_db:
      image: mongo:3.0.2

26. Build the container (Only if building from source code -otherwise next step is all needed to run)

docker-compose build

27. Create and start the containers

docker-compose up

(after initial create, 'docker-compose start / stop' can be used instead)

28. Test the API using the postman collection: orders_api/ordersSystemAPI.postman_collection

node's People

Contributors

luisw19 avatar hanskarlsson avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.