-
-
Notifications
You must be signed in to change notification settings - Fork 228
Middlewares
Massimo Melina edited this page May 15, 2024
·
16 revisions
A middleware is a mechanism you can add to the server, doing some work on each request.
This can be inside a plugin, but also directly written into Admin > Options > Server code
.
A middleware has the form of a function that receives a Context object as a parameter. The context object contains all information about the http request and the http response.
exports.middleware = ctx => ctx.set('x-my-header', 'some value')
exports.middleware = ctx => {
if (ctx.path === '/some/address')
ctx.body = 'my content'
}
exports.middleware = ctx => ctx.get('user-agent').includes('Chrome') || ctx.socket.destroy()
(from version 0.53.0) Sending back MD5 with a header
exports.init = api => {
const { createHash } = api.require('crypto')
const { Transform } = api.require('stream')
return {
unload: api.events.on('uploadStart', obj => {
const hasher = createHash('md5')
const was = obj.writeStream
obj.writeStream = new Transform({
transform(chunk, encoding, cb) {
hasher.update(chunk)
was.write(chunk, encoding, cb)
},
flush(cb) {
obj.ctx.set({ 'X-MD5': hasher.digest('hex') })
cb()
},
})
})
}
}