Skip to content
Myr

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

7 files+75 added−50 removed

modified:src/helper/factory/index.test.ts+2 added-2 removed
2 unmodified lines
3import { hc } from '../../client'4import type { ClientRequest } from '../../client/types'5import { Hono } from '../../index'6import type { ToSchema, TypedResponse } from '../../types'7import type { StatusCode } from '../../utils/http-status'7import type { ContentfulStatusCode, StatusCode } from '../../utils/http-status'8import { validator } from '../../validator'9import { createFactory, createMiddleware } from './index'1011describe('createMiddleware', () => {
93 unmodified lines
105 $get: {106 input: {}107 output: 'A'108 outputFormat: 'text'109 status: StatusCode109 status: ContentfulStatusCode110 }111 }>112 }>()113 })
171 unmodified lines
modified:src/middleware/bearer-auth/index.ts+2 added-2 removed
modified:src/utils/http-status.ts+3 added
65 unmodified lines
66 | RedirectStatusCode67 | ClientErrorStatusCode68 | ServerErrorStatusCode69 | UnofficialStatusCode7071export type ContentlessStatusCode = 101 | 204 | 205 | 30472export type ContentfulStatusCode = Exclude<StatusCode, ContentlessStatusCode>
modified:src/validator/validator.test.ts+8 added-8 removed
8 unmodified lines
9 MiddlewareHandler,10 ParsedFormValue,11 ValidationTargets,12} from '../types'13import type { StatusCode } from '../utils/http-status'13import type { ContentfulStatusCode } from '../utils/http-status'14import type { Equal, Expect } from '../utils/types'15import type { ValidationFunction } from './validator'16import { validator } from './validator'17
46 unmodified lines
64 query: undefined65 }66 output: 'Valid!'67 outputFormat: 'text'68 status: StatusCode68 status: ContentfulStatusCode69 }70 }71 }72
403 unmodified lines
476 id: number477 }478 }479 outputFormat: 'json'480 status: StatusCode480 status: ContentfulStatusCode481 }482 }483 }484
54 unmodified lines
539 title: string540 }541 }542 outputFormat: 'json'543 status: StatusCode543 status: ContentfulStatusCode544 }545 }546 }547
280 unmodified lines
828 page: number829 title: string830 }831 outputFormat: 'json'832 status: StatusCode832 status: ContentfulStatusCode833 }834 }835 }836
55 unmodified lines
892 }893 }894 output: 'Valid!'895 outputFormat: 'text'896 status: StatusCode896 status: ContentfulStatusCode897 }898 }899 }900
39 unmodified lines
940 output: {941 success: boolean942 }943 outputFormat: 'json'944 status: StatusCode944 status: ContentfulStatusCode945 }946 }947 }948
248 unmodified lines
1197 output: {1198 page: number1199 }1200 outputFormat: 'json'1201 status: StatusCode1201 status: ContentfulStatusCode1202 }1203 }1204 }1205
4 unmodified lines
modified:src/context.ts+20 added-17 removed
9 unmodified lines
10 TypedResponse,11} from './types'12import type { ResponseHeader } from './utils/headers'13import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html'14import type { RedirectStatusCode, StatusCode } from './utils/http-status'14import type { ContentfulStatusCode, RedirectStatusCode, StatusCode } from './utils/http-status'15import type { BaseMime } from './utils/mime'16import type {17 InvalidJSONValue,18 IsAny,
94 unmodified lines
113114/**115 * Interface for responding with a body.116 */117interface BodyRespond extends NewResponse {}117interface 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}123124/**125 * Interface for responding with text.126 *
7 unmodified lines
134 *135 * @returns {Response & TypedResponse<T, U, 'text'>} - The response after rendering the text content, typed with the provided text and status code types.136 */137interface 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}148149/**150 * Interface for responding with JSON.
10 unmodified lines
161 */162interface 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 lines
184 * @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 */186type 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 lines
209 */210interface 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 ? Response
500 unmodified lines
718 * 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 lines
738 * ```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 lines
771 * ```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?: HeaderRecord
8 unmodified lines
788 }789790 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 lines
modified:src/http-exception.ts+3 added-3 removed
1 unmodified line
2 * @module3 * This module provides the `HTTPException` class.4 */56import type { StatusCode } from './utils/http-status'6import type { ContentfulStatusCode } from './utils/http-status'78/**9 * Options for creating an `HTTPException`.10 * @property res - Optional response object to use.
33 unmodified lines
44 * ```45 */46export class HTTPException extends Error {47 readonly res?: Response48 readonly status: StatusCode48 readonly status: ContentfulStatusCode4950 /**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 lines
modified:src/types.test.ts+37 added-18 removed
18 unmodified lines
19 ResponseFormat,20 ToSchema,21 TypedResponse,22} from './types'23import type { StatusCode } from './utils/http-status'23import type { ContentfulStatusCode, StatusCode } from './utils/http-status'24import type { Equal, Expect } from './utils/types'25import { validator } from './validator'2627describe('Env', () => {
67 unmodified lines
95 output: {96 message: string97 }98 outputFormat: 'json'99 status: StatusCode99 status: ContentfulStatusCode100 }101 }102 }103 type verify = Expect<Equal<Expected, Actual>>
30 unmodified lines
134 output: {135 message: string136 }137 outputFormat: 'json'138 status: StatusCode138 status: ContentfulStatusCode139 }140 }141 }142 type verify = Expect<Equal<Expected, Actual>>
19 unmodified lines
162 }163 }164 output: 'foo'165 outputFormat: 'text'166 status: StatusCode166 status: ContentfulStatusCode167 }168 }169 }170 type verify = Expect<Equal<Expected, Actual>>
20 unmodified lines
191 }192 }193 output: string194 outputFormat: 'text'195 status: StatusCode195 status: ContentfulStatusCode196 }197 }198 }199 type verify = Expect<Equal<Expected, Actual>>
16 unmodified lines
216 }217 }218 output: string219 outputFormat: 'text'220 status: StatusCode220 status: ContentfulStatusCode221 }222 }223 } & {224 '/foo/:foo/books/:id': {
45 unmodified lines
270 output: {271 success: boolean272 }273 outputFormat: 'json'274 status: StatusCode274 status: ContentfulStatusCode275 }276 }277 }278 type verify = Expect<Equal<Expected, Actual>>
96 unmodified lines
375 $get: {376 input: {}377 output: never378 outputFormat: 'json'379 status: StatusCode379 status: ContentfulStatusCode380 }381 }382 }383 type verify = Expect<Equal<Expected, Actual>>
75 unmodified lines
459 output: {460 message: string461 }462 outputFormat: 'json'463 status: StatusCode463 status: ContentfulStatusCode464 }465 }466 }467 type verify = Expect<Equal<Expected, Actual>>
433 unmodified lines
901 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 lines
973 output: {974 default: boolean975 }976 outputFormat: 'json'977 status: StatusCode977 status: ContentfulStatusCode978 }979 }980 }981 type verify = Expect<Equal<Expected, Actual>>
29 unmodified lines
1011 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 lines
1083 output: {1084 default: boolean1085 }1086 outputFormat: 'json'1087 status: StatusCode1087 status: ContentfulStatusCode1088 }1089 }1090 }1091 type verify = Expect<Equal<Expected, Actual>>
18 unmodified lines
1110 output: {1111 ok: boolean1112 }1113 outputFormat: 'json'1114 status: StatusCode1114 status: ContentfulStatusCode1115 }1116 }1117 }1118 type verify = Expect<Equal<Expected, Actual>>
1151 unmodified lines
2270 type Expected = { data: string }2271 expectTypeOf<Actual>().toEqualTypeOf<Expected>()2272 })2273})2274describe('status code', () => {2275 const app = new Hono()22762277 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})