2015-03-21 15:14:51 +03:00
|
|
|
// ### prevNext helper exposes methods for prev_post and next_post - separately defined in helpers index.
|
|
|
|
// Example usages
|
|
|
|
// `{{#prev_post}}<a href ="{{url}}>previous post</a>{{/prev_post}}'
|
|
|
|
// `{{#next_post}}<a href ="{{url absolute="true">next post</a>{{/next_post}}'
|
|
|
|
|
2017-04-04 19:07:35 +03:00
|
|
|
var proxy = require('./proxy'),
|
|
|
|
Promise = require('bluebird'),
|
2015-03-21 15:14:51 +03:00
|
|
|
|
2017-08-27 19:00:32 +03:00
|
|
|
logging = proxy.logging,
|
|
|
|
i18n = proxy.i18n,
|
|
|
|
createFrame = proxy.hbs.handlebars.createFrame,
|
|
|
|
|
2017-04-04 19:07:35 +03:00
|
|
|
api = proxy.api,
|
|
|
|
isPost = proxy.checks.isPost,
|
|
|
|
|
|
|
|
fetch;
|
|
|
|
|
2017-08-27 19:00:32 +03:00
|
|
|
fetch = function fetch(apiOptions, options, data) {
|
|
|
|
var self = this;
|
|
|
|
|
|
|
|
return api.posts
|
|
|
|
.read(apiOptions)
|
|
|
|
.then(function handleSuccess(result) {
|
|
|
|
var related = result.posts[0];
|
|
|
|
|
|
|
|
if (related.previous) {
|
|
|
|
return options.fn(related.previous, {data: data});
|
|
|
|
} else if (related.next) {
|
|
|
|
return options.fn(related.next, {data: data});
|
|
|
|
} else {
|
|
|
|
return options.inverse(self, {data: data});
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.catch(function handleError(err) {
|
|
|
|
logging.error(err);
|
|
|
|
data.error = err.message;
|
|
|
|
return options.inverse(self, {data: data});
|
|
|
|
});
|
2015-03-21 15:14:51 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
// If prevNext method is called without valid post data then we must return a promise, if there is valid post data
|
|
|
|
// then the promise is handled in the api call.
|
|
|
|
|
2017-04-04 19:07:35 +03:00
|
|
|
module.exports = function prevNext(options) {
|
2015-03-21 15:14:51 +03:00
|
|
|
options = options || {};
|
2015-04-22 21:56:56 +03:00
|
|
|
|
2017-08-27 19:00:32 +03:00
|
|
|
var data = createFrame(options.data),
|
|
|
|
apiOptions = {
|
|
|
|
include: options.name === 'prev_post' ? 'previous,previous.author,previous.tags' : 'next,next.author,next.tags'
|
|
|
|
};
|
|
|
|
|
|
|
|
if (!options.fn) {
|
|
|
|
data.error = i18n.t('warnings.helpers.mustBeCalledAsBlock', {helperName: options.name});
|
|
|
|
logging.warn(data.error);
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
2015-04-22 21:56:56 +03:00
|
|
|
|
2017-04-04 19:07:35 +03:00
|
|
|
if (isPost(this) && this.status === 'published') {
|
2015-04-22 21:56:56 +03:00
|
|
|
apiOptions.slug = this.slug;
|
2017-08-27 19:00:32 +03:00
|
|
|
return fetch(apiOptions, options, data);
|
2015-03-21 15:14:51 +03:00
|
|
|
} else {
|
2017-08-27 19:00:32 +03:00
|
|
|
return Promise.resolve(options.inverse(this, {data: data}));
|
2015-03-21 15:14:51 +03:00
|
|
|
}
|
|
|
|
};
|