Skip to content
This repository has been archived by the owner on Jun 27, 2024. It is now read-only.

Commit

Permalink
refactor: use new c.exception() everywhere (#175)
Browse files Browse the repository at this point in the history
* refactor: use new `c.exception()` everywhere

* fmt

* fix issues
  • Loading branch information
boywithkeyboard authored Aug 16, 2023
1 parent b69de26 commit 635fd01
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 30 deletions.
11 changes: 7 additions & 4 deletions cheetah.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
import { base, Method } from './base.ts'
import { Collection } from './collection.ts'
import { Context } from './context.ts'
import { Exception } from './exception.ts'
import { Extension, validExtension } from './extensions.ts'
import { Handler, HandlerOrSchema, Payload } from './handler.ts'
import { OAuthStore } from './oauth/mod.ts'
import { OAuthSessionData } from './oauth/types.ts'
import { ResponseContext } from './response_context.ts'
import { Exception } from './context.ts'
import { Exception as OriginalException } from './exception.ts'

export type AppContext = {
env: Record<string, unknown> | undefined
Expand Down Expand Up @@ -341,7 +342,7 @@ export class cheetah extends base<cheetah>() {

if (!route) {
if (!this.#notFound) {
throw new Exception(404)
throw new Exception('Not Found', undefined, 404)
}

if (req.method !== 'HEAD') {
Expand Down Expand Up @@ -381,7 +382,7 @@ export class cheetah extends base<cheetah>() {
} catch (err) {
let res: Response

if (err instanceof Exception) {
if (err instanceof Exception || err instanceof OriginalException) {
res = err.response(req)
} else {
if (this.#debug) {
Expand All @@ -391,7 +392,9 @@ export class cheetah extends base<cheetah>() {
if (this.#error) {
res = await this.#error(err, req)
} else {
res = new Exception('Something Went Wrong').response(req)
res = new Exception('Something Went Wrong', undefined, 500).response(
req,
)
}
}

Expand Down
11 changes: 9 additions & 2 deletions context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const HTTP_MESSAGES = {
'Gone': 410,
'Length Required': 411,
'Precondition Failed': 412,
'Upload Limit Exceeded': 413,
'Content Too Large': 413,
'URI Too Long': 414,
'Unsupported Media Type': 415,
'Range Not Satisfiable': 416,
Expand Down Expand Up @@ -110,7 +110,13 @@ export class Context<
return this.#req
}

this.#req = new RequestContext(this.#a, this.#p, this.#r, this.#s)
this.#req = new RequestContext(
this.#a,
this.#p,
this.#r,
this.#s,
this.exception,
)

return this.#req
}
Expand All @@ -136,6 +142,7 @@ export class Context<
}
}

/** @private */
export class Exception {
public response

Expand Down
7 changes: 3 additions & 4 deletions oauth/handle_callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
getUser,
} from 'https://deno.land/x/authenticus@v2.0.3/mod.ts'
import { Context } from '../context.ts'
import { Exception } from '../exception.ts'
import { getVariable } from '../x/env.ts'
import { sign, verify } from '../x/jwt.ts'
import { LocationData } from '../x/location_data.ts'
Expand All @@ -31,7 +30,7 @@ export async function handleCallback(
typeof c.req.query.state !== 'string' ||
typeof c.req.query.code !== 'string'
) {
throw new Exception('Bad Request')
throw c.exception('Bad Request')
}

// validate state
Expand All @@ -43,7 +42,7 @@ export async function handleCallback(
)

if (!payload || payload.ip !== c.req.ip) {
throw new Exception('Access Denied')
throw c.exception('Access Denied')
}

try {
Expand Down Expand Up @@ -125,6 +124,6 @@ export async function handleCallback(
...data,
}
} catch (_err) {
throw new Exception('Bad Request')
throw c.exception('Bad Request')
}
}
19 changes: 12 additions & 7 deletions request_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from 'https://deno.land/x/zod@v3.21.4/types.ts'
import { Method } from './base.ts'
import { BaseType, ObjectType } from './handler.ts'
import { AppContext, Exception } from './mod.ts'
import { AppContext, Context } from './mod.ts'

type Static<T extends ZodType> = T extends ZodType ? z.infer<T>
: never
Expand All @@ -30,6 +30,7 @@ export class RequestContext<
#q: Record<string, unknown> | undefined
#r
#s
#e

constructor(
a: AppContext,
Expand All @@ -42,11 +43,13 @@ export class RequestContext<
query?: ObjectType | undefined
[key: string]: unknown
} | null,
e: Context['exception'],
) {
this.#a = a
this.#p = p
this.#r = r
this.#s = s
this.#e = e
}

get ip(): string {
Expand Down Expand Up @@ -127,13 +130,15 @@ export class RequestContext<
}
}
} catch (err: unknown) {
throw new Exception(err instanceof DeadlineError ? 413 : 400)
throw this.#e(
err instanceof DeadlineError ? 'Content Too Large' : 'Bad Request',
)
}

const result = this.#s.body.safeParse(body)

if (!result.success) {
throw new Exception(400)
throw this.#e('Bad Request')
}

return result.data
Expand All @@ -153,7 +158,7 @@ export class RequestContext<
const header = this.#r.headers.get('cookies') ?? ''

if (header.length > 1000) {
throw new Exception(413)
throw this.#e('Content Too Large')
}

this.#c = header
Expand All @@ -173,7 +178,7 @@ export class RequestContext<
const isValid = this.#s.cookies.safeParse(this.#c).success

if (!isValid) {
throw new Exception(400)
throw this.#e('Bad Request')
}

return this.#c as [ValidatedCookies] extends [never] ? never
Expand Down Expand Up @@ -212,7 +217,7 @@ export class RequestContext<
const isValid = this.#s.headers.safeParse(this.#h).success

if (!isValid) {
throw new Exception(400)
throw this.#e('Bad Request')
}
}

Expand Down Expand Up @@ -262,7 +267,7 @@ export class RequestContext<
const isValid = this.#s.query.safeParse(this.#q).success

if (!isValid) {
throw new Exception(400)
throw this.#e('Bad Request')
}
}

Expand Down
1 change: 1 addition & 0 deletions test/deps.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { assertEquals } from 'https://deno.land/std@0.198.0/assert/assert_equals.ts'
export { assertInstanceOf } from 'https://deno.land/std@0.198.0/assert/assert_instance_of.ts'
export { z } from 'https://deno.land/x/zod@v3.21.4/mod.ts'
5 changes: 4 additions & 1 deletion test/exception.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// Copyright 2023 Samuel Kopp. All rights reserved. Apache-2.0 license.
import cheetah, { Exception } from '../mod.ts'
import cheetah from '../mod.ts'
import { assertEquals } from './deps.ts'
import { Exception } from '../exception.ts'

// TODO write test suite for new c.exception() instead

Deno.test('Exception', async () => {
const app = new cheetah()
Expand Down
8 changes: 0 additions & 8 deletions test/preflight_mode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,20 +87,12 @@ Deno.test('preflight mode', async (t) => {
const res1 = await app.fetch(new Request('https://deno.com/foo'))

assertEquals(res1.body === null, false)
assertEquals(
res1.headers.get('content-length'),
'Something Went Wrong'.length.toString(),
)

const res2 = await app.fetch(
new Request('https://deno.com/foo', { method: 'HEAD' }),
)

assertEquals(res2.body === null, true)
assertEquals(
res2.headers.get('content-length'),
'Something Went Wrong'.length.toString(),
)
})

await t.step('error (custom)', async () => {
Expand Down
5 changes: 1 addition & 4 deletions x/x.test.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
// Copyright 2023 Samuel Kopp. All rights reserved. Apache-2.0 license.
/** @jsx h */
import {
assertEquals,
assertInstanceOf,
} from 'https://deno.land/std@0.198.0/testing/asserts.ts'
import { cheetah } from '../cheetah.ts'
import { assertEquals, assertInstanceOf } from '../test/deps.ts'
import { h, jsx } from './jsx.tsx'
import { createKey, importKey, sign, verify } from './jwt.ts'

Expand Down

0 comments on commit 635fd01

Please sign in to comment.