I thought it would be fun to build an app that lets users search and explore this list in different ways: by name, style, brewery, alcohol content, etc. I learned a ton: not only building the application, but also using it!

Running the Application

Architecture Highlights

Belgian Beer explorer is a single page application built with React and Bootstrap. The back-end is built with Node.js and Express: it consists of a simple REST service that exposes the data stored in a Postgres database.

If you are new to React and are looking for a step-by-step walkthrough, take a look at the Employee Directory application I documented here and here.

Source Code

The source code is available in this GitHub repository. It includes the database based on the Wikipedia list and exported in .sql format.

]]>http://coenraets.org/blog/2015/01/belgian-beer-explorer-with-react-bootstrap-node-js-and-postgres/feed/16ForceServer: A Local Server to Streamline Salesforce OAuth and REST Developmenthttp://coenraets.org/blog/2014/11/forceserver-local-server-oauth-rest-development/
http://coenraets.org/blog/2014/11/forceserver-local-server-oauth-rest-development/#commentsTue, 04 Nov 2014 20:00:11 +0000http://coenraets.org/blog/?p=8075Salesforce provides a REST API that makes it easy to access and manipulate Salesforce data from any application.

To start using Salesforce OAuth and the REST APIs, you need to add a few components to your development environment:

A Local Web Server to (1) serve the OAuth callback URL defined in your Connected App, and (2) serve the whole app during development and avoid cross-domain policy issues when loading files (for example, templates) from the local file system.

There are of course existing proxy servers and local web servers, but what’s often lacking is a simple and integrated developer experience.

ForceServer

To experiment with a streamlined developer experience, I put together ForceServer, a simple development server that combines a Proxy Server built for the Salesforce REST APIs, and a Local Web Server to serve your app during development.

To install ForceServer, make sure Node.js is installed on your system, open a command prompt and type:

npm install -g force-server

or (Mac):

sudo npm install -g force-server

Build your First Salesforce REST App in 2 Minutes

Now that the server is installed on your system, let’s put the developer experience to the test by creating an application that displays the proverbial list of Salesforce contacts:

In a real-lfe app, you should host the force.js file on your own server or development machine.

Start ForceServer in the directory where you created index.html:

force-server

This command will start the server on port 8200, and automatically load your app (http://localhost:8200) in a browser window. You’ll see the Salesforce login window (make sure you enable the popup window), and the list of contacts will appear after you log in. If you don’t have a free Salesforce Developer Edition to log in to, you can create one here.

You can change the port number and the web root. Type force-server --help for more info.

Code Highlights:

The sample application above uses the ForceJS library. ForceJS and ForceServer are built to work closely together and provide an integrated developer experience.

ForceJS uses a default connected app: No need to create a connected app to start development. You should however create your own connected app for production use.

Transparently Running Hybrid Apps on Device and in the Browser

If you develop a hybrid application using the Mobile SDK, you often switch back and forth between running the app in the browser and on device: Developing in the browser is generally faster and easier to debug, but you still need to test device-specific features and check that everything runs as expected on the target platforms. The problem is that the configuration of OAuth and REST is different when running in the browser and on-device. Here is a summary of the key differences:

Browser

Device

Proxy

Yes

No

OAuth

Popup

Plugin

ForceJS abstracts these differences and allows you to run your app in the browser and on device without code or configuration change.

Closing Comments

This is mostly an experiment at this point, and I’m planning to test it in workshops and hackathons to simplify the initial developer experience. I’m interested in hearing from you: what’s your setup when building applications using Salesforce OAuth and the REST APIs?

Installing Node.js

Run the installer that you just downloaded. When the installer completes, a message indicates that Node was installed at /usr/local/bin/node and npm was installed at /usr/local/bin/npm.

At this point node.js is ready to use. Let’s implement the webserver application from the nodejs.org home page. We will use it as a starting point for our project: a RESTful API to access data (retrieve, create, update, delete) in a wine cellar database.

Create a folder named nodecellar anywhere on your file system.

In the wincellar folder, create a file named server.js.

Code server.js as follows:

We are now ready to start the server and test the application:

To start the server, open a shell, cd to your nodecellar directory, and start your server as follows:

Using Node.js Modules

In a large application, things could easily get out of control if we keep adding code to a single JavaScript file (server.js). Let’s move the wine-related code in a wines module that we then declare as a dependency in server.js.

In the nodecellar folder, create a subfolder called routes.

In the routes folder create a file named wines.js and defined as follows:

Modify server.js as follows to delegate the routes implementation to the wines module:

Installing the MongoDB Driver for Node.js

There are different solutions offering different levels of abstraction to access MongoDB from Node.js (For example, Mongoose and Mongolia). A comparaison of these solutions is beyond the scope of this article. In this, guide we use the native Node.js driver.

To install the the native Node.js driver, open a terminal window, cd to your nodecellar folder, and execute the following command:

npm install mongodb

Implementing the REST API

The full REST API for the nodecellar application consists of the following methods:

Method

URL

Action

GET

/wines

Retrieve all wines

GET

/wines/5069b47aa892630aae000001

Retrieve the wine with the specified _id

POST

/wines

Add a new wine

PUT

/wines/5069b47aa892630aae000001

Update wine with the specified _id

DELETE

/wines/5069b47aa892630aae000001

Delete the wine with the specified _id

To implement all the routes required by the API, modify server.js as follows:

To provide the data access logic for each route, modify wines.js as follows:

Restart the server to test the API.

Testing the API using cURL

If you want to test your API before using it in a client application, you can invoke your REST services straight from a browser address bar. For example, you could try:

Next Steps

In my next post, I’ll share a client application that makes use of that API. Update: The “next post” is now available here.

]]>http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/feed/285Backbone.js Wine Cellar Tutorial — Part 3: Deep Linking and Application Stateshttp://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-3-deep-linking-and-application-states/
http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-3-deep-linking-and-application-states/#commentsThu, 08 Dec 2011 21:04:53 +0000http://coenraets.org/blog/?p=2555UPDATE: I posted a “Postface” to this series with some lessons learned and an improved version of the app. Make sure you read it here.

In Part 1 of this tutorial, we set up the basic infrastructure for the Wine Cellar application. In Part 2, we added the ability to create, update, and delete (CRUD) wines.

There are a few remaining issues in the application. They are all related to “deep linking”. The application needs to continuously keep its URL in sync with its current state. This allows you to grab the URL from the address bar at any point in time during the course of the application, and re-use or share it to go back to the exact same state.

In this last installment of the tutorial, we add support for deep linking in the Wine Cellar application.

Problem 1: Linking to a specific wine

The problem: Select a specific wine from the list. The URL looks like this: http://www.coenraets.org/backbone-cellar/part2/#wines/[id]. Now do one of these two things:

Grab that URL from the address bar and try to access it from another browser window or tab

Simply click your browser’s Refresh button

You get an empty screen with no data. If you look at a debug console (for example, in Chrome’s Developer Tools), you’ll get this message:

The problem is on line 20: we are assuming that a wine collection (this.wineList) already exists, and are trying to “get” a specific item from that list. That works well when we start the application with the default (“”) route. But this.wineList won’t exist if we start the application with the “wines/:id” route. There are different ways to address the issue:

We could modify the wineDetails function to fetch the requested item directly:

That takes care of loading the wine details in the form, but the wine list remains empty when we start the application with “wines/:id” route. We could add the following line of code to load the list if it doesn’t exist:

if (!this.wineList) this.list();

But now, the wine model that is part of the collection and the wine model fetched separately are two different objects, which means that data binding and View synchronization will not work as expected.

Another approach is to check if the collection exists in the wineDetails function. If it does, we simply “get” the requested item and render it as we did before. If it doesn’t, we store the requested id in a variable, and then invoke the existing list() function to populate the list. We then modify the list function: When we get the list from the server (on success), we check if there was a requested id. If there was, we invoke the wineDetails function to render the corresponding item.

Problem 2: Updating the URL after a wine is created

The problem: Add a new Wine, and click Save. The id that has been assigned to the newly created wine appears in the form field. However the URL is still:
http://localhost/backbone-cellar/part2/ when it should really be: http://localhost/backbone-cellar/part2/#wines/[id].

You can easily fix that issue by using the router’s navigate function to change the URL. The second argument (false), indicates that we actually don’t want to “execute” that route: we just want to change the URL.

Problem 3: Updating the URL while creating a new wine

The problem: Select a wine in the list. The URL looks like this: http://localhost/backbone-cellar/part2/#wines/[id]

Now, click the “Add Wine” button. You get an empty form to enter a new wine, but notice that the URL is still unchanged (http://localhost/backbone-cellar/part2/#wines/[id]). In other words, it doesn’t reflect the current state of the application.

Download

The source code for this application is hosted on GitHub here (see part3). And here is a quick link to the download.

You will need the RESTful services to run this application. A PHP version (using the Slim framework) is available as part of the download.

UPDATE (1/11/2012): A version of this application with a Java back-end (using JAX-RS and Jersey) is also available on GitHub here. You can find more information on the Java version of this application here.

]]>http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-3-deep-linking-and-application-states/feed/49Backbone.js Wine Cellar Tutorial — Part 2: CRUDhttp://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-2-crud/
http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-2-crud/#commentsWed, 07 Dec 2011 16:52:01 +0000http://coenraets.org/blog/?p=2483In Part 1 of this tutorial, we set up the basic infrastructure for the Wine Cellar application. The application so far is read-only: it allows you to retrieve a list of wines, and display the details of the wine you select.

In this second installment, we will add the ability to create, update, and delete (CRUD) wines.

RESTful Services

As mentioned in Part 1, Backbone.js provides a natural and elegant integration with RESTful services. If your back-end data is exposed through a pure RESTful API, retrieving (GET), creating (POST), updating (PUT), and deleting (DELETE) models is incredibly easy using the Backbone.js simple Model API.

This tutorial uses pure RESTful services. The services are implemented as follows:

HTTP Method

URL

Action

GET

/api/wines

Retrieve all wines

GET

/api/wines/10

Retrieve wine with id == 10

POST

/api/wines

Add a new wine

PUT

/api/wines/10

Update wine with id == 10

DELETE

/api/wines/10

Delete wine with id == 10

A PHP version of these services (using the Slim framework) is available as part of the download. A similar Java version of the API (using JAX-RS) is available as part of this post.

Using Backbone.js with non-RESTful Services

If your persistence layer is not available through RESTful services, you can override Backbone.sync. From the documentation:

“Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses (jQuery/Zepto).ajax to make a RESTful JSON request. You can override it in order to use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.”

Using non-RESTful services is not discussed in this tutorial. See the documentation for more information.

Part 2: Adding Create, Update, Delete

You can run the application (Part 2) here. The create/update/delete features are disabled in this online version. Use the link at the bottom of this post to download a fully enabled version.

Here is the code for the improved version of the applications. Key changes are discussed below.

Wine

Two attributes were added to the Wine Model:

urlRoot: RESTful service endpoint to retrieve or persist Model data. Note that this attribute is only needed when retrieving/persisting Models that are not part of a Collection. If the Model is part of a Collection, the url attribute defined in the Collection is enough for Backbone.js to know how to retrieve, update, or delete data using your RESTful API.

defaults: Default values used when a new instance of the model is created. This attribute is optional. However, it was required in this application for the wine-details template to render an ‘empty’ wine model object (which happens when adding a new wine).

WineListView

When a new wine is added, you want it to automatically appear in the list. To make that happen, you bind the View to the add event of the WineListView model (which is the collection of wines). When that event is fired, a new instance of WineListItemView is created and added to the list.

WineListItemView

When a wine is changed, you want the corresponding WineListItemView to re-render automatically to reflect the change. To make that happen, you bind the View to the change event of its model, and execute the render function when the event is fired.

Similarly, when a wine is deleted, you want the list item to be removed automatically. To make that happen, you bind the view to the destroy event of its model and execute our custom close function when the event is fired. To avoid memory leaks and events firing multiple times, it is important to unbind the event listeners before removing the list item from the DOM.

Note that in either case we don’t have the overhead of re-rendering the entire list: we only re-render or remove the list item affected by the change.

WineView

In the spirit of encapsulation, the event handlers for the Save and Delete buttons are defined inside WineView, as opposed to defining them as free-hanging code blocks outside the “class” definitions. You use the Backbone.js Events syntax which uses jQuery delegate mechanism behind the scenes.

There are always different approaches to update the model based on user input in a form:

“Real time” approach: you use the change handler to update the model as changes are made in the form. This is in essence bi-directional data binding: the model and the UI controls are always in sync. Using this approach, you can then choose between sending changes to the server in real time (implicit save), or wait until the user clicks a Save button (explicit save). The first option can be chatty and unpractical when there are cross-field validation rules. The second option may require you to undo model changes if the user navigates to another item without clicking Save.

“Delayed” approach: You wait until the user clicks Save to update the model based on the new values in UI controls, and then send the changes to the server.

This discussion is not specific to Backbone.js and is therefore beyond the scope of this post. For simplicity, I used the delayed approach here. However I still wired the change event, and use it to log changes to the console. I found this very useful when debugging the application, and particularly to make sure I had cleaned up my bindings (see close function): I you see the change event firing multiple times, you probably didn’t clean up as appropriate.

HeaderView

Backbone.js Views are typically used to render domain models (as done in WineListView, WineListItemView, and Wine View). But they can also be used to create composite UI components. For example, in this application, we define a Header View (a toolbar) that could be made of different components and that encapsulates its own logic.

Download

The source code for this application is hosted on GitHub here (see part2). And here is a quick link to the download.

You will need the RESTful services to run this application. A PHP version (using the Slim framework) is available as part of the download.

UPDATE (1/11/2012): A version of this application with a Java back-end (using JAX-RS and Jersey) is also available on GitHub here. You can find more information on the Java version of this application here.

What’s Next?

The application so far doesn’t support deep-linking. For example, select a wine in the list, grab the URL in the address bar and paste it in another browser window: it doesn’t work. In Part 3, we will add complete support for deep linking.

One of the challenges when building nontrivial Web applications is that JavaScript’s non-directive nature can initially lead to a lack of structure in your code, or in other words, a lack of… backbone. JavaScript is often written as a litany of free-hanging and unrelated blocks of code, and it doesn’t take long before it becomes hard to make sense of the logic and organization of your own code.

Backbone.js is a lightweight framework that addresses this issue by adding structure to JavaScript-heavy Web applications.Self-contained building blocks

Backbone.js provides several classes (Model, Collection, View, Router) that you can extend to define the building blocks of your application. To build an app with Backbone.js, you first create the Models, Collections, and Views of your application. You then bring these components to life by defining a “Router” that provides the entry points of your application through a set of (deep-linkable) URLs.

With Backbone.js, your code is organized in self-contained entities (Models, Collections, Views): No more free-hanging and unrelated blocks of code.

Data Binding

With Backbone.js, you bind Views to Models so that when a Model’s data changes, all the Views bound to that Model automatically re-render. No more complex UI synchronization code.

WineModel (line 2): Notice that we don’t need to explicitly define the attributes (name, country, year, etc). You could add validation, default values, etc. More on that in Part 2.

WineCollection (lines 4 to 7): “model” indicates the nature of the collection. “url” provides the endpoint for the RESTFul API. This is all that’s needed to retrieve, create, update, and delete wines with Backbone’s simple Model API.

WineListView (lines 10 to 25): The render() function iterates through the collection, instantiates a WineListItemView for each wine in the collection, and adds it to the wineList.

WineListItemView (lines 27 to 38): The render() function merges the model data into the “wine-list-item” template (defined in index.html). By defining a separate View for list items, you will make it easy to update (re-render) a specific list item when the backing model changes without re-rendering the entire list. More on that in Part 2.

WineView (lines 40 to 49): The view responsible for displaying the wine details in the Wine form. The render() function merges the model data (a specific wine) into the “wine-details” template retrieved from index.html.

AppRouter (lines 52 to 71): Provides the entry points for the application through a set of (deep-linkable) URLs. Two routes are defined: The default route (“”) displays the list of wine. The “wines/:id” route displays the details of a specific wine in the wine form. Note that in Part 1, this route is not deep-linkable. You have to start the application with the default route and then select a specific wine. In Part 3, you will make sure you can deep-link to a specific wine.

Download

The source code for this application is hosted on GitHub here. And here is a quick link to the download.

You will need the RESTful services to run this application. A PHP version (using the Slim framework) is available as part of the download.

UPDATE (1/11/2012): A version of this application with a Java back-end (using JAX-RS and Jersey) is also available on GitHub here. You can find more information on the Java version of this application here.

]]>http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/feed/149RESTful services with jQuery, PHP and the Slim Frameworkhttp://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/
http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/#commentsThu, 01 Dec 2011 17:12:06 +0000http://coenraets.org/blog/?p=2369NOTE: This is the PHP version of this article and its companion app. A Java version is available here.

I have been looking for a lightweight framework to build a RESTful API in PHP. There are a number of good options out there: Slim, Epiphany, Tonic, Recess, and Frapi to name a few. They all seem like good frameworks. In the end, I chose Slim for this project for two main reasons:

It’s very lightweight and focused on REST and nothing else.

It supports all the HTTP methods (GET, POST, PUT, DELETE), which was a key requirement for my application.

This article (and its companion app) provides an example of building a complete RESTful API using the different HTTP methods:

GET to retrieve and search data

POST to add data

PUT to update data

DELETE to delete data

The application used as an example for this article is a Wine Cellar app. You can search for wines, add a wine to your cellar, update and delete wines.

You can run the application here. The create/update/delete features are disabled in this online version. Use the link at the bottom of this post to download a fully enabled version.

The jQuery Client

Accessing your API through cURL is cool, but there is nothing like a real application to put your API to the test. So the source code (available for download at the end of this post) includes a simple jQuery client to manage your wine cellar.

Download the Source Code

The source code for this application is hosted on GitHub here. And here is a quick link to the source code download. It includes both the PHP and jQuery code for the application.

I’m interested in your feedback. Let me know what you think and what your experience has been building RESTful-based applications using PHP and jQuery

]]>http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/feed/159RESTful services with jQuery and Java using JAX-RS and Jerseyhttp://coenraets.org/blog/2011/12/restful-services-with-jquery-and-java-using-jax-rs-and-jersey/
http://coenraets.org/blog/2011/12/restful-services-with-jquery-and-java-using-jax-rs-and-jersey/#commentsThu, 01 Dec 2011 15:28:51 +0000http://coenraets.org/blog/?p=2244NOTE: This is the Java version of this article and its companion app. A PHP version is available here.

This is a more in depth version of my previous post on the same topic. The previous article only covered the HTTP GET method for building RESTful services. This article (and its new companion app) provides an example of building a complete RESTful API using the different HTTP methods:

GET to retrieve and search data

POST to add data

PUT to update data

DELETE to delete data

The application used as an example for this article is a Wine Cellar app. You can search for wines, add a wine to your cellar, update and delete wines.

You can run the application here. The create/update/delete features are disabled in this online version. Use the link at the bottom of this post to download a fully enabled version.
The REST API consists of the following methods:

Method

URL

Action

GET

/api/wines

Retrieve all wines

GET

/api/wines/search/Chateau

Search for wines with ‘Chateau’ in their name

GET

/api/wines/10

Retrieve wine with id == 10

POST

/api/wines

Add a new wine

PUT

/api/wines/10

Update wine with id == 10

DELETE

/api/wines/10

Delete wine with id == 10

Implementing the API using JAX-RS

JAX-RS makes it easy to implement this API in Java. You simply create a class defined as follows:

@Consumes: type of data the method can take as input. The data will automatically be deserialized into a method input parameter. For example, you can pass a wine object to the addWined() method either as JSON or XML. The JSON or XML representation of a new wine is automatically deserialized into the Wine object passed as an argument to the method.

@Produces: One or more response content type(s) the method can generate. The method’s return value will be automatically serialized using the content type requested by the client. If the client didn’t request a specific content type, the first content type listed in the @Produces annotation will be used. For example, if you access http://coenraets.org/rest/wines, you get a list of wines represented as JSON because it is the first content type listed in the @Produces annotation of the findAll() method.

The jQuery client below sends data to the server using JSON (addWine() and updateWine() methods).

The approach you use to actually retrieve the data is totally up to you. In this example, I use a simple DAO, but you can of course use your own data access solution.

Testing the API using cURL

If you want to test your API before using it in a client application, you can invoke your REST services straight from a browser address bar. For example, you could try:

The jQuery Client

Accessing your API through cURL is cool, but there is nothing like a real application to put your API to the test. So the source code (available for download at the end of this post) includes a simple jQuery client to manage your wine cellar.

Download the Source Code

The source code for this application is hosted on GitHub here. And here is a quick link to the project download (Eclipse Dynamic Web Project). It includes both the Java and jQuery code for the application.

UPDATE (1/11/2012): A version of this application using Backbone.js at the client-side is also available on GitHub here. You can find more information on the Backbone.js of this application here.

I’m interested in your feedback. Let me know what you think and what your experience has been building RESTful-based applications using Java and jQuery.

]]>http://coenraets.org/blog/2011/12/restful-services-with-jquery-and-java-using-jax-rs-and-jersey/feed/114Building RESTful Services with Java Using JAX-RS and Jersey — Sample Applicationhttp://coenraets.org/blog/2011/11/building-restful-services-with-java-using-jax-rs-and-jersey-sample-application/
http://coenraets.org/blog/2011/11/building-restful-services-with-java-using-jax-rs-and-jersey-sample-application/#commentsMon, 07 Nov 2011 16:32:57 +0000http://coenraets.org/blog/?p=2019I’m working on a project that required a RESTful API implemented in Java. Jersey, the reference implementation for JAX-RS, made it easy to implement and deploy these services. I figured I’d share my sample application here.

Configuring Tomcat (or your own app server)

There are many options to initialize Jersey in your servlet container. Some of them require no XML configuration at all. For my application, I simply configured the Jersey Servlet in web.xml as follows:

You annotate your class and methods with the path (@Path) and the content type (@Produces) they respond to. The serialization from model objects to the content type requested by the client happens automatically. In this application, the methods will return either JSON or XML depending on the content type requested by the client.

The approach you use to actually retrieve the data is, of course, totally up to you. In this example, I use a simple DAO, but you can of course use your own data access solution.

This application only required GET methods, but JAX-RS allows you to handle the other HTTP methods (@GET, @PUT, @POST, @DELETE and @HEAD).

Note that the package name matches the packages parameter defined in web.xml.

Testing the API

If you want to test your API before using it in a client application, you can invoke your REST services straight from a browser address bar. For example, try:

However, that doesn’t give you full control to test all the content types your API can return. A common option to test the different content types supported by your API is to use cURL and specify the content type requested in the Accept header: