feat: auto set `statusText` (#93)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* refactor: context * tweak * feat: auto set status text
authored by Yusuke Wada · committed by GitHub · parent c883563 · Browse files · 6 files·+75 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+75 added−20 removed
- tests:+21 added−8 removed
- other:+54 added−12 removed
Provenance
- Commit
a72660b- Tree
d73a05c- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
c883563
6 files changed+75 added−20 removed
added:src/utils/http-status.test.ts+7 added
1234567import { getStatusText } from './http-status'
describe('http-status utility', () => { it('getStatusText', () => { expect(getStatusText(200)).toBe('OK') })})added:src/utils/http-status.ts+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243export const getStatusText = (statusNumber: number): string => { const text = statuses[statusNumber] return text}
const statuses: { [key: number]: string } = { 200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content', 206: 'Partial Content', 301: 'Moved Permanently', 302: 'Moved Temporarily', 303: 'See Other', 304: 'Not Modified', 307: 'Temporary Redirect', 308: 'Permanent Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Not Allowed', 406: 'Not Acceptable', 408: 'Request Time-out', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Large', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 421: 'Misdirected Request', 429: 'Too Many Requests', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Temporarily Unavailable', 504: 'Gateway Time-out', 505: 'HTTP Version Not Supported', 507: 'Insufficient Storage',}modified:src/context.ts+10 added-10 removed
1234567893 unmodified lines13141516171819202119 unmodified lines414243444546474849505152454647484953545556575 unmodified lines6364656663646768697071727372747576777810 unmodified lines8990919291939495969 unmodified lines1061071081091091101111121139 unmodified linesimport { isAbsoluteURL } from './utils/url'import { getStatusText } from './utils/http-status'
type Headers = { [key: string]: string }type Data = string | ArrayBuffer | ReadableStream
export interface Env {}
export class Context {3 unmodified lines event: FetchEvent private _headers: Headers private _status: number private _statusText: string
render: (template: string, params?: object, options?: object) => Promise<Response>
constructor(req: Request, opts?: { res: Response; env: Env; event: FetchEvent }) { this.req = req19 unmodified lines this._headers[name] = value }
status(number: number): void { if (this.res) { console.warn('c.res.status is already setted.') return } this._status = number this._statusText = getStatusText(number) }
statusText(text: string): void { this._statusText = text }
newResponse(data: any, init: ResponseInit = {}): Response { newResponse(data: Data, init: ResponseInit = {}): Response { init.status = init.status || this._status init.statusText = init.statusText || this._statusText
init.headers = { ...this._headers, ...init.headers }5 unmodified lines length = data.byteLength } else if (typeof data == 'string') { const Encoder = new TextEncoder() length = Encoder.encode(data).byteLength || 0 } else { length = data.bytelength } } init.headers = { ...init.headers, ...{ 'Content-Length': length.toString() } }
return new Response(data, init) }
body(data: any, status: number = this._status, headers: Headers = this._headers): Response { body(data: Data, status: number = this._status, headers: Headers = this._headers): Response { return this.newResponse(data, { status: status, headers: headers, })10 unmodified lines json(object: object, status: number = this._status, headers: Headers = {}): Response { if (typeof object !== 'object') { throw new TypeError('json method arg must be a object!') }
const body = JSON.stringify(object) headers['Content-Type'] ||= 'application/json; charset=UTF-8' return this.body(body, status, headers) }9 unmodified lines redirect(location: string, status: number = 302): Response { if (typeof location !== 'string') { throw new TypeError('location must be a string!') }
if (!isAbsoluteURL(location)) { const url = new URL(this.req.url) url.pathname = location location = url.toString()9 unmodified linesmodified:test/context.test.ts+11 added-6 removed
46 unmodified lines47 })48 49 it('c.status() and c.statusText()', async () => {50 c.status(201)51- c.statusText('Created!!!!')51 const res = c.body('Hi')52 expect(res.status).toBe(201)54- expect(res.statusText).toBe('Created!!!!')53+ expect(res.statusText).toBe('Created')54 })55 56 it('Complext pattern', async () => {57 c.status(404)59- c.statusText('Hono is Not Found')58 const res = c.json({ hono: 'great app' })59 expect(res.status).toBe(404)62- expect(res.statusText).toBe('Hono is Not Found')60+ expect(res.statusText).toBe('Not Found')61 expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')62 const obj: { [key: string]: string } = await res.json()63 expect(obj['hono']).toBe('great app')64 })4 unmodified lines69 res = c.text('炎')70 expect(res.headers.get('Content-Length')).toBe('3')71 })72 75- it('Headers', async () => {73+ it('Headers, status, statusText', async () => {74 c.header('X-Custom1', 'Message1')75 c.header('X-Custom2', 'Message2')76 c.status(200)79- c.statusText('OK')77 const res = c.newResponse('this is body', {78 status: 201,79 headers: {80 'X-Custom3': 'Message3',4 unmodified lines85 expect(res.headers.get('X-Custom2')).toBe('Message2-Override')86 expect(res.headers.get('X-Custom3')).toBe('Message3')87 expect(res.status).toBe(201)88 expect(await res.text()).toBe('this is body')89+90+ // res is already setted.91+ c.res = res92+ c.header('X-Custom4', 'Message4')93+ c.status(202)94+ expect(c.res.headers.get('X-Custom4')).toBe('Message4')95+ expect(c.res.status).toBe(201)96+ expect(c.res.statusText).toBe('OK')97 })98 })modified:test/hono.test.ts+3 added-2 removed
4 unmodified lines5 6 app.get('/hello', () => {7 return new Response('hello', {8 status: 200,9+ statusText: 'Hono is OK',10 })11 })12 13 app.get('/hello-with-shortcuts', (c) => {14 c.header('X-Custom', 'This is Hono')14- c.statusText('Hono is created')15 c.status(201)16 return c.html('<h1>Hono!!!</h1>')17 })18 7 unmodified lines26 const req = new Request('http://localhost/hello')27 const res = await app.dispatch(req)28 expect(res).not.toBeNull()29 expect(res.status).toBe(200)30+ expect(res.statusText).toBe('Hono is OK')31 expect(await res.text()).toBe('hello')32 })33 34 it('GET /hell-with-shortcuts is ok', async () => {35 const req = new Request('http://localhost/hello-with-shortcuts')36 const res = await app.dispatch(req)37 expect(res).not.toBeNull()38 expect(res.status).toBe(201)38- expect(res.statusText).toBe('Hono is created')39+ expect(res.statusText).toBe('Created')40 expect(res.headers.get('X-Custom')).toBe('This is Hono')41 expect(res.headers.get('Content-Type')).toMatch(/text\/html/)42 expect(await res.text()).toBe('<h1>Hono!!!</h1>')43 })274 unmodified linesmodified:README.md+1 added-2 removed
251 unmodified lines252 app.get('/welcome', (c) => {253 c.header('X-Message', 'Hello!')254 c.header('Content-Type', 'text/plain')255 c.status(201)256- c.statusText('201 Content Created')256 257 return c.body('Thank you for comming')258 259 /*260 Same as:261 return new Response('Thank you for comming', {262 status: 201,264- statusText: '201 Content Created',263+ statusText: 'Created',264 headers: {265 'X-Message': 'Hello',266 'Content-Type': 'text/plain',267 'Content-Length: '22'203 unmodified lines