← back to the blog


Front End Widgets - Part 2 - Opening the KeystoneJS API

Posted in KeystoneJS

Table of Contents:

 

This part of the tutorial is based on this GitHub Gist by Jed Watson. In it, he desribed how to open up an API to read and write KeystoneJS blog post data via an AJAX request. This post tweeks it slightly and instead opens up an API to our new front end widget.

Start by logging into the Admin UI of KeystoneJS and populate the database with three new widgets. In my case, I named them Widget 1, Widget 2, and Widget 3 and gave them an image URL and Alt tag description like so:

 

 

Add the following lines to routes/index.js. This handles the routing the API URL.

var routes = {
        views: importRoutes('./views'),
        api: importRoutes('./api')
};

// Setup Route Bindings
exports = module.exports = function(app) {
...
app.get('/api/frontendwidget/list', keystone.middleware.api, routes.api.frontendwidget.list); app.get('/api/frontendwidget/:id', keystone.middleware.api, routes.api.frontend
widget.get);
app.all('/api/frontendwidget/:id/update', keystone.middleware.api, routes.api.frontendwidget.update);

...
};

 

Now that the router is configured, you need create a view/handler for the API. Create the directory routes/api and create the following file routes/api/frontendwidget.js by pasting in the following code:

var async = require('async'),
keystone = require('keystone');

var ImgData = keystone.list('FrontendWidget');

/**
 * List Images
 */
exports.list = function(req, res) {
        ImgData.model.find(function(err, items) {

                if (err) return res.apiError('database error', err);

                res.apiResponse({
                        collections: items
                });

        });
}

/**
 * Get Image by ID
 */
exports.get = function(req, res) {

        ImgData.model.findById(req.params.id).exec(function(err, item) {

                if (err) return res.apiError('database error', err);
                if (!item) return res.apiError('not found');

                res.apiResponse({
                        collection: item
                });

        });
}


/**
 * Update Image by ID
 */
exports.update = function(req, res) {
        ImgData.model.findById(req.params.id).exec(function(err, item) {

                if (err) return res.apiError('database error', err);
                if (!item) return res.apiError('not found');

                var data = (req.method == 'POST') ? req.body : req.query;

                item.getUpdateHandler(req).process(data, function(err) {

                        if (err) return res.apiError('create error', err);

                        res.apiResponse({
                                collection: item
                        });

                });

        });
}

 

Restart KeystoneJS to make the changes go live. You can now 'list' the JSON data for the front end widgets in your browser by going to:

http://<your ip address>:3000/api/frontendwidget/list