Ghost.js is a Node.js alternative to WordPress and other blogging CMS frameworks

Here we'll walk through how to make use of the supplied API that is available on every Ghost.js implementation in order to build a custom search feature for our posts

Why?

Search functionality walks hand-in-hand with scalability

I looked around for an example Ghost.js site with internal search functionality but couldn't find one

Using the Ghost.js API separates the men from the boys, the women from the girls

Ghost 0.8.0 API

Scratch-built but with some guidance from the Ghost.js spec

Using MixItUp to help present results

See it in action on the search page!

Post Search Functionality

Main search event:


    $('#search-submit').click(function (e) {
        e.preventDefault();

        //Destroy MixItUp instance
        if ($('#MixItUpPosts').mixItUp('isLoaded')) {
            $('#MixItUpPosts').mixItUp('destroy', true);
        }
        $('.posts-mixitup-wrapper').empty();

        var searchQuery = $('#search-field').val().toLowerCase();
        if (!(searchQuery == null || searchQuery == "" || searchQuery == undefined || searchQuery.length == 0)) {

            //Execute GET request against Post endpoint
            $.get(ghost.url.api('posts'), { limit: 'all', order: 'created_at DESC' })
                .done(function (data) {

                    //Post success callback
                    postsOnSuccess(searchQuery, data);
                    $('#MixItUpPosts').mixItUp({
                        selectors: {
                            sort: '.sort'
                        }
                    });
                })
                .fail(function (err) {
                    console.log(err);
                });
        }
    });


Success callback:


function postsOnSuccess(searchQuery, data) {
    var transfer = [];
    for (var key in data.posts) {
        var a = data.posts[key], entry = {
            title: JSON.stringify(a.title),
            url: JSON.stringify(a.slug),
            html: JSON.stringify(a.html)
        };
        transfer.push(entry)
    }
    if (transfer.length > 0) {
        var template = "<h3>Search Results</h3>", flag = false;
        for (var key in transfer) {
            var b = transfer[key], html = (b.html).replace(/"/g, "").toLowerCase();
            if (html.indexOf(searchQuery) !== -1) {
                var url = (b.url).replace(/"/g, ""), title = (b.title).replace(/"/g, "");
                template += "<a class='post-entry mix' data-order='" + title + "' href='http://www.postlib.com/" + url + "'><span class='post-entry'>" + title + "</span></a>";
                flag = true;
            }
        }
        if (!flag) {
            template += "<p class='post-entry mix no-result'>No Results Found</p>"
        }
        $('.posts-mixitup-wrapper').append(template)
    }
}