Created
October 31, 2018 01:22
-
-
Save mkamakura/a7a1bd11abfef4f870a30aed49a24083 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
export default function maintenance (app, options) { | |
let mode = false | |
let endpoint = false | |
let url = '/maintenance' | |
let accessKey | |
let view = 'maintenance.html' | |
let api = false | |
let status = 503 | |
let message = 'sorry, we are on maintenance' | |
if (typeof options === 'boolean') { | |
mode = options | |
} else if (typeof options === 'object') { | |
mode = options.current || mode | |
endpoint = options.httpEndpoint || endpoint | |
url = options.url || url | |
accessKey = options.accessKey | |
view = options.view || view | |
api = options.api || api | |
status = options.status || status | |
message = options.message || message | |
} else { | |
throw new Error('unsupported options') | |
} | |
const checkAccess = (req, res, next) => { | |
if (!accessKey) { | |
return next() | |
} | |
if (req.query['access_key'] === accessKey) { | |
return next() | |
} | |
res.sendStatus(401) | |
} | |
const server = function (app) { | |
if (endpoint) { | |
const router = express.Router() | |
router.post(url, checkAccess, (req, res) => { | |
mode = true | |
res.sendStatus(200) | |
}) | |
router.delete(url, checkAccess, (req, res) => { | |
mode = false | |
res.sendStatus(200) | |
}) | |
app.use('/', router) | |
} | |
} | |
const handle = (req, res) => { | |
const isApi = api && req.url.indexOf(api) === 0 | |
res.status(status) | |
if (isApi) { | |
return res.json({ message: message }) | |
} | |
return res.render(view) | |
} | |
const middleware = (req, res, next) => { | |
if (mode) { | |
const requestUrl = req.url.split('?')[0] | |
if (requestUrl === url && (req.method === 'DELETE' || req.method === 'POST')) { | |
next() | |
} else { | |
return handle(req, res) | |
} | |
} | |
next() | |
} | |
const inject = (app) => { | |
app.use(middleware) | |
return app | |
} | |
return server(inject(app)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment