Skip to content
Myr

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

8 files+102 added−18 removed

modified:deno_dist/client/client.ts+7 added-5 removed
modified:deno_dist/client/types.ts+7 added-3 removed
modified:deno_dist/client/utils.ts+23 added
1import { getPathFromURL } from '../utils/url.ts'2import type { ObjectType } from './types.ts'34export const mergePath = (base: string, path: string) => {5 base = base.replace(/\/+$/, '')6 base = base + '/'
16 unmodified lines
23 return urlSting.replace(/index$/, '')24 }25 return urlSting26}2728function isObject(item: unknown): item is ObjectType {29 return typeof item === 'object' && item !== null && !Array.isArray(item)30}3132export 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>3738 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 }4647 return merged as T48}
modified:src/client/client.test.ts+5 added-1 removed
32 unmodified lines
33 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 lines
4950 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 lines
76 id: 123,77 title: 'Hello! Hono!',78 }7977 const client = hc<AppType>('http://localhost')80 const client = hc<AppType>('http://localhost', { headers: { 'x-hono': 'hono' } })8182 it('Should get 200 response', async () => {83 const res = await client.posts.$post(84 {
10 unmodified lines
95 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 lines
modified:src/client/client.ts+7 added-5 removed
1import type { Hono } from '../hono'2import type { ValidationTargets } from '../types'3import type { UnionToIntersection } from '../utils/types'4import type { Callback, Client, RequestOption } from './types'5import { replaceUrlParam, mergePath, removeIndexString } from './utils'4import type { Callback, Client, RequestOptions } from './types'5import { replaceUrlParam, mergePath, removeIndexString, deepMerge } from './utils'67const createProxy = (callback: Callback, path: string[]) => {8 const proxy: unknown = new Proxy(() => {}, {9 get(_obj, key) {
25 unmodified lines
35 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 lines
99 })100 }101}102103export const hc = <T extends Hono>(baseUrl: string) =>103export const hc = <T extends Hono>(baseUrl: string, options?: RequestOptions) =>104 createProxy(async (opts) => {105 const parts = [...opts.path]106107 let method = ''
7 unmodified lines
115 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 lines
11 }12 output: {}13}1415export type RequestOption = {15export type RequestOptions = {16 headers?: Record<string, string>17}1819type 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}2425export interface ClientResponse<T> extends Response {
1 unmodified line
27}2829export type Fetch<T> = (30 args?: InferRequestType<T>,31 opt?: RequestOption31 opt?: RequestOptions32) => Promise<ClientResponse<InferResponseType<T>>>3334export type InferResponseType<T> = T extends () => Promise<ClientResponse<infer O>> ? O : never35export type InferRequestType<T> = T extends (args: infer R) => Promise<ClientResponse<unknown>>
28 unmodified lines
64 path: string[]65 // eslint-disable-next-line @typescript-eslint/no-explicit-any66 args: any[]67}6869export type ObjectType<T = unknown> = {70 [key: string]: T71}
modified:src/client/utils.test.ts+23 added-1 removed
1import { mergePath, removeIndexString, replaceUrlParam } from './utils'1import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './utils'23describe('mergePath', () => {4 it('Should merge paths correctly', () => {5 expect(mergePath('http://localhost', '/api')).toBe('http://localhost/api')
26 unmodified lines
32 newUrl = removeIndexString(url)33 expect(newUrl).toBe('/')34 })35})3637describe('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 })4445 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
1import { getPathFromURL } from '../utils/url'2import type { ObjectType } from './types'34export const mergePath = (base: string, path: string) => {5 base = base.replace(/\/+$/, '')6 base = base + '/'
16 unmodified lines
23 return urlSting.replace(/index$/, '')24 }25 return urlSting26}2728function isObject(item: unknown): item is ObjectType {29 return typeof item === 'object' && item !== null && !Array.isArray(item)30}3132export 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>3738 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 }4647 return merged as T48}