feat(hono/context): contentful status code typing (#3763)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Anthony Skorupskyy · committed by GitHub · parent 7751ff3 · Browse files · 7 files·+75 added−50 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+75 added−50 removed
- tests:+47 added−28 removed
- other:+28 added−22 removed
Provenance
- Commit
bfd839a- Tree
fa56d49- Author
Anthony Skorupskyy <50280805+askorupskyy@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
7751ff3
7 files changed+75 added−50 removed
modified:src/helper/factory/index.test.ts+2 added-2 removed
2 unmodified lines3 import { hc } from '../../client'4 import type { ClientRequest } from '../../client/types'5 import { Hono } from '../../index'6 import type { ToSchema, TypedResponse } from '../../types'7-import type { StatusCode } from '../../utils/http-status'7+import type { ContentfulStatusCode, StatusCode } from '../../utils/http-status'8 import { validator } from '../../validator'9 import { createFactory, createMiddleware } from './index'10 11 describe('createMiddleware', () => {93 unmodified lines105 $get: {106 input: {}107 output: 'A'108 outputFormat: 'text'109- status: StatusCode109+ status: ContentfulStatusCode110 }111 }>112 }>()113 })171 unmodified linesmodified:src/middleware/bearer-auth/index.ts+2 added-2 removed
5 unmodified lines678910101112131471 unmodified lines8687888990909192939465 unmodified lines5 unmodified linesimport type { Context } from '../../context'import { HTTPException } from '../../http-exception'import type { MiddlewareHandler } from '../../types'import { timingSafeEqual } from '../../utils/buffer'import type { StatusCode } from '../../utils/http-status'import type { ContentfulStatusCode } from '../../utils/http-status'
const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'const PREFIX = 'Bearer'const HEADER = 'Authorization'71 unmodified lines const wwwAuthenticatePrefix = options.prefix === '' ? '' : `${options.prefix} `
const throwHTTPException = async ( c: Context, status: StatusCode, status: ContentfulStatusCode, wwwAuthenticateHeader: string, messageOption: string | object | MessageFunction ): Promise<Response> => { const headers = {65 unmodified linesmodified:src/utils/http-status.ts+3 added
65 unmodified lines66 | RedirectStatusCode67 | ClientErrorStatusCode68 | ServerErrorStatusCode69 | UnofficialStatusCode70+71+export type ContentlessStatusCode = 101 | 204 | 205 | 30472+export type ContentfulStatusCode = Exclude<StatusCode, ContentlessStatusCode>modified:src/validator/validator.test.ts+8 added-8 removed
8 unmodified lines9 MiddlewareHandler,10 ParsedFormValue,11 ValidationTargets,12 } from '../types'13-import type { StatusCode } from '../utils/http-status'13+import type { ContentfulStatusCode } from '../utils/http-status'14 import type { Equal, Expect } from '../utils/types'15 import type { ValidationFunction } from './validator'16 import { validator } from './validator'17 46 unmodified lines64 query: undefined65 }66 output: 'Valid!'67 outputFormat: 'text'68- status: StatusCode68+ status: ContentfulStatusCode69 }70 }71 }72 403 unmodified lines476 id: number477 }478 }479 outputFormat: 'json'480- status: StatusCode480+ status: ContentfulStatusCode481 }482 }483 }484 54 unmodified lines539 title: string540 }541 }542 outputFormat: 'json'543- status: StatusCode543+ status: ContentfulStatusCode544 }545 }546 }547 280 unmodified lines828 page: number829 title: string830 }831 outputFormat: 'json'832- status: StatusCode832+ status: ContentfulStatusCode833 }834 }835 }836 55 unmodified lines892 }893 }894 output: 'Valid!'895 outputFormat: 'text'896- status: StatusCode896+ status: ContentfulStatusCode897 }898 }899 }900 39 unmodified lines940 output: {941 success: boolean942 }943 outputFormat: 'json'944- status: StatusCode944+ status: ContentfulStatusCode945 }946 }947 }948 248 unmodified lines1197 output: {1198 page: number1199 }1200 outputFormat: 'json'1201- status: StatusCode1201+ status: ContentfulStatusCode1202 }1203 }1204 }1205 4 unmodified linesmodified:src/context.ts+20 added-17 removed
9 unmodified lines10 TypedResponse,11 } from './types'12 import type { ResponseHeader } from './utils/headers'13 import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html'14-import type { RedirectStatusCode, StatusCode } from './utils/http-status'14+import type { ContentfulStatusCode, RedirectStatusCode, StatusCode } from './utils/http-status'15 import type { BaseMime } from './utils/mime'16 import type {17 InvalidJSONValue,18 IsAny,94 unmodified lines113 114 /**115 * Interface for responding with a body.116 */117-interface BodyRespond extends NewResponse {}117+interface BodyRespond {118+ // if we return content, only allow the status codes that allow for returning the body119+ (data: Data, status?: ContentfulStatusCode, headers?: HeaderRecord): Response120+ (data: null, status?: StatusCode, headers?: HeaderRecord): Response121+ (data: Data | null, init?: ResponseInit): Response122+}123 124 /**125 * Interface for responding with text.126 *7 unmodified lines134 *135 * @returns {Response & TypedResponse<T, U, 'text'>} - The response after rendering the text content, typed with the provided text and status code types.136 */137 interface TextRespond {133- <T extends string, U extends StatusCode = StatusCode>(138+ <T extends string, U extends ContentfulStatusCode = ContentfulStatusCode>(139 text: T,140 status?: U,141 headers?: HeaderRecord142 ): Response & TypedResponse<T, U, 'text'>138- <T extends string, U extends StatusCode = StatusCode>(text: T, init?: ResponseInit): Response &139- TypedResponse<T, U, 'text'>143+ <T extends string, U extends ContentfulStatusCode = ContentfulStatusCode>(144+ text: T,145+ init?: ResponseInit146+ ): Response & TypedResponse<T, U, 'text'>147 }148 149 /**150 * Interface for responding with JSON.10 unmodified lines161 */162 interface JSONRespond {163 <164 T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,158- U extends StatusCode = StatusCode165+ U extends ContentfulStatusCode = ContentfulStatusCode166 >(167 object: T,168 status?: U,169 headers?: HeaderRecord170 ): JSONRespondReturn<T, U>171 <172 T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,166- U extends StatusCode = StatusCode173+ U extends ContentfulStatusCode = ContentfulStatusCode174 >(175 object: T,176 init?: ResponseInit177 ): JSONRespondReturn<T, U>6 unmodified lines184 * @returns {Response & TypedResponse<SimplifyDeepArray<T> extends JSONValue ? (JSONValue extends SimplifyDeepArray<T> ? never : JSONParsed<T>) : never, U, 'json'>} - The response after rendering the JSON object, typed with the provided object and status code types.185 */186 type JSONRespondReturn<187 T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,181- U extends StatusCode188+ U extends ContentfulStatusCode189 > = Response &190 TypedResponse<191 SimplifyDeepArray<T> extends JSONValue192 ? JSONValue extends SimplifyDeepArray<T>16 unmodified lines209 */210 interface HTMLRespond {211 <T extends string | Promise<string>>(212 html: T,206- status?: StatusCode,213+ status?: ContentfulStatusCode,214 headers?: HeaderRecord215 ): T extends string ? Response : Promise<Response>216 <T extends string | Promise<string>>(html: T, init?: ResponseInit): T extends string217 ? Response500 unmodified lines718 * return c.body('Thank you for coming')719 * })720 * ```721 */715- body: BodyRespond = (716- data: Data | null,717- arg?: StatusCode | ResponseInit,718- headers?: HeaderRecord719- ): Response => {722+ body: BodyRespond = (data, arg?: StatusCode | RequestInit, headers?: HeaderRecord) => {723 return typeof arg === 'number'724 ? this.#newResponse(data, arg, headers)725 : this.#newResponse(data, arg)726 }11 unmodified lines738 * ```739 */740 text: TextRespond = (741 text: string,739- arg?: StatusCode | ResponseInit,742+ arg?: ContentfulStatusCode | ResponseInit,743 headers?: HeaderRecord744 ): ReturnType<TextRespond> => {745 // If the header is empty, return Response immediately.746 // Content-Type will be added automatically as `text/plain`.24 unmodified lines771 * ```772 */773 json: JSONRespond = <774 T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,772- U extends StatusCode = StatusCode775+ U extends ContentfulStatusCode = ContentfulStatusCode776 >(777 object: T,778 arg?: U | ResponseInit,779 headers?: HeaderRecord8 unmodified lines788 }789 790 html: HTMLRespond = (791 html: string | Promise<string>,789- arg?: StatusCode | ResponseInit,792+ arg?: ContentfulStatusCode | ResponseInit,793 headers?: HeaderRecord794 ): Response | Promise<Response> => {795 this.#preparedHeaders ??= {}796 this.#preparedHeaders['content-type'] = 'text/html; charset=UTF-8'55 unmodified linesmodified:src/http-exception.ts+3 added-3 removed
1 unmodified line2 * @module3 * This module provides the `HTTPException` class.4 */5 6-import type { StatusCode } from './utils/http-status'6+import type { ContentfulStatusCode } from './utils/http-status'7 8 /**9 * Options for creating an `HTTPException`.10 * @property res - Optional response object to use.33 unmodified lines44 * ```45 */46 export class HTTPException extends Error {47 readonly res?: Response48- readonly status: StatusCode48+ readonly status: ContentfulStatusCode49 50 /**51 * Creates an instance of `HTTPException`.52 * @param status - HTTP status code for the exception. Defaults to 500.53 * @param options - Additional options for the exception.54 */55- constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {55+ constructor(status: ContentfulStatusCode = 500, options?: HTTPExceptionOptions) {56 super(options?.message, { cause: options?.cause })57 this.res = options?.res58 this.status = status59 }19 unmodified linesmodified:src/types.test.ts+37 added-18 removed
18 unmodified lines19 ResponseFormat,20 ToSchema,21 TypedResponse,22 } from './types'23-import type { StatusCode } from './utils/http-status'23+import type { ContentfulStatusCode, StatusCode } from './utils/http-status'24 import type { Equal, Expect } from './utils/types'25 import { validator } from './validator'26 27 describe('Env', () => {67 unmodified lines95 output: {96 message: string97 }98 outputFormat: 'json'99- status: StatusCode99+ status: ContentfulStatusCode100 }101 }102 }103 type verify = Expect<Equal<Expected, Actual>>30 unmodified lines134 output: {135 message: string136 }137 outputFormat: 'json'138- status: StatusCode138+ status: ContentfulStatusCode139 }140 }141 }142 type verify = Expect<Equal<Expected, Actual>>19 unmodified lines162 }163 }164 output: 'foo'165 outputFormat: 'text'166- status: StatusCode166+ status: ContentfulStatusCode167 }168 }169 }170 type verify = Expect<Equal<Expected, Actual>>20 unmodified lines191 }192 }193 output: string194 outputFormat: 'text'195- status: StatusCode195+ status: ContentfulStatusCode196 }197 }198 }199 type verify = Expect<Equal<Expected, Actual>>16 unmodified lines216 }217 }218 output: string219 outputFormat: 'text'220- status: StatusCode220+ status: ContentfulStatusCode221 }222 }223 } & {224 '/foo/:foo/books/:id': {45 unmodified lines270 output: {271 success: boolean272 }273 outputFormat: 'json'274- status: StatusCode274+ status: ContentfulStatusCode275 }276 }277 }278 type verify = Expect<Equal<Expected, Actual>>96 unmodified lines375 $get: {376 input: {}377 output: never378 outputFormat: 'json'379- status: StatusCode379+ status: ContentfulStatusCode380 }381 }382 }383 type verify = Expect<Equal<Expected, Actual>>75 unmodified lines459 output: {460 message: string461 }462 outputFormat: 'json'463- status: StatusCode463+ status: ContentfulStatusCode464 }465 }466 }467 type verify = Expect<Equal<Expected, Actual>>433 unmodified lines901 output: {902 ng: boolean903 }904 outputFormat: 'json'905- status: StatusCode905+ status: ContentfulStatusCode906 }907 | {908 input: {}909 output: {910 ok: boolean911 }912 outputFormat: 'json'913- status: StatusCode913+ status: ContentfulStatusCode914 }915 | {916 input: {}917 output: {918 default: boolean919 }920 outputFormat: 'json'921- status: StatusCode921+ status: ContentfulStatusCode922 }923 }924 }925 type verify = Expect<Equal<Expected, Actual>>47 unmodified lines973 output: {974 default: boolean975 }976 outputFormat: 'json'977- status: StatusCode977+ status: ContentfulStatusCode978 }979 }980 }981 type verify = Expect<Equal<Expected, Actual>>29 unmodified lines1011 output: {1012 ng: boolean1013 }1014 outputFormat: 'json'1015- status: StatusCode1015+ status: ContentfulStatusCode1016 }1017 | {1018 input: {}1019 output: {1020 ok: boolean1021 }1022 outputFormat: 'json'1023- status: StatusCode1023+ status: ContentfulStatusCode1024 }1025 | {1026 input: {}1027 output: {1028 default: boolean1029 }1030 outputFormat: 'json'1031- status: StatusCode1031+ status: ContentfulStatusCode1032 }1033 }1034 }1035 type verify = Expect<Equal<Expected, Actual>>47 unmodified lines1083 output: {1084 default: boolean1085 }1086 outputFormat: 'json'1087- status: StatusCode1087+ status: ContentfulStatusCode1088 }1089 }1090 }1091 type verify = Expect<Equal<Expected, Actual>>18 unmodified lines1110 output: {1111 ok: boolean1112 }1113 outputFormat: 'json'1114- status: StatusCode1114+ status: ContentfulStatusCode1115 }1116 }1117 }1118 type verify = Expect<Equal<Expected, Actual>>1151 unmodified lines2270 type Expected = { data: string }2271 expectTypeOf<Actual>().toEqualTypeOf<Expected>()2272 })2273 })2274+describe('status code', () => {2275+ const app = new Hono()2276+2277+ it('should only allow to return .json() with contentful status codes', async () => {2278+ const route = app.get('/', async (c) => c.json({}))2279+ type Actual = ExtractSchema<typeof route>['/']['$get']['status']2280+ expectTypeOf<Actual>().toEqualTypeOf<ContentfulStatusCode>()2281+ })2282+ it('should only allow to return .body(null) with all status codes', async () => {2283+ const route = app.get('/', async (c) => c.body(null))2284+ type Actual = ExtractSchema<typeof route>['/']['$get']['status']2285+ expectTypeOf<Actual>().toEqualTypeOf<StatusCode>()2286+ })2287+ it('should only allow to return .text() with contentful status codes', async () => {2288+ const route = app.get('/', async (c) => c.text('whatever'))2289+ type Actual = ExtractSchema<typeof route>['/']['$get']['status']2290+ expectTypeOf<Actual>().toEqualTypeOf<ContentfulStatusCode>()2291+ })2292+})