Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JSON responses #250

Merged
merged 3 commits into from Mar 1, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions server/index.js
Expand Up @@ -69,6 +69,15 @@ app.use((req, res, next) => {
next()
})

// treat requests ending in .json as application/json
app.use((req, res, next) => {
if (req.path.endsWith('.json')) {
req.headers.accept = 'application/json'
req.url = req.baseUrl + req.path.slice(0, -5)
}
next()
})

app.use(pages)
app.use(cache)

Expand Down
32 changes: 25 additions & 7 deletions server/routes/categories.js
Expand Up @@ -48,24 +48,42 @@ async function handleCategory(req, res) {

// if this is a folder, just render from the generic data
if (resourceType === 'folder') {
return res.render(template, baseRenderData, (err, html) => {
if (err) throw err
res.end(html)
return res.format({
html: () => {
res.render(template, baseRenderData, (err, html) => {
if (err) throw err
res.end(html)
})
},

json: () => {
res.json(baseRenderData)
}
})
}

res.locals.docId = data.id // we need this for history later
// for docs, fetch the html and then combine with the base data
const {html, byline, createdBy, sections} = await fetchDoc(id, resourceType, req)

res.render(template, Object.assign({}, baseRenderData, {
const renderData = Object.assign({}, baseRenderData, {
content: html,
byline,
createdBy,
sections
}), (err, html) => {
if (err) throw err
res.end(html)
})

res.format({
html: () => {
res.render(template, renderData, (err, html) => {
if (err) throw err
res.end(html)
})
},

json: () => {
res.json(renderData)
}
})
}

Expand Down
22 changes: 18 additions & 4 deletions server/routes/errors.js
Expand Up @@ -63,9 +63,23 @@ module.exports = async (err, req, res, next) => {
const code = messages[err.message] || 500
log.error(`Serving an error page for ${req.url}`, err)
const inlined = await loadInlineAssets()
res.status(code).render(`errors/${code}`, {
inlineCSS: inlined.css,
err,
template: inlined.stringTemplate
res.status(code)

res.format({
html: () => {
res.render(`errors/${code}`, {
inlineCSS: inlined.css,
err,
template: inlined.stringTemplate
})
},

json: () => {
res.json({
error: true,
code: code,
message: inlined.stringTemplate(`error.${code}.message`)
})
}
})
}
37 changes: 34 additions & 3 deletions server/routes/pages.js
Expand Up @@ -10,7 +10,7 @@ const {getTemplates, sortDocs, stringTemplate, getConfig} = require('../utils')
router.get('/', handlePage)
router.get('/:page', handlePage)

router.get('/filename-listing.json', async (req, res) => {
router.get('/filename-listing', async (req, res) => {
res.header('Cache-Control', 'public, must-revalidate') // override no-cache
const filenames = await getFilenames()
res.json({filenames: filenames})
Expand Down Expand Up @@ -38,7 +38,23 @@ async function handlePage(req, res) {
if (exactMatches.length === 1) return res.redirect(exactMatches[0].path)
}

res.render(template, {q, results, template: stringTemplate})
res.format({
html: () => {
res.render(template, {q, results, template: stringTemplate})
},

json: () => {
res.json(results.map((result) => ({
url: result.path,
title: result.prettyName,
lastUpdatedBy: (result.lastModifyingUser || {}).displayName,
modifiedAt: result.modifiedTime,
createdAt: result.createdTime,
id: result.id,
resourceType: result.resourceType
tilgovi marked this conversation as resolved.
Show resolved Hide resolved
})))
}
})
})
}

Expand All @@ -47,7 +63,22 @@ async function handlePage(req, res) {
if (page === 'categories' || page === 'index') {
const tree = await getTree()
const categories = buildDisplayCategories(tree)
res.render(template, {...categories, template: stringTemplate})
res.format({
html: () => {
res.render(template, {...categories, template: stringTemplate})
},

json: () => {
res.json(categories.all.map((category) => ({
url: category.path,
title: category.prettyName,
lastUpdatedBy: (category.lastModifyingUser || {}).displayName,
modifiedAt: category.modifiedTime,
createdAt: category.createdTime,
id: category.id
smoores-dev marked this conversation as resolved.
Show resolved Hide resolved
})))
}
})
return
}

Expand Down
37 changes: 37 additions & 0 deletions test/functional/pages.test.js
Expand Up @@ -122,5 +122,42 @@ describe('Server responses', () => {
expect(filenames.length).to.equal(allFilenames.length)
})
})

it('folder with home doc should render the doc', () => {
return request(app)
.get('/test-folder-9')
.set('Accept', 'application/json')
.expect(200)
.expect('Content-Type', /json/)
.then((res) => {
const data = JSON.parse(res.text)
expect(data).to.deep.equal(
{
html: '<p> This is a simple test document export.</p>',
byline: 'John Smith',
createdBy: 'John Smith',
sections: []
}
)
})
})

it('folder with home doc should render the doc (.json suffix)', () => {
return request(app)
.get('/test-folder-9.json')
.expect(200)
.expect('Content-Type', /json/)
.then((res) => {
const data = JSON.parse(res.text)
expect(data).to.deep.equal(
{
html: '<p> This is a simple test document export.</p>',
byline: 'John Smith',
createdBy: 'John Smith',
sections: []
}
)
})
})
})
})
3 changes: 3 additions & 0 deletions test/unit/errors.test.js
Expand Up @@ -8,6 +8,9 @@ const req = {url: 'foo.com/bar'}
const res = {
renderResults: {},
status: () => res,
format: (formats) => {
formats.html()
},
render: (template, opts) => { res.renderResults = {template, opts} }
}

Expand Down