Skip to content

Commit

Permalink
Add default caching options when serving with single flag
Browse files Browse the repository at this point in the history
  • Loading branch information
ro-savage committed Jun 3, 2017
1 parent 7a27cae commit 5bb5724
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
25 changes: 19 additions & 6 deletions bin/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,11 @@ if (process.env.NODE_ENV !== 'production' && pkg.dist) {

args
.option('port', 'Port to listen on', process.env.PORT || 5000)
.option('cache', 'Time in milliseconds for caching files in the browser')
.option(
'cache',
'Time in milliseconds for caching files in the browser',
3600
'single',
'Serve single page apps with only one index.html. Sets cache for 1 day.'
)
.option('single', 'Serve single page apps with only one index.html')
.option('unzipped', 'Disable GZIP compression')
.option('ignore', 'Files and directories to ignore')
.option('auth', 'Serve behind basic auth')
Expand All @@ -62,7 +61,15 @@ const flags = args.parse(process.argv, {
n: 'no-clipboard',
o: 'open'
},
boolean: ['auth', 'cors', 'silent', 'single', 'unzipped', 'no-clipboard', 'open']
boolean: [
'auth',
'cors',
'silent',
'single',
'unzipped',
'no-clipboard',
'open'
]
}
})

Expand Down Expand Up @@ -109,7 +116,13 @@ detect(port).then(open => {
server.listen(
port,
coroutine(function*() {
yield listening(server, current, inUse, flags.noClipboard !== true, flags.open)
yield listening(
server,
current,
inUse,
flags.noClipboard !== true,
flags.open
)
})
)
})
11 changes: 11 additions & 0 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ module.exports = coroutine(function*(req, res, flags, current, ignoredFiles) {
streamOptions.maxAge = flags.cache
}

if (!flags.cache && flags.single) {
// Default to 1 day for SPAs
// index.html defaults to 0
streamOptions.maxAge = '8640000'
}

// Check if directory
if (relatedExists && (yield pathType.dir(related))) {
// Normalize path to trailing slash
Expand Down Expand Up @@ -139,10 +145,15 @@ module.exports = coroutine(function*(req, res, flags, current, ignoredFiles) {
indexPath = path.join(current, '/index.html')
}

if (flags.single && indexPath === path.join(current, '/index.html')) {
streamOptions.maxAge = 0 // Don't cache SPA index
}

return stream(req, indexPath, streamOptions).pipe(res)
}

if (!(yield fs.exists(related)) && flags.single) {
streamOptions.maxAge = 0 // Don't cache SPA index
const indexPath = path.join(current, '/index.html')
return stream(req, indexPath, streamOptions).pipe(res)
}
Expand Down

0 comments on commit 5bb5724

Please sign in to comment.