feat(client): Inject common headers (#908)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(client): Inject common headers * feat: Accept a RequestOptions object as argument. * refactor: Rename RequestOption to RequestOptions * denoify
authored by hagishi · committed by GitHub · parent 22839f5 · Browse files · 8 files·+102 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+102 added−18 removed
- tests:+28 added−2 removed
- other:+74 added−16 removed
Provenance
- Commit
7ffb5b5- Tree
c054117- Author
hagishi <fujiyama@kakumei.jp>- Committer
GitHub <noreply@github.com>- Parent
22839f5
8 files changed+102 added−18 removed
modified:deno_dist/client/client.ts+7 added-5 removed
1234545678925 unmodified lines3536373839394041424355 unmodified lines991001011021031031041051061077 unmodified lines115116117118119120119121122123124import type { Hono } from '../hono.ts'import type { ValidationTargets } from '../types.ts'import type { UnionToIntersection } from '../utils/types.ts'import type { Callback, Client, RequestOption } from './types.ts'import { replaceUrlParam, mergePath, removeIndexString } from './utils.ts'import type { Callback, Client, RequestOptions } from './types.ts'import { replaceUrlParam, mergePath, removeIndexString, deepMerge } from './utils.ts'
const createProxy = (callback: Callback, path: string[]) => { const proxy: unknown = new Proxy(() => {}, { get(_obj, key) {25 unmodified lines fetch = ( args?: ValidationTargets & { param?: Record<string, string> }, opt?: RequestOption opt?: RequestOptions ) => { if (args) { if (args.query) { for (const [k, v] of Object.entries(args.query)) {55 unmodified lines }) }}
export const hc = <T extends Hono>(baseUrl: string) =>export const hc = <T extends Hono>(baseUrl: string, options?: RequestOptions) => createProxy(async (opts) => { const parts = [...opts.path]
let method = ''7 unmodified lines const path = parts.join('/') const url = mergePath(baseUrl, path) const req = new ClientRequestImpl(url, method) if (method) { options ??= {} const args = deepMerge<RequestOptions>(options, { ...(opts.args[1] ?? {}) }) return req.fetch(opts.args[0], opts.args[1]) return req.fetch(opts.args[0], args) } return req }, []) as UnionToIntersection<Client<T>>modified:deno_dist/client/types.ts+7 added-3 removed
10 unmodified lines1112131415151617181920212122232425262728293031313233343528 unmodified lines646566676869707110 unmodified lines } output: {}}
export type RequestOption = {export type RequestOptions = { headers?: Record<string, string>}
type ClientRequest<S extends Data> = { [M in keyof S]: S[M] extends { input: infer R; output: infer O } ? (args?: R, options?: RequestOption) => Promise<ClientResponse<O>> ? (args?: R, options?: RequestOptions) => Promise<ClientResponse<O>> : never}
export interface ClientResponse<T> extends Response { json(): Promise<T>}
export type Fetch<T> = ( args?: InferRequestType<T>, opt?: RequestOption opt?: RequestOptions) => Promise<ClientResponse<InferResponseType<T>>>
export type InferResponseType<T> = T extends () => Promise<ClientResponse<infer O>> ? O : neverexport type InferRequestType<T> = T extends (args: infer R) => Promise<ClientResponse<unknown>>28 unmodified lines path: string[] // eslint-disable-next-line @typescript-eslint/no-explicit-any args: any[]}
export type ObjectType<T = unknown> = { [key: string]: T}modified:deno_dist/client/utils.ts+23 added
1 import { getPathFromURL } from '../utils/url.ts'2+import type { ObjectType } from './types.ts'3 4 export const mergePath = (base: string, path: string) => {5 base = base.replace(/\/+$/, '')6 base = base + '/'16 unmodified lines23 return urlSting.replace(/index$/, '')24 }25 return urlSting26 }27+28+function isObject(item: unknown): item is ObjectType {29+ return typeof item === 'object' && item !== null && !Array.isArray(item)30+}31+32+export function deepMerge<T>(target: T, source: Record<string, unknown>): T {33+ if (!isObject(target) && !isObject(source)) {34+ return source as T35+ }36+ const merged = { ...target } as ObjectType<T>37+38+ for (const key in source) {39+ const value = source[key]40+ if (isObject(merged[key]) && isObject(value)) {41+ merged[key] = deepMerge(merged[key], value)42+ } else {43+ merged[key] = value as T[keyof T] & T44+ }45+ }46+47+ return merged as T48+}modified:src/client/client.test.ts+5 added-1 removed
32 unmodified lines33 return c.jsonT({34 success: true,35 message: 'dummy',36 requestContentType: 'dummy',37+ requestHono: 'dummy',38 requestMessage: 'dummy',39 requestBody: {40 id: 123,41 title: 'dummy',7 unmodified lines49 50 const server = setupServer(51 rest.post('http://localhost/posts', async (req, res, ctx) => {52 const requestContentType = req.headers.get('content-type')53+ const requestHono = req.headers.get('x-hono')54 const requestMessage = req.headers.get('x-message')55 const requestBody = await req.json()56 const payload = {57 message: 'Hello!',58 success: true,59 requestContentType,60+ requestHono,61 requestMessage,62 requestBody,63 }64 return res(ctx.status(200), ctx.json(payload))11 unmodified lines76 id: 123,77 title: 'Hello! Hono!',78 }79 77- const client = hc<AppType>('http://localhost')80+ const client = hc<AppType>('http://localhost', { headers: { 'x-hono': 'hono' } })81 82 it('Should get 200 response', async () => {83 const res = await client.posts.$post(84 {10 unmodified lines95 const data = await res.json()96 expect(data.success).toBe(true)97 expect(data.message).toBe('Hello!')98 expect(data.requestContentType).toBe('application/json')99+ expect(data.requestHono).toBe('hono')100 expect(data.requestMessage).toBe('foobar')101 expect(data.requestBody).toEqual(payload)102 })103 171 unmodified linesmodified:src/client/client.ts+7 added-5 removed
1 import type { Hono } from '../hono'2 import type { ValidationTargets } from '../types'3 import type { UnionToIntersection } from '../utils/types'4-import type { Callback, Client, RequestOption } from './types'5-import { replaceUrlParam, mergePath, removeIndexString } from './utils'4+import type { Callback, Client, RequestOptions } from './types'5+import { replaceUrlParam, mergePath, removeIndexString, deepMerge } from './utils'6 7 const createProxy = (callback: Callback, path: string[]) => {8 const proxy: unknown = new Proxy(() => {}, {9 get(_obj, key) {25 unmodified lines35 fetch = (36 args?: ValidationTargets & {37 param?: Record<string, string>38 },39- opt?: RequestOption39+ opt?: RequestOptions40 ) => {41 if (args) {42 if (args.query) {43 for (const [k, v] of Object.entries(args.query)) {55 unmodified lines99 })100 }101 }102 103-export const hc = <T extends Hono>(baseUrl: string) =>103+export const hc = <T extends Hono>(baseUrl: string, options?: RequestOptions) =>104 createProxy(async (opts) => {105 const parts = [...opts.path]106 107 let method = ''7 unmodified lines115 const path = parts.join('/')116 const url = mergePath(baseUrl, path)117 const req = new ClientRequestImpl(url, method)118 if (method) {119+ options ??= {}120+ const args = deepMerge<RequestOptions>(options, { ...(opts.args[1] ?? {}) })119- return req.fetch(opts.args[0], opts.args[1])121+ return req.fetch(opts.args[0], args)122 }123 return req124 }, []) as UnionToIntersection<Client<T>>modified:src/client/types.ts+7 added-3 removed
10 unmodified lines11 }12 output: {}13 }14 15-export type RequestOption = {15+export type RequestOptions = {16 headers?: Record<string, string>17 }18 19 type ClientRequest<S extends Data> = {20 [M in keyof S]: S[M] extends { input: infer R; output: infer O }21- ? (args?: R, options?: RequestOption) => Promise<ClientResponse<O>>21+ ? (args?: R, options?: RequestOptions) => Promise<ClientResponse<O>>22 : never23 }24 25 export interface ClientResponse<T> extends Response {1 unmodified line27 }28 29 export type Fetch<T> = (30 args?: InferRequestType<T>,31- opt?: RequestOption31+ opt?: RequestOptions32 ) => Promise<ClientResponse<InferResponseType<T>>>33 34 export type InferResponseType<T> = T extends () => Promise<ClientResponse<infer O>> ? O : never35 export type InferRequestType<T> = T extends (args: infer R) => Promise<ClientResponse<unknown>>28 unmodified lines64 path: string[]65 // eslint-disable-next-line @typescript-eslint/no-explicit-any66 args: any[]67 }68+69+export type ObjectType<T = unknown> = {70+ [key: string]: T71+}modified:src/client/utils.test.ts+23 added-1 removed
1-import { mergePath, removeIndexString, replaceUrlParam } from './utils'1+import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './utils'2 3 describe('mergePath', () => {4 it('Should merge paths correctly', () => {5 expect(mergePath('http://localhost', '/api')).toBe('http://localhost/api')26 unmodified lines32 newUrl = removeIndexString(url)33 expect(newUrl).toBe('/')34 })35 })36+37+describe('deepMerge', () => {38+ it('should return the source object if the target object is not an object', () => {39+ const target = null40+ const source = { a: 1 }41+ const result = deepMerge(target, source)42+ expect(result).toEqual(source)43+ })44+45+ it('should merge two objects with object properties', () => {46+ expect(47+ deepMerge(48+ { headers: { hono: '1' }, timeout: 2, params: {} },49+ { headers: { hono: '2', demo: 2 }, params: undefined }50+ )51+ ).toStrictEqual({52+ params: undefined,53+ headers: { hono: '2', demo: 2 },54+ timeout: 2,55+ })56+ })57+})modified:src/client/utils.ts+23 added
1 import { getPathFromURL } from '../utils/url'2+import type { ObjectType } from './types'3 4 export const mergePath = (base: string, path: string) => {5 base = base.replace(/\/+$/, '')6 base = base + '/'16 unmodified lines23 return urlSting.replace(/index$/, '')24 }25 return urlSting26 }27+28+function isObject(item: unknown): item is ObjectType {29+ return typeof item === 'object' && item !== null && !Array.isArray(item)30+}31+32+export function deepMerge<T>(target: T, source: Record<string, unknown>): T {33+ if (!isObject(target) && !isObject(source)) {34+ return source as T35+ }36+ const merged = { ...target } as ObjectType<T>37+38+ for (const key in source) {39+ const value = source[key]40+ if (isObject(merged[key]) && isObject(value)) {41+ merged[key] = deepMerge(merged[key], value)42+ } else {43+ merged[key] = value as T[keyof T] & T44+ }45+ }46+47+ return merged as T48+}