blog/themes/chameleon/scripts/feed/generator.js

59 lines
1.3 KiB
JavaScript
Raw Permalink Normal View History

2019-08-12 11:02:22 +00:00
'use strict'
const nunjucks = require('nunjucks')
const env = new nunjucks.Environment()
const { join } = require('path')
const { readFileSync } = require('fs')
2019-08-12 11:02:22 +00:00
const moment = require('moment')
const { encodeURL, full_url_for } = require('hexo-util')
2019-08-12 11:02:22 +00:00
env.addFilter('uriencode', str => {
return encodeURL(str)
2019-08-12 11:02:22 +00:00
})
env.addFilter('noControlChars', str => {
return str.replace(/[\x00-\x1F\x7F]/g, '') // eslint-disable-line no-control-regex
})
env.addFilter('formatDate', str => {
2019-08-12 11:02:22 +00:00
return moment(str).format('YYYY-MM-DD[T00:00:00.000Z]')
})
const atomTmplSrc = join(__dirname, './.atom.xml')
const atomTmpl = nunjucks.compile(readFileSync(atomTmplSrc, 'utf8'), env)
2019-08-12 11:02:22 +00:00
module.exports = function (locals) {
2020-07-01 07:21:24 +00:00
const { config } = this
const { feed, url } = config
2020-07-01 07:21:24 +00:00
const { icon: iconCfg, limit, order_by, path } = feed
2019-08-12 11:02:22 +00:00
const template = atomTmpl
env.addFilter('fullUrlFor', str => {
return full_url_for.call(this, str)
})
2020-07-01 07:21:24 +00:00
let posts = locals.posts.sort(order_by || '-date')
2019-08-12 11:02:22 +00:00
posts = posts.filter(post => {
return post.draft !== true
})
2020-07-01 07:21:24 +00:00
if (limit) posts = posts.limit(limit)
2019-08-12 11:02:22 +00:00
const icon = iconCfg ? full_url_for.call(this, iconCfg) : ''
2019-08-12 11:02:22 +00:00
const feed_url = full_url_for.call(this, path);
2020-07-01 07:21:24 +00:00
const data = template.render({
config,
url,
icon,
posts,
feed_url
2019-08-12 11:02:22 +00:00
})
return {
2020-07-01 07:21:24 +00:00
path,
data
2019-08-12 11:02:22 +00:00
}
}