Building a Node.js E-Commerce API for noobs — Selling Stuff

Flo Sloot
Flo Sloot
Jul 22, 2017 · 4 min read

Commander,
basic structure is up and running!

Now let’s shop!!

First of all you should create a store at Moltin(if not done already).
Then add at least one Product to your stores stock (note: this products status must be set to live)

Alrighty, now let’s try and fetch our first product!!

Moltin is pretty forward.. so with our authentication middleware already setup we can simply create a new handler that fetches all products

// in api/controllers/moltin_requests.js// extract the Moltin object we added to the request
// call moltin and fetch all products we have in the specific store
// send it as response back to the client
function getProducts(req, res) {
let { Moltin } = req;
Moltin.Products.All()
.then(product => {
res.json(product)
})
}
// export the function
module.exports = {
getProducts
};

Almost ready to go!
Just need to tell the swagger.yaml that we want to set up a new route

...
paths:
/products:
x-swagger-router-controller: moltin_requests
get:
description: Returns Products to caller
operationId: getProducts
parameters: []
responses:
‘200’:
description: Success
schema:
# renamed the helloWorldResponse ;)
$ref: ‘#/definitions/StandardResponse
default:
description: Error
schema:
$ref: ‘#/definitions/ErrorResponse’
...definitions:
StandardResponse:
type: object

ErrorResponse:
required:
- message
properties:
message:
type: string

Is it working?
At this point I’d recommend you download Postman and do http requests from there..

But of course you can go with the command line as well!

$ curl localhost:10010/products 
# returns a big object containing all of your products

Ha! At this point we could already show our customers our products!!

Yet I’d like to sell those products as well.. So we need an /addToCart route + function

soo let’s update our swagger.yaml real quick

...'/addToCart/{productId}':
x-swagger-router-controller: moltin_requests
get:
description: Returns Products to caller
operationId: addToCart
parameters:
- name: productId
in: path
description: ProductID
required: true
type: string

responses:
'200':
description: Success
schema:
$ref: '#/definitions/StandardResponse'
default:
description: Error
schema:
$ref: '#/definitions/ErrorResponse'
...

so we got our addToCart route and gave it a path parameter, productId.

Trivial, right?

moltin_requests.js:

...
// define an alternative ID (for testing only) in case there is no
// productId passed as param
// extract the url param "productId" (if given)
// add the product x3 to our cart
function putToCart(req, res) {
let { Moltin } = req;
let alt_Id = '18f41b76-e744-42ad-8f53-3daef70b3b51';
let productId = req.swagger.params.productId.value || alt_Id;

Moltin.Cart.AddProduct(productId, 3)
.then((item) => {
console.log(`Added ${item.data[0].name} to your cart`);
res.json(item)
});
}
...module.exports = {
getProducts,
addToCart
};

To test this route I need to head back to Postman and call the /products again; from the response I can just take the product_id attribute and append it to the route

$ curl localhost:10010/addToCart/ProductIdYouChose
# voila returns the items in you just added

Working like a charm!
Last thing do to is the checkout so the customer can buy the stuff he just added!

This one again is so straight forward.. like I said Moltin ist just great for those things!
In this case I’m chaining the “create an order” and “pay the order” into one big process for simplicity.
Actually looks like a lot of stuff.. But it’s basically just customer and credit card data

// moltin_requests.js...// define an order object including the customer + addresses
// define the payment gateway and the used credit card
// note: credit card number is a dummy number! You can use it // without worrying about anything!
function checkout(req, res) {
let { Moltin } = req;
Moltin.Cart.Checkout({
customer: {
name: 'John Doe',
email: '
john@doe.co'
},
billing_address: {
first_name: 'John',
last_name: 'Doe',
line_1: '123 Sunny Street',
line_2: 'Sunnycreek',
county: 'California',
postcode: 'CA94040',
country: 'US'
},
shipping_address: {
first_name: 'Jon',
last_name: 'Doe',
line_1: '123 Sunny Street',
line_2: 'Sunnycreek',
county: 'California',
postcode: 'CA94040',
country: 'US'
}
})
.then(order => {
Moltin.Orders.Payment(order.data.id, {
gateway: "stripe",
method: "purchase",
first_name: "John",
last_name: "Doe",
number: "4242424242424242",
month: "09",
year: "2017",
verification_value: "123"
})
.then(payment => {
res.json(payment)
})
.catch(err => {
console.log(err);
})
})
}
module.exports = {
getProducts,
putToCart,
checkout
};

one more time the swagger.yaml needs an update; one new route, no parameters, nothing special!

.../checkout:
x-swagger-router-controller: moltin_requests
get:
description: Creates an Order
operationId: checkout
parameters: []
responses:
'200':
description: Success
schema:
$ref: '#/definitions/StandardResponse'
default:
description: Error
schema:
$ref: '#/definitions/ErrorResponse'
...

That’s it!

Before testing the new Route, I’ll need to:
- head over to Stripe
- create an account (including activating + confirming itvia SMS (!) which might be a bit exhausting, yet necessary for the payment stuff to work)
- put your Stripe secret key in the Moltin Forge Gateway settings and enable it
- ready to roll!!

$ curl localhost:10010/checkout #success unless it threw an error

Back over in the Stripe dashboard I can see whether or not the payment was processed..

Pronto!

Yes, Sir! Just paid the first order!

A fully functioning e-commerce backend

Alright! That’s it for the backend side!

From now on I’m going to build the client side in React.js and will come back later to do some adaptions and improvements on the API..

Flo Sloot

Written by

Flo Sloot

in love with JS, Freelancer, Hamburg ⚓️

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade