const express = require('@runkit/runkit/express-endpoint/1.0.0')
const app = express(exports)
const Cite = require('citation-js')
const docs = 'https://gist.github.com/larsgw/ada240ded0a78d5a6ee2a864fbcb8640'
const validStyle = style => ['bibtxt', 'bibtex', 'csl', 'citation'].includes(style) || /^citation-\w+$/.test(style)
const validType = type => ['string', 'html', 'json'].includes(type)
const last = array => array[array.length - 1]
const getOptions = params => {
const fragments = params.split('/')
let data, style = 'csl', type = 'html'
if (fragments.length === 1) {
data = fragments.pop()
} else if (validType(last(fragments))) {
type = fragments.pop()
if (validStyle(last(fragments))) {
style = fragments.pop()
data = fragments.join('/')
} else {
data = fragments.join('/')
}
} else if (validStyle(last(fragments))) {
style = fragments.pop()
data = fragments.join('/')
} else {
data = fragments.join('/')
}
return {data, style, type}
}
app
.get('/', (_, res) => res.redirect(docs))
.get('/*', ({params: {0: params}}, res) => {
const {data, style, type} = getOptions(params)
const cite = new Cite(data)
const output = cite.get({style, type})
res.send(output)
})