import getSSRApolloClient from '@/api/ssrApollo'
const SITE_URL = 'https://stacker.news'
const SITE_TITLE = 'stacker news'
const SITE_SUBTITLE = 'It\'s like Hacker News, but we pay you Bitcoin.'
function escapeXml (unsafe) {
return unsafe.replace(/[<>&'"]/g, function (c) {
switch (c) {
case '<': return '<'
case '>': return '>'
case '&': return '&'
case '\'': return '''
case '"': return '"'
}
})
}
const generateRssItem = (item) => {
const guid = `${SITE_URL}/items/${item.id}`
const link = item.url || guid
let title = item.title
if (item.isJob) {
title = item.title + ' \\ ' + item.company + ' \\ ' + `${item.location || ''}${item.location && item.remote ? ' or ' : ''}${item.remote ? 'Remote' : ''}`
}
const category = item.subName ? `${item.subName}` : ''
return `
-
${guid}
${escapeXml(title)}
${escapeXml(link)}
${guid}
Comments]]>
${new Date(item.createdAt).toUTCString()}
${category}
${item.user.name}
`
}
function generateRssFeed (items, sub = null) {
const itemsList = items.map(generateRssItem)
return `
${SITE_TITLE}${sub ? ` ~${sub}` : ''}
${SITE_URL}${sub ? `/~${sub}` : ''}
${SITE_SUBTITLE}
en
${new Date().toUTCString()}
${itemsList.join('')}
`
}
export default function getGetRssServerSideProps (query, variables = null) {
return async function ({ req, res, query: params }) {
const emptyProps = { props: {} } // to avoid server side warnings
const client = await getSSRApolloClient({ req, res })
const { error, data: { items: { items } } } = await client.query({
query, variables: { ...params, ...variables }
})
if (!items || error) return emptyProps
res.setHeader('Content-Type', 'text/xml; charset=utf-8')
res.write(generateRssFeed(items, params?.sub))
res.end()
return emptyProps
}
}