Inspired by the use of Node.js and mongoDB in this How To Node article, this tutorial aims to show how BrightstarDB can also be used with Node to create a simple blogging system.
Before starting, ensure you have the following installed;
- ASP.NET MVC
Node needs to be able to access data from BrightstarDB, unfortunately we can’t use WCF under Node, so first of all we will create a simple ASP.NET MVC Rest service which will handle querying and interactions with BrightstarDB.
If you just want to get straight to the code, a download for the source of both projects is available at the end of the post.
Creating MVC Rest interface for BrightstarDB
For the blogging system, our Rest interface will allow the following commands;
- Query a store by name using sparql and returning the results as JTriples
- Post a new article using N-Triples
To get started, first create a new ASP.NET MVC 3 Project. For the Template, choose Empty.
In the project References add a reference to the NetworkedPlanet.Brightstar.dll.
Add a new Controller to the project and name it StoreController.cs. This will serve as the main interface to the BrightstarDB store. We will be using the BrightstarService class to create an embedded client, so we need to include the following using statement in the top of our controller;
Before using the embedded client we need a location for our BrightstarDB data. Open the BrightstarDB management application Polaris and create a new Embedded connection to a location on your computer.
From the Server menu, choose New Store… and call it ‘Blog’.
This will create a new store in our BrightstarDB data folder named ‘Blog’. Back to our MVC project and StoreController.cs, we can now create an embedded client and point it to the path we used in Polaris to create the ‘Blog’ store.
In StoreController.cs add the following property, be sure to use the location of the BrightstarDB data folder and not the location of the ‘Blog’ store folder;
This will create a BrightstarService property called Context which will be using to perform queries and transactions on our ‘Blog’ store.
Next, we first need to be able to query our store, the path to this Rest method will look like this;
Add the following method that accepts a storeName and a query variable;
The above method uses the BrightstarService Context to execute a Sparql query against our named store. The results are iterated by row and the names of the columns and its value added to a Dictionary for each row. A List<Dictionary<string,string>> allows us to return the results using the JsonResult class from ASP.NET in the JTriples format.
Note, the above method uses a Sparql extension method, GetVariableNames, if the method is not available in the release you are using, then add the following code to StoreController.cs and change the above code to use the private mehtod GetVariableNames below.
To support adding new blog posts, we need to add an Insert method. Our insert method will use the Rest path;
In StoreController.cs add the following method;
The above method accepts NTriple data and uses the BrightstarService Context to insert the data into the named store. Because we want to return when the job is finished, we wait until the job status is OK before returning. Of course we are assuming that the NTriples are valid and the job will never fail, this may not always be the case so you would need to check for this.
Lastly, to finish the MVC project we need to add additional routes in Global.asax.cs.
Update the RegisterRoutes method with the following;
This will map our methods in StoreController.cs to the routes specified earlier. Make sure to run the server by pressing F5 and make a note of the port number that the server is using.
Creating the Node blog application
Before starting to write the Node application, first of all we should look at the triples that we will be storing in BrightstarDB for our blog articles.
In the above triple we are defining a ‘type’ named ‘post’ that has a ‘title’, ‘body’ and ‘date’. For the sake of simplicity we will exclude storing comments in this post. To get started with the Node application, as well as Node installed, we need to install Express. To do this, execute the following in a command prompt;
npm install express -g
Note: Installing Nodejs under Windows should add node and npm to the system path, if it doesn’t add the following to your Path system environment variables;
C:\Users\*username*\AppData\Roaming\npm;C:\Program Files (x86)\nodejs\;
With Express installed, we can now create an Express starter project. In a command prompt run the following;
mkdir blog cd blog express -c stylus npm install -d
This will generate an Express application using the stylus css engine, and download any dependancies using npm. To test that the application generated successfully, run node against the main app.js;
You should now be able to access localhost:3000 and see the default express content. We will be creating the following operations in our blog application, these are:
- Displaying all blog articles
- Creating a blog article
- Displaying an individual blog article
To create the interface between our application and the BrightstarDB ASP.NET MVC service created earlier, we will add an communication layer named brightstar-server.js to our app.
Create a new file under the /blog folder named ‘brightstar-server.js’ and add the following;
The BrightstarServer class provides a single method collection, that will contact the BrightstarDB ASP.NET MVC server using an HTTP request, execute a Sparql query to return all blog posts and process the resulting JSON. The Sparql query is requesting the ‘_id’, ‘title’, ‘body’, and ‘created_at’ properties for each blog post. The JSON returned will look similar to the data below;
Next we will create an articleprovider that uses the brightstarserver class. Add a new file named ‘articleprovider-brightstar.js’ and include the following;
The ArticleProvider provides a single method findAll that uses the BrightstarServer class to fetch all of the blog posts. To make our blog app uses our ArticleProvider, we need to update app.js to render a view when the ‘/’ route is called and display all of the blog posts.
Update app.js with the following ensuring that the port number for the ASP.NET server earlier is used when initialising ArticleProvider;
Our application is now using the BrightstarDB ArticleProvider, calling its findAll method to fetch all of the blog posts and passing them to a view ‘index.jade’, which we will add now. Create a new file named index.jade and add the following code;
Update the file style.styl the following css rules;
Before we can test that the app is working correctly and fetching blog posts, we need to populate our store with some test data. Using Polaris, run a new transaction on the ‘Blog’ store using the following test data;
With the test data added, restart the Node server and run node app.jsagain. Refresh the site and there should now be three blog posts displayed on the page.
Now that we can display our posts we need to add functionality to create new articles. Create a new view named blog_new.jade and the following code;
In app.js add another two routes to handle creating new blog posts;
In brightstar-server.js and articleprovider-brightstar.js we need to add the the save methods to handle saving blog posts. Open brightstar-server.js and add the following method after the collection method;
The save method creates a set of NTriples from our post object and sends them to our ASP.NET MVC Rest server. Next we need to add the save method to our ArticleProvider.
In articleprovider-brightstar.js add another method for saving posts;
In the above method we first get all of the posts using the findAll method and use the number of existing posts to create an Id, then pass the article to BrightstarServer to save the post to the server. Reload the Node server and navigate to localhost:3000/blog/new and check that posts can be saved. Note, since characters are not escaped when saving the posts as triples, using carriage returns will cause an error!
Finally, we will add the ability to view a single post by Id. Open brightstar-server.js and add another method beneath the save method added previously;
In the method above we are using another Sparql query to return the ‘title’, ‘body, and ‘created_at’ properties from the given Id. Since we are storing the ISO date, we need to create a Date() object using the date string for each row.
Next update articleprovider-brightstar.js with the following code to fetch a single post;
In the code above we are simply calling the BrightstarServer method findById. Lastly, we need to add a new view to display a single article and add a route in app.js.
Create a new view and name it blog_show.jade, and add the following code;
In app.js add another route for viewing individual posts;
Restart the Node server and we should now be able to view all posts, open individual posts, and create new posts. It should also be possible to add comments to the blogging system so adding comments has been left as an exercise for the reader.
Hopefully this shows the possibilities that are available in using Node.js and BrightstarDB together.
Download the source for both projects.