- 
          
- 
                Notifications
    You must be signed in to change notification settings 
- Fork 418
feat: add --ky option #690
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            aleclarson
  wants to merge
  14
  commits into
  acacode:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
aleclarson:feat/ky-client
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from 13 commits
      Commits
    
    
            Show all changes
          
          
            14 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      7c8567e
              
                feat: add --ky option
              
              
                aleclarson c0536b8
              
                fix: remove imports from api.ejs
              
              
                aleclarson 240b553
              
                fix: `HttpClient#request` return type
              
              
                aleclarson 0128ad2
              
                fix: use `ky.create`
              
              
                aleclarson dc52cf3
              
                fix: remove securityWorker et al
              
              
                aleclarson 1a15458
              
                fix: `query` option type
              
              
                aleclarson 84710b8
              
                fix: ky instance usage
              
              
                aleclarson b3310ef
              
                chore: remove method description
              
              
                aleclarson 8ceddad
              
                fix: body option must be cast to any
              
              
                aleclarson 66c617d
              
                nit: rename the rest param
              
              
                aleclarson 5ed1fe4
              
                fix: ky headers option
              
              
                aleclarson 69a26ec
              
                fix: strip leading / to avoid ky error
              
              
                aleclarson 8c770b8
              
                feat: reimplement securityWorker
              
              
                aleclarson 5ef5380
              
                Update index.js
              
              
                aleclarson File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
      
      Oops, something went wrong.
      
    
  
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,220 @@ | ||
| <% | ||
| const { apiConfig, generateResponses, config } = it; | ||
| %> | ||
|  | ||
| import type { | ||
| BeforeRequestHook, | ||
| Hooks, | ||
| KyInstance, | ||
| Options as KyOptions, | ||
| NormalizedOptions, | ||
| SearchParamsOption, | ||
| } from "ky"; | ||
| import ky from "ky"; | ||
|  | ||
| type KyResponse<Data> = Response & { | ||
| json<T extends Data = Data>(): Promise<T>; | ||
| } | ||
|  | ||
| export type ResponsePromise<Data> = { | ||
| arrayBuffer: () => Promise<ArrayBuffer>; | ||
| blob: () => Promise<Blob>; | ||
| formData: () => Promise<FormData>; | ||
| json<T extends Data = Data>(): Promise<T>; | ||
| text: () => Promise<string>; | ||
| } & Promise<KyResponse<Data>>; | ||
|  | ||
| export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">; | ||
|  | ||
| export interface FullRequestParams | ||
| extends Omit<KyOptions, "json" | "body" | "searchParams"> { | ||
| /** set parameter to `true` for call `securityWorker` for this request */ | ||
| secure?: boolean; | ||
| /** request path */ | ||
| path: string; | ||
| /** content type of request body */ | ||
| type?: ContentType; | ||
| /** query params */ | ||
| query?: SearchParamsOption; | ||
| /** format of response (i.e. response.json() -> format: "json") */ | ||
| format?: ResponseFormat; | ||
| /** request body */ | ||
| body?: unknown; | ||
| } | ||
|  | ||
| export type RequestParams = Omit< | ||
| FullRequestParams, | ||
| "body" | "method" | "query" | "path" | ||
| >; | ||
|  | ||
| export interface ApiConfig<SecurityDataType = unknown> | ||
| extends Omit<KyOptions, "data" | "cancelToken"> { | ||
| securityWorker?: ( | ||
| securityData: SecurityDataType | null, | ||
| ) => Promise<NormalizedOptions | void> | NormalizedOptions | void; | ||
| secure?: boolean; | ||
| format?: ResponseType; | ||
| } | ||
|  | ||
| export enum ContentType { | ||
| Json = "application/json", | ||
| FormData = "multipart/form-data", | ||
| UrlEncoded = "application/x-www-form-urlencoded", | ||
| Text = "text/plain", | ||
| } | ||
|  | ||
| export class HttpClient<SecurityDataType = unknown> { | ||
| public ky: KyInstance; | ||
| private securityData: SecurityDataType | null = null; | ||
| private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"]; | ||
| private secure?: boolean; | ||
| private format?: ResponseType; | ||
|  | ||
| constructor({ | ||
| securityWorker, | ||
| secure, | ||
| format, | ||
| ...options | ||
| }: ApiConfig<SecurityDataType> = {}) { | ||
| this.ky = ky.create({ ...options, prefixUrl: options.prefixUrl || "" }); | ||
| this.secure = secure; | ||
| this.format = format; | ||
| this.securityWorker = securityWorker; | ||
| } | ||
|  | ||
| public setSecurityData = (data: SecurityDataType | null) => { | ||
| this.securityData = data; | ||
| }; | ||
|  | ||
| protected mergeRequestParams( | ||
| params1: KyOptions, | ||
| params2?: KyOptions, | ||
| ): KyOptions { | ||
| return { | ||
| ...params1, | ||
| ...params2, | ||
| headers: { | ||
| ...params1.headers, | ||
| ...(params2 && params2.headers), | ||
| }, | ||
| }; | ||
| } | ||
|  | ||
| protected stringifyFormItem(formItem: unknown) { | ||
| if (typeof formItem === "object" && formItem !== null) { | ||
| return JSON.stringify(formItem); | ||
| } else { | ||
| return `${formItem}`; | ||
| } | ||
| } | ||
|  | ||
| protected createFormData(input: Record<string, unknown>): FormData { | ||
| return Object.keys(input || {}).reduce((formData, key) => { | ||
| const property = input[key]; | ||
| const propertyContent: any[] = | ||
| property instanceof Array ? property : [property]; | ||
|  | ||
| for (const formItem of propertyContent) { | ||
| const isFileType = formItem instanceof Blob || formItem instanceof File; | ||
| formData.append( | ||
| key, | ||
| isFileType ? formItem : this.stringifyFormItem(formItem), | ||
| ); | ||
| } | ||
|  | ||
| return formData; | ||
| }, new FormData()); | ||
| } | ||
|  | ||
| public request = <T = any, _E = any>({ | ||
| secure = this.secure, | ||
| path, | ||
| type, | ||
| query, | ||
| format, | ||
| body, | ||
| ...options | ||
| <% if (config.unwrapResponseData) { %> | ||
| }: FullRequestParams): Promise<T> => { | ||
| <% } else { %> | ||
| }: FullRequestParams): ResponsePromise<T> => { | ||
| <% } %> | ||
| if (body) { | ||
| if (type === ContentType.FormData) { | ||
| body = | ||
| typeof body === "object" | ||
| ? this.createFormData(body as Record<string, unknown>) | ||
| : body; | ||
| } else if (type === ContentType.Text) { | ||
| body = typeof body !== "string" ? JSON.stringify(body) : body; | ||
| } | ||
| } | ||
|  | ||
| let headers: Headers | Record<string, string | undefined> | undefined; | ||
| if (options.headers instanceof Headers) { | ||
| headers = new Headers(options.headers); | ||
| if (type && type !== ContentType.FormData) { | ||
| headers.set("Content-Type", type); | ||
| } | ||
| } else { | ||
| headers = { ...options.headers } as Record<string, string | undefined>; | ||
| if (type && type !== ContentType.FormData) { | ||
| headers["Content-Type"] = type; | ||
| } | ||
| } | ||
|  | ||
| let hooks: Hooks | undefined; | ||
| if (secure && this.securityWorker) { | ||
| const securityWorker: BeforeRequestHook = async (request, options) => { | ||
| const secureOptions = await this.securityWorker!(this.securityData); | ||
| if (secureOptions && typeof secureOptions === "object") { | ||
| let { headers } = options; | ||
| if (secureOptions.headers) { | ||
| const mergedHeaders = new Headers(headers); | ||
| const secureHeaders = new Headers(secureOptions.headers); | ||
| secureHeaders.forEach((value, key) => { | ||
| mergedHeaders.set(key, value); | ||
| }); | ||
| headers = mergedHeaders; | ||
| } | ||
| return new Request(request.url, { | ||
| ...options, | ||
| ...secureOptions, | ||
| headers, | ||
| }); | ||
| } | ||
| }; | ||
|  | ||
| hooks = { | ||
| ...options.hooks, | ||
| beforeRequest: | ||
| options.hooks && options.hooks.beforeRequest | ||
| ? [securityWorker, ...options.hooks.beforeRequest] | ||
| : [securityWorker], | ||
| }; | ||
| } | ||
|  | ||
| const request = this.ky(path.replace(/^\//, ""), { | ||
| ...options, | ||
| headers, | ||
| searchParams: query, | ||
| body: body as any, | ||
| hooks, | ||
| }); | ||
|  | ||
| <% if (config.unwrapResponseData) { %> | ||
| const responseFormat = format || this.format || undefined; | ||
| return (responseFormat === "json" | ||
| ? request.json() | ||
| : responseFormat === "arrayBuffer" | ||
| ? request.arrayBuffer() | ||
| : responseFormat === "blob" | ||
| ? request.blob() | ||
| : responseFormat === "formData" | ||
| ? request.formData() | ||
| : request.text()) as Promise<T>; | ||
| <% } else { %> | ||
| return request; | ||
| <% } %> | ||
| }; | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.