Commit 3b21e147 authored by Aral Balkan's avatar Aral Balkan
Browse files

Add support for custom middleware

parent 132e5c03
...@@ -380,6 +380,10 @@ class Site { ...@@ -380,6 +380,10 @@ class Site {
next() next()
}) })
// Add any custom middleware from a .middleware folder
// supplied by the person (if any).
this.appAddCustomMiddleware()
// Statistics middleware (captures anonymous, ephemeral statistics). // Statistics middleware (captures anonymous, ephemeral statistics).
this.app.use(this.stats.middleware) this.app.use(this.stats.middleware)
...@@ -1423,6 +1427,23 @@ class Site { ...@@ -1423,6 +1427,23 @@ class Site {
} }
} }
// To enable any aspect of the server to be customised, you can
// specify custom Express middleware in a .middleware folder. Any files
// here will be read (in lexicographical order, so use, e.g. 1_something.js, 2_something_else.js)
// if middleware order is important for you.
appAddCustomMiddleware () {
const customMiddlewareDirectory = path.join(this.pathToServe, '.middleware')
if (fs.existsSync(customMiddlewareDirectory)) {
const customMiddleware = getRoutes(customMiddlewareDirectory)
customMiddleware.forEach(middleware => {
this.log(` 👣️ ❨site.js❩ Adding custom middleware: ${middleware.path}`)
decache(middleware.callback)
this.app.use(require(middleware.callback))
})
}
}
// Add dynamic routes, if any, if a <pathToServe>/.dynamic/ folder exists. // Add dynamic routes, if any, if a <pathToServe>/.dynamic/ folder exists.
// If there are errors in any of your dynamic routes, you will get 500 (server) errors. // If there are errors in any of your dynamic routes, you will get 500 (server) errors.
// //
......
...@@ -550,9 +550,9 @@ ...@@ -550,9 +550,9 @@
"integrity": "sha512-+BXEtwZukQuaKVzajJ/Np3nABGgLW2jiZca8qxoETiKg1wOUBZpCJYK51JLgmA3mtRHpYFFCitRqaUCAoxQQvg==" "integrity": "sha512-+BXEtwZukQuaKVzajJ/Np3nABGgLW2jiZca8qxoETiKg1wOUBZpCJYK51JLgmA3mtRHpYFFCitRqaUCAoxQQvg=="
}, },
"@small-tech/web-routes-from-files": { "@small-tech/web-routes-from-files": {
"version": "3.0.1", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/@small-tech/web-routes-from-files/-/web-routes-from-files-3.0.1.tgz", "resolved": "https://registry.npmjs.org/@small-tech/web-routes-from-files/-/web-routes-from-files-3.1.0.tgz",
"integrity": "sha512-IR8p+h4gPyxMhn8Kl/SeLBwHBv5GgR4vJsAknLn6qoc0T4We8yn8ni1SSEghyCLMbuOXd0ILn6FnSUa7hLA+2Q==" "integrity": "sha512-z/VkIrjwn6TEE2PDpdywpxGo/AenFy5uki7+i5P34Yx66l3KdnhXwFZ+SmnC2O/G4WRA96fLpmufJ1zsR6OTxQ=="
}, },
"@szmarczak/http-timer": { "@szmarczak/http-timer": {
"version": "1.1.2", "version": "1.1.2",
......
...@@ -39,6 +39,7 @@ async function secureGet (url) { ...@@ -39,6 +39,7 @@ async function secureGet (url) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
https.get(url, (response) => { https.get(url, (response) => {
const statusCode = response.statusCode const statusCode = response.statusCode
const headers = response.headers
const location = response.headers.location const location = response.headers.location
const contentType = response.headers['content-type'] const contentType = response.headers['content-type']
...@@ -50,7 +51,7 @@ async function secureGet (url) { ...@@ -50,7 +51,7 @@ async function secureGet (url) {
let body = '' let body = ''
response.on('data', _ => body += _) response.on('data', _ => body += _)
response.on('end', () => { response.on('end', () => {
resolve({statusCode, contentType, location, body}) resolve({statusCode, contentType, location, body, headers})
}) })
}) })
}) })
...@@ -772,6 +773,32 @@ test('[site.js] proxy', async t => { ...@@ -772,6 +773,32 @@ test('[site.js] proxy', async t => {
}) })
test('[site.js] custom middleware', async t => {
const site = new Site({path: 'test/site-custom-middleware'})
const server = await site.serve()
let response
try {
response = await secureGet('https://localhost/index.html')
} catch (error) {
console.log(error)
process.exit(1)
}
t.equal(response.statusCode, 200, 'request succeeds')
t.strictEqual(response.headers['access-control-allow-origin'], '*', 'access-control-allow-origin header is correct'),
t.strictEqual(response.headers['access-control-allow-headers'], 'Origin, X-Requested-With, Content-Type, Accept', 'access-control-allow-headers is correct')
await new Promise ((resolve, reject) => {
site.server.close(error => {
if (error) reject(error)
resolve()
})
})
t.end()
})
test('[site.js] serve method', async t => { test('[site.js] serve method', async t => {
const site = new Site({path: 'test/site'}) const site = new Site({path: 'test/site'})
const server = await site.serve() const server = await site.serve()
......
////////////////////////////////////////////////////////////////////////////////
//
// Middleware: Allow all Cross Origin Requests (CORS).
//
////////////////////////////////////////////////////////////////////////////////
module.exports = (request, response, next) => {
response.header('Access-Control-Allow-Origin', '*')
response.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
next()
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Document</title>
</head>
<body>
<h1>Custom Middleware Test</h1>
<p>The request that serves this should have CORS set to allow all requests.</p>
</body>
</html>
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment