Skip to content

Commit

Permalink
feat: add debug option to app
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Nov 19, 2020
1 parent 824d879 commit b0891cd
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 10 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ server.listen(port, () => {
## utils

- `send (req, data, type)`
- `error (req, error, code)`
- `error (req, error, debug, code)`
- `redirect (req, location, code)`
- `lazy (handle)`

Expand Down
6 changes: 3 additions & 3 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { IncomingMessage, ServerResponse } from 'http'
import type { Stack, InputLayer, Handle, App } from './types'
import type { Stack, InputLayer, Handle, App, AppOptions } from './types'
import { promisifyHandle } from './promisify'
import { send, error, MIMES } from './utils'

export function createApp (): App {
export function createApp (options: AppOptions = {}): App {
const stack: Stack = []

async function unsafeHandle (req: IncomingMessage, res: ServerResponse) {
Expand Down Expand Up @@ -42,7 +42,7 @@ export function createApp (): App {
}

const handle: Handle = function (req: IncomingMessage, res: ServerResponse) {
return unsafeHandle(req, res).catch((err: Error | any) => { error(res, err) })
return unsafeHandle(req, res).catch((err: Error | any) => { error(res, err, options.debug) })
}

function use (route: string, handle: Handle) {
Expand Down
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,7 @@ export interface App {
unsafeHandle: Handle
use: (route: string, handle: Handle) => void
}

export interface AppOptions {
debug?: boolean
}
11 changes: 5 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,17 @@ export function defaultContentType (res: ServerResponse, type: string) {
}
}

export function error (res: ServerResponse, error: Error | string, code?: number) {
// @ts-ignore
res._error = error

export function error (res: ServerResponse, error: Error | string, debug?: boolean, code?: number) {
res.statusCode = code || (res.statusCode !== 200)
? res.statusCode
// @ts-ignore
: (error.status || error.statusCode || 500)

const message = error.toString()
if (debug) {
console.error(error) // eslint-disable-line no-console
}

res.end(res.statusCode + ' - ' + message)
res.end(`'"Internal error (${res.statusCode})"`)
}

export function redirect (res: ServerResponse, location: string, code = 302) {
Expand Down

0 comments on commit b0891cd

Please sign in to comment.