Optional
options: IApiKeyOptionsCustom options.
The new middleware.
import assert from 'assert'
import createServer, { ApiKeyValidator, HttpRequestHandler, IHttpRequest, IHttpResponse, apiKey } from '@egomobile/http-server'
// custom validator function
const myApiKeyValidator: ApiKeyValidator =
async (request: IHttpRequest) => request.headers['x-key'] === 'mySecretApiKey3'
// custom error handler
const onValidationFailed: HttpRequestHandler = async (request: IHttpRequest, response: IHttpResponse) => {
const errorMessage = Buffer.from('Wrong API key!', 'utf8')
response.writeHead(403, {
'Content-Length': String(errorMessage.length)
});
response.write(errorMessage)
}
const app = createServer()
// check 'x-api-key' header for 'mySecretApiKey1'
app.get('/foo', [apiKey('mySecretApiKey1')], async (request: IHttpRequest, response: IHttpResponse) => {
assert.strictEqual(request.headers['x-api-key'], 'mySecretApiKey1')
})
// check 'x-key' header for 'mySecretApiKey2'
app.get('/bar', [apiKey('mySecretApiKey2', 'x-key')], async (request: IHttpRequest, response: IHttpResponse) => {
assert.strictEqual(request.headers['x-key'], 'mySecretApiKey2')
})
// use function to validate
app.get('/baz', [apiKey(myApiKeyValidator)], async (request: IHttpRequest, response: IHttpResponse) => {
assert.strictEqual(request.headers['x-key'], 'mySecretApiKey3')
})
// with custom error handler
app.get('/test', [apiKey(myApiKeyValidator, onValidationFailed)], async (request: IHttpRequest, response: IHttpResponse) => {
assert.strictEqual(request.headers['x-key'], 'mySecretApiKey3')
})
Optional
onValidationFailed: HttpRequestHandlerOptional
onValidationFailed: Nilable<HttpRequestHandler>Generated using TypeDoc
Creates a middleware, that checks for an API key.