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

54 lines
1.2 KiB
JavaScript
Raw 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 } = require('hexo-util')
2020-07-01 07:21:24 +00:00
const { format } = require('url')
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('date', str => {
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, root, url } = config
const { icon: iconCfg, limit, order_by, path } = feed
2019-08-12 11:02:22 +00:00
const template = atomTmpl
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
2020-07-01 07:21:24 +00:00
const icon = iconCfg ? format(new URL(iconCfg, url), { unicode: true }) : ''
2019-08-12 11:02:22 +00:00
2020-07-01 07:21:24 +00:00
const data = template.render({
config,
url,
icon,
posts,
feed_url: root + path
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
}
}