Skip to content

Commit

Permalink
api clientでwatchに対応しました
Browse files Browse the repository at this point in the history
  • Loading branch information
kahirokunn committed Mar 13, 2024
1 parent 3680360 commit 0c99fe9
Show file tree
Hide file tree
Showing 2 changed files with 216 additions and 114 deletions.
21 changes: 16 additions & 5 deletions examples/generate-all-k8s-client/k8s-client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,20 @@ type HttpHeaderOptions = {
headers?: Record<string, string> | undefined
}

export type WatchEventType = 'ADDED' | 'Modified' | 'Deleted' | 'BOOKMARK'
export type WatchExtraOptions<T> = {
watchEventHandler: (e: {
type: WatchEventType
object: T
}) => MaybePromise<unknown>
}
export type Options = RetryOptions & HttpHeaderOptions

export async function apiClient<Response>(
arguments_: QueryArgumentsSpec,
extraOptions?: Options
extraOptions: Options & WatchExtraOptions<Response>
): Promise<Response> {
const maxRetries = extraOptions?.maxRetries ?? 3
const maxRetries = extraOptions.maxRetries ?? 3

const defaultRetryCondition: RetryConditionFunction = ({ ...object }) => {
const { res, attempt, error } = object
Expand Down Expand Up @@ -227,7 +234,12 @@ export async function apiClient<Response>(
const isJsonResponse = contentType?.includes('application/json') ?? false

if (isSuccess && isJsonResponse) {
if ('watch' in params && params.watch && response.body) {
if (
'watch' in params &&
params.watch &&
response.body &&
'watchEventHandler' in extraOptions
) {
const reader = response.body.getReader()
const textDecoder = new TextDecoder()
let buffer = ''
Expand All @@ -242,8 +254,7 @@ export async function apiClient<Response>(
const line = buffer.slice(0, newlineIndex)
buffer = buffer.slice(newlineIndex + 1)

console.log('----------------')
console.log(JSON.parse(line))
await extraOptions.watchEventHandler(JSON.parse(line))
}
}

Expand Down
Loading

0 comments on commit 0c99fe9

Please sign in to comment.