Saturday, February 04, 2017

Backbone Views when API Endpoints aren't available...

Let's say you have a view you need to create for a Backbone project. For that view you need a collection of data to display.
BUT, let's also assume that, at the moment, you don't have an API Endpoint or data available from a back end system. But you want to create the GUI for the data that will be forthcoming.

First, determine what your data will look like and then create a standalone JSON file using the same structure that the API Endpoint will eventually return:

view_roles_map.json =
[
     {
            "menuName": "PatientManagement",
            "roles": [
                "National Surgery Admin",
                "Facility Surgery Admin",
                "Surgical Case Admin",
                "Surgery Staff",
                "Surgery Coder"
            ]
        },
        {
            "menuName": "SurgeryMonitoring",
            "roles": [
                "National Surgery Admin",
                "Facility Surgery Admin",
                "Surgical Case Admin",
                "Surgery Case Scheduler",
                "Surgery Case Requestor",
                "Surgery Staff",
                "Surgery Coder"
            ]
        }
]


Next, you're going to need a model for this data:
module.exports = BaseModel.extend({  
     defaults: {  
         "menuName": "",  
         "roles": []  
     }  
 });  
Our simple model has a string as a "menuName" and an array of strings for the "roles" that are assigned to each model in the collection.

Now that we have our model, we'll establish a collection of the data the model will return:
const MenuAccessModel  = require("./model");
module.exports = BaseCollection.extend({
 "url": API.getURL("MenuAccessRoles"),
 "model": MenuAccessModel
});
Notice that we have a function that returns a URL for the data.

Normally this URL is to a RESTful API Endpoint, but in this case the URL is only the URL to the local JSON file we created:
/data_files/view_roles_map.json
That's it we're done.

Now we make use of that collection just as we would any OTHER backbone collection.
const ViewAccessCollection = require("./entities/administration/view_access_config/collection");
 loadViewAccess() {
  const access = new ViewAccessCollection();
  return access.fetch()
   .then(() => Radio.request("store", "set", "viewAccess", access));
 },

Now when an API Endpoint or the data becomes available through an API Endpoint all you have to do is change the URL that your collection/model calls to fetch the data!