If you’re new to Node.js, Couchbase or both, you’re about to level up your skills.
Today I’ll show you how to build a minimal REST-based application for retrieving documents from Couchbase using Node.js and Express.
This post continues my introductory series on using Node.js with Couchbase (including last week’s post on async functions).
In today’s post, we’ll build on my previous examples of using Node.js and Couchbase, so check out those two earlier articles if you haven’t already. I’ll also assume you have basic familiarity with JavaScript, Node.js and NoSQL document databases.
Get the Express Module
Starting from where we left off last week, we can add a web-based REST interface to help isolate your web application from the database. To do this, you need the Express module. Install it and add it to your package dependencies using:
1 |
npm install express --save |
To test that Express is installed correctly, you can build a small application (app.js
) that creates the HTTP server and returns a Hello World
value. For later convenience, wrap it with an async
function as you can see below:
1 2 3 4 5 6 7 8 9 |
var app = require('express')(); const couchbase = require("couchbase"); async function main(){ app.get('/', (req, res) => res.send('Hello world!')); app.listen(3000, () => console.log('Listening on port 3000')); } main(); |
Launch it and access it through a web browser on port 3000. It should look something like this image below:
1 |
node app.js |
Congratulations! You’ve successfully built your first Express app, albeit a small one.
Building the Application
The application has three components:
-
- Route management
- Database connectivity
- The HTTP server layer
Add an Express Route for Data Retrieval
The application intercepts and serves the root path /
. We’ll create a route called get
for retrieving a specific document. The REST user provides a document ID and returns the JSON document using the following syntax:
1 |
localhost:3000/get/[documentID] |
The function for creating that route includes two important objects – req
(request) and res
(results) – which we’ll use for getting data to and from the app. See the example below:
1 2 3 4 5 6 7 |
app.get('/get/:docid', runAsync(async (req, res) => { var docid = req.params.docid; var docjson = await getDoc(docid, function(err, result){ res.json(result.content) }); })); |
Notice that the :docid
parameter becomes a variable you can access through the request object: var docid = req.params.docid
. It is then passed to the getDoc()
function which we’ll cover in a minute.
The application also has this convenience function below for running everything asynchronously:
1 2 3 4 5 6 |
function runAsync (callback) { return function (req, res, next) { callback(req, res, next) .catch(next) } } |
The function above wraps your calls nicely but I won’t explain it in detail here (maybe in a future post). For now, just add it to the script.
Add a Document-Retrieval Function
The database connectivity in the script is as basic as the earlier posts in this series. Select a Bucket and Collection, then use the get()
function to retrieve a document based on a given document ID.
First comes the connectivity piece. If you have a different username, password, Bucket or Collection, substitute it here:
1 2 3 4 5 6 7 |
var cluster = new couchbase.Cluster("couchbase://localhost", { username: "Administrator", password: "Administrator" }); var bucket = cluster.bucket("travel-sample"); var collection = bucket.defaultCollection(); |
Note that I host the app on a server on my network that also hosts the database (localhost
). But I access the app from my dev laptop, so in the web browser samples below you’ll see the IP address 192.168.0.158
hitting the REST API.
Now let’s look at the main function for document retrieval:
1 2 3 4 5 |
var getDoc = async (key) => { var result = await collection.get(key); console.log(result) return result }; |
We use the collection
variable, which is the Couchbase database connection to the Bucket, etc., defined earlier. The get()
function takes one input: a string with a document ID. For example, we used hotel_5336
in the previous posts in this series.
Running the REST API
The HTTP server for the REST API still needs to run as well. It hasn’t changed since the first test app in this post:
1 |
app.listen(3000, () => console.log('Listening on port 3000')); |
That covers all the code; a full listing is included below. Now you can run the server as before ( node app.js
) and provide a document ID through the web browser – e.g., http://192.168.0.158:3000/get/hotel_5336
.
The requested document is printed in the console and returned to the browser:
Full Code Sample
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
var app = require('express')(); var couchbase = require("couchbase"); async function main(){ app.get('/get/:docid', runAsync(async (req, res) => { var docid = req.params.docid; var docjson = await getDoc(docid, function(err, result){ res.json(result.content) }); res.json(docjson.content); })); app.listen(3000, () => console.log('Listening on port 3000')); function runAsync (callback) { return function (req, res, next) { callback(req, res, next) .catch(next) } } var cluster = new couchbase.Cluster("couchbase://localhost", { username: "Administrator", password: "Administrator" }); var bucket = cluster.bucket("travel-sample"); var collection = bucket.defaultCollection(); var getDoc = async (key) => { var result = await collection.get(key); console.log(result) return result }; } main(); |
Conclusion
In future posts I’ll cover how to build a database query, conduct full-text searches and more – all using different Express routes.
In the meantime, take your application to the next level by doing some of the following:
-
- Add error capturing.
- Create a authentication system, such as JSON Web Token or JWT (see this travel-sample demo project).
- Read up on other Couchbase Node.js SDK functions you can add to the app.
Catch up with the rest of the Node.js + Couchbase how-to series:
-
- How to Get Started with the Node.js SDK for Couchbase
- How to Create Async Get/Upsert Calls with Node.js and Couchbase
- Build a REST-Based Application with Node.js, Express and Couchbase
- How to Query JSON Data Using N1QL for Node.js and Couchbase
- How to Add Full-Text Search Functionality to Your JavaScript App
[…] post Build a REST-Based Application with Node.js, Express and Couchbase appeared first on The Couchbase […]