Skip to content

Commit

Permalink
feat: add support for dnsPrefetch
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Oct 26, 2019
1 parent ca80ed9 commit f7b466a
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
6 changes: 6 additions & 0 deletions adonis-typings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,10 @@ declare module '@ioc:Adonis/Addons/Shield' {
export type IENoOpenOptions = {
enabled: boolean,
}

// X-DNS-Prefetch-Control
export type DnsPrefetchOptions = {
enabled: boolean,
allow?: boolean,
}
}
30 changes: 30 additions & 0 deletions src/dnsPrefetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* @adonisjs/shield
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

/// <reference path="../adonis-typings/index.ts" />

import { DnsPrefetchOptions } from '@ioc:Adonis/Addons/Shield'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { noop } from './noop'

/**
* Adds `X-Content-Type-Options` header based upon given
* user options
*/
export function dnsPrefetch (options: DnsPrefetchOptions) {
if (!options.enabled) {
return noop
}

const value = options.allow ? 'on' : 'off'

return function dnsPrefetchMiddlewareFn ({ response }: HttpContextContract) {
response.header('X-DNS-Prefetch-Control', value)
}
}
38 changes: 38 additions & 0 deletions test/dns-prefetch.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* @adonisjs/shield
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

import test from 'japa'
import { HttpContext } from '@adonisjs/http-server/build/standalone'
import { dnsPrefetch } from '../src/dnsPrefetch'

test.group('Dns Prefetch', () => {
test('return noop function when enabled is false', (assert) => {
const middlewareFn = dnsPrefetch({ enabled: false })
const ctx = HttpContext.create('/', {}, {}, {}, {})
middlewareFn(ctx)

assert.isUndefined(ctx.response.getHeader('X-DNS-Prefetch-Control'))
})

test('set X-DNS-Prefetch-Control header', (assert) => {
const middlewareFn = dnsPrefetch({ enabled: true, allow: true })
const ctx = HttpContext.create('/', {}, {}, {}, {})
middlewareFn(ctx)

assert.equal(ctx.response.getHeader('X-DNS-Prefetch-Control'), 'on')
})

test('set X-DNS-Prefetch-Control header to off', (assert) => {
const middlewareFn = dnsPrefetch({ enabled: true, allow: false })
const ctx = HttpContext.create('/', {}, {}, {}, {})
middlewareFn(ctx)

assert.equal(ctx.response.getHeader('X-DNS-Prefetch-Control'), 'off')
})
})

0 comments on commit f7b466a

Please sign in to comment.