utility-types#OptionalKeys TypeScript Examples

The following examples show how to use utility-types#OptionalKeys. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: fetch.ts    From open-design-sdk with Apache License 2.0 5 votes vote down vote up
// MultipartFilePart

export async function postMultipart<
  PathPattern extends MethodPathPatterns<'post'>,
  Operation extends paths[PathPattern]['post'],
  MultipartBody extends OperationMultipartBodyParams<Operation>
>(
  apiRoot: string,
  pathPattern: PathPattern,
  pathParams: PathParams<PathPattern>,
  data: {
    [K in Extract<RequiredKeys<MultipartBody>, string>]:
      | MultipartBody[K]
      | ReadStream
  } &
    {
      [K in Extract<OptionalKeys<MultipartBody>, string>]?:
        | MultipartBody[K]
        | ReadStream
    },
  authInfo: AuthInfo,
  options: {
    console?: Console | null
    cancelToken?: CancelToken | null
  } = {}
): Promise<Exclude<OperationResponse<Operation>, { statusCode: 500 }>> {
  const path = populatePathPattern(pathPattern, pathParams)

  const requestBody = new FormData()
  keys(data).forEach((fieldName) => {
    requestBody.append(fieldName, data[fieldName])
  })

  const res = await fetch(`${apiRoot}${path}`, {
    method: 'post',
    body: requestBody,
    headers: {
      'Authorization': `Bearer ${authInfo.token}`,
    },
    console: options.console || console,
    cancelToken: options.cancelToken || null,
  })
  options.cancelToken?.throwIfCancelled()

  const body = await res.json()
  options.cancelToken?.throwIfCancelled()

  if (res.status === 500) {
    throw new Error('Server Error')
  }

  return {
    statusCode: res.status,
    headers: res.headers,
    body,
  } as Exclude<OperationResponse<Operation>, { statusCode: 500 }>
}