From ad7715bebd336f9be503695cd0ac452a25a5737e Mon Sep 17 00:00:00 2001 From: Caleb Barnes Date: Thu, 16 Jan 2025 10:14:26 -0800 Subject: [PATCH] fix(js-client): api client types - make passing params optional where necessary (#6017) - add type AreAllOptional to check if every key on a type is optional - add IsPathAndQueryOptional to check if all params on a method are optional - allow passing nothing (void) or undefined for method params when there are no required params - simplify OperationParams / move some logic to ExtractPathAndQueryParameters to avoid repeating --- packages/js-client/src/types.ts | 46 ++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/packages/js-client/src/types.ts b/packages/js-client/src/types.ts index 7e6520ea16..565d0f714d 100644 --- a/packages/js-client/src/types.ts +++ b/packages/js-client/src/types.ts @@ -1,5 +1,31 @@ import type { operations } from '@netlify/open-api' +/** + * Determines whether all keys in T are optional. + */ +type AreAllOptional = keyof T extends never // If T has no keys, it's considered optional + ? true + : T extends Record + ? { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T] extends never + ? true + : false + : false + +/** + * Determines whether `path` and `query` are both optional. + */ +type IsPathAndQueryOptional = 'parameters' extends keyof operations[K] + ? AreAllOptional< + 'path' extends keyof operations[K]['parameters'] ? operations[K]['parameters']['path'] : object + > extends true + ? AreAllOptional< + 'query' extends keyof operations[K]['parameters'] ? operations[K]['parameters']['query'] : object + > extends true + ? true + : false + : false + : true + /** * Converts snake_case to camelCase for TypeScript types. */ @@ -13,26 +39,32 @@ type SnakeToCamel = { } /** - * Combines snake_case and camelCase parameters. + * Combines snake_case and camelCase parameters into one Params type. */ -type CombinedCaseParams = SnakeToCamel | T +type Params = SnakeToCamel | T /** - * Combines `path` and `query` parameters into a single type. + * Extracts and combines `path` and `query` parameters into a single type. */ -type OperationParams = 'parameters' extends keyof operations[K] +type ExtractPathAndQueryParameters = 'parameters' extends keyof operations[K] ? 'path' extends keyof operations[K]['parameters'] ? 'query' extends keyof operations[K]['parameters'] - ? CombinedCaseParams< + ? Params< Omit & operations[K]['parameters']['query'] > - : CombinedCaseParams + : Params : 'query' extends keyof operations[K]['parameters'] - ? CombinedCaseParams + ? Params : undefined : undefined +type OperationParams = 'parameters' extends keyof operations[K] + ? IsPathAndQueryOptional extends true + ? ExtractPathAndQueryParameters | void + : ExtractPathAndQueryParameters + : void + type SuccessHttpStatusCodes = 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 226 /** * Extracts the response type from the operation.