Skip to content

Commit

Permalink
feat!: export options types and update options
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Apr 4, 2022
1 parent 5efaec0 commit fc80f7c
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 17 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ A mapping from handler to placeholder. Values can be `String` or `Buffer`. You c

A mapping from handler to the mime type. Mime type will be set as `Content-Type` header. You can disable sending any of the mimes by setting the value to `false`.

### `noCache`
### `cacheHeaders`

- Default: `true`

Expand All @@ -115,7 +115,7 @@ When enabled, these headers will be sent:
}
```

### `addPlaceholderHeader`
### `placeholderHeader`

- Default: `true`

Expand Down
53 changes: 50 additions & 3 deletions src/defaults.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,58 @@
export const defaultOptions = {
export interface ServePlaceholderOptions {
/**
* Sets `statusCode` for all handled responses. Set to `false` to disable overriding statusCode.
*
* @default 404
*/
statusCode?: number

/**
* Skip middleware when no handler is defined for the current request.
* Please note that if this option is set to `true`, then `default` handler will be disabled
* @default false
*/
skipUnknown?: boolean

/**
* Set headers to prevent accidentally caching 404 resources.
*
* @default true
*/
cacheHeaders?: boolean

/**
* Sets an `X-Placeholder` header with value of handler name.
*
* @default true
*/
placeholderHeader?: boolean

/**
* A mapping from file extensions to the handler. Extensions should start with *dot* like `.js`.
* You can disable any of the handlers by setting the value to `null`
* If the value of a handler is set to `false`, the middleware will be ignored for that extension.
*/
handlers?: Record<string, string|false>

/**
* A mapping from handler to placeholder. Values can be `String` or `Buffer`. You can disable any of the placeholders by setting the value to `false`.
*/
placeholders?: Record<string, string|undefined>

/**
* A mapping from handler to the mime type. Mime type will be set as `Content-Type` header. You can disable sending any of the mimes by setting the value to `false`.
*/
mimes?: Record<string, string|undefined>
}

export const DefaultOptions: ServePlaceholderOptions = {
statusCode: 404,

skipUnknown: false,

noCache: true,
cacheHeaders: true,

addPlaceholderHeader: true,
placeholderHeader: true,

handlers: {
// css
Expand Down
11 changes: 5 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import type { IncomingMessage, ServerResponse } from 'http'
import defu from 'defu'
import { defaultOptions } from './defaults'

import { ServePlaceholderOptions, DefaultOptions } from './defaults'
export type ServerMiddleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void

const EXT_REGEX = /\.[a-zA-Z0-9]+$/

export function servePlaceholder (_options): ServerMiddleware {
export function servePlaceholder (_options: ServePlaceholderOptions): ServerMiddleware {
// Assign default options
const options = defu(_options, defaultOptions)
const options: ServePlaceholderOptions = defu(_options, DefaultOptions)

return function servePlaceholderMiddleware (req, res, next) {
// If response already sent, skip
Expand Down Expand Up @@ -53,14 +52,14 @@ export function servePlaceholder (_options): ServerMiddleware {
}

// Prevent caching
if (options.noCache) {
if (options.cacheHeaders) {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate') // HTTP 1.1
res.setHeader('Pragma', 'no-cache') // HTTP 1.0
res.setHeader('Expires', '0') // Proxies
}

// Add X- header
if (options.addPlaceholderHeader) {
if (options.placeholderHeader) {
res.setHeader('X-Placeholder', handler)
}

Expand Down
12 changes: 6 additions & 6 deletions test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { createApp } from 'h3'
import { listen } from 'listhen'
import { fetch } from 'ohmyfetch'
import { servePlaceholder } from '../src'
import { defaultOptions } from '../src/defaults'
import { DefaultOptions } from '../src/defaults'

describe('basic', () => {
describe('default', () => {
let app, listener, _fetch

beforeAll(async () => {
Expand Down Expand Up @@ -39,25 +39,25 @@ describe('basic', () => {
})

// Test all handlers
const handlersToTest = Object.entries(defaultOptions.handlers).map(([ext, handler]) => ({ ext, handler }))
const handlersToTest = Object.entries(DefaultOptions.handlers).map(([ext, handler]) => ({ ext, handler }))
handlersToTest.push({ ext: '.unknown', handler: 'default ' })
for (const { ext, handler } of handlersToTest) {
it('Handler for ' + ext, async () => {
const res = await _fetch(listener.url + `assets/foo${ext}`)
expect(await res.text()).toMatchObject(defaultOptions.placeholders[handler] || '')
expect(await res.text()).toMatchObject(DefaultOptions.placeholders[handler] || '')
})
}
})

describe('skipUnknown', () => {
describe('withOptions', () => {
let app, listener, _fetch

beforeAll(async () => {
app = createApp()
app.use('/test', () => 'Works!')
app.use(servePlaceholder({
skipUnknown: true,
noCache: false,
cacheHeaders: false,
handlers: {
'.skipme': false
}
Expand Down

0 comments on commit fc80f7c

Please sign in to comment.