jcicero518
4/30/2015 - 11:50 PM

gistfile1.js

'use strict';

angular.module('wordpress', [])

.service( 'wpService',
function($http, $q){

    var url = 'http://allin.local/wp-json/';

    return({
        base: base,
        custom: custom,
        types: types,
        taxonomies: taxonomies,
        terms: terms,
        term: term,
        page: page,
        getByType: getByType,
        getBySlug: getBySlug
    })

    function base() {
        return ( $http.get(url)
            .then( handleSuccess, handleError ) );
    }

    function custom( path ) {
        return ( $http.get(url+path)
            .then( handleSuccess, handleError ) );
    }

    function types() {
        return ( $http.get(url+'posts/types')
            .then( handleSuccess, handleError ) );
    }

    function taxonomies() {
        return ( $http.get(url+'taxonomies')
            .then( handleSuccess, handleError ) );
    }

    function terms( tax ) {
        return ( $http.get(url+'taxonomies/'+tax+'/terms')
            .then( handleSuccess, handleError ) );
    }

    function term( tax, term ) {
        return ( $http.get(url+'taxonomies/'+tax+'/terms/'+term)
            .then( handleSuccess, handleError ) );
    }

    function page( id ) {
        return ( $http.get(url+'posts/'+id)
            .then( handleSuccess, handleError ) );
    }

    function getByType( type, limit ) {
        return ( $http.get(url+'posts?type[]='+type+'&filter[posts_per_page]='+limit)
            .then( handleSuccess, handleError ) );
    }

    function getBySlug( type, slug ) {
        return ( $http.get(url+'posts?type[]='+type+'&filter[posts_per_page]=1&filter[name]='+slug)
            .then( handleSuccess, handleError ) );
    }

    function handleSuccess( response ) {

        return( response.data );

    }

    function handleError( response ) {

        if ( ! angular.isObject( response.data ) || ! response.data.message ) {

            return( $q.reject( "An unknown error occurred." ) );

        }

        return( $q.reject( response.data.message ) );
    }

});