Skip to content
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

feat: Add sdk-qbo powered by custom createClient #2

Merged
merged 9 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="website/public/logo-dark.png">
<source media="(prefers-color-scheme: light)" srcset="website/public/logo-light.png">
<img alt="Shows a black logo in light color mode and a white one in dark color mode." src="https://avatars.githubusercontent.com/u/51786539?v=4">
<img alt="Shows a black logo in light color mode and a white one in dark color mode." src="website/public/logo-light.png">
</picture>
<h1 align="center">OpenSDKs</h1>
</a>
</p>


<p align="center">
<a aria-label="Venice logo" href="https://venice.is">
<img src="website/public/made-by-venice.svg">
Expand Down Expand Up @@ -45,7 +46,7 @@ void github
```
Example 2: Use `sdks/sdk-slack`

```typescript
```ts
import {initSDK} from '@opensdks/runtime'
import {slackSdkDef} from '@opensdks/sdk-slack'

Expand All @@ -61,6 +62,7 @@ void slack
```



## Features

- ✅&nbsp; End-to-end type-safety for all third-party SDKs you consume
Expand All @@ -83,14 +85,19 @@ void github
### Powerful middleware when you need them
In the future we will implement features like tRPC links for extensibility for all SDKs. tRPC links can
be found here: [https://trpc.io/docs/client/links](https://trpc.io/docs/client/links)

```ts

const discord = createSdk(discordSdkDef, {
links: [
rateLimitLink({storage: AsyncStorage}),
retryLink(),
authorizationLink({storage: AsyncStorage}),
oauth1RefreshLink({onChange: () => {}}),
logLink({verbose: true}),
errorHandlingMiddleware(),
axios(),
fetchMiddleware(),
]
})
```
Expand Down
18 changes: 18 additions & 0 deletions examples/example-openai.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import {initSDK} from '@opensdks/core'
import {openaiSdkDef} from '@opensdks/sdk-openai'
import {slackSdkDef} from '@opensdks/sdk-slack'

const openai = initSDK(openaiSdkDef)

openai
.POST('/chat/completions', {body: {messages: [], model: ''}})
.then((r) => {
r.data.choices
})

const slack = initSDK(slackSdkDef)

slack.POST('/chat.postMessage', {
params: {header: {token: ''}},
body: {channel: 'hello'},
})
25 changes: 25 additions & 0 deletions examples/example-qbo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import {initSDK} from '@opensdks/core'
import {qboSdkDef} from '@opensdks/sdk-qbo'

const realmId = process.env['QBO_REALM_ID']!

const qbo = initSDK(qboSdkDef, {
reamId: '12345',
headers: {
authorization: `Bearer ${process.env['QBO_ACCESS_TOKEN']}`,
accept: 'application/json',
},
baseUrl: `https://sandbox-quickbooks.api.intuit.com/v3/company/${realmId}`,
})

qbo.GET('/companyinfo/{id}', {params: {path: {id: realmId}}}).then((r) => {
console.log(r.data)
})

void qbo.GET('/account/{id}', {params: {path: {id: '33'}}})

void qbo.query('SELECT * FROM Account')

// qbo.GET('/preferences').then((r) => {
// console.log(r.data)
// })
14 changes: 2 additions & 12 deletions examples/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,6 @@ import {slackSdkDef} from '@opensdks/sdk-slack'
import {twilio_api_v2010SdkDef} from '@opensdks/sdk-twilio_api_v2010'
import {veniceSdkDef} from '@opensdks/sdk-venice'

// Helper function for type guard
function ensureString(value: unknown): string {
if (typeof value !== 'string') {
throw new TypeError('Expected a string')
}
return value
}

// Comparison between GitHub vanilla octokit client and openSDKs client
const github = initSDK(githubSdkDef, {
headers: {
Expand Down Expand Up @@ -52,8 +44,8 @@ void octokit.rest.repos
// Comparison between Twilio vanilla API and openSDKs client
// highlighting type safety

const accountSid = ensureString(process.env['TWILIO_ACCOUNT_SID'])
const authToken = ensureString(process.env['TWILIO_AUTH_TOKEN'])
const accountSid = process.env['TWILIO_ACCOUNT_SID']!
const authToken = process.env['TWILIO_AUTH_TOKEN']!

const twilio = initSDK(twilio_api_v2010SdkDef, {
headers: {
Expand Down Expand Up @@ -124,5 +116,3 @@ void github
void venice.GET('/core/resource').then((r) => console.log(r.data))

void apollo.GET('/v1/email_accounts').then((r) => console.log(r.data))

apollo.hello
1 change: 1 addition & 0 deletions examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"@opensdks/sdk-github": "workspace:*",
"@opensdks/sdk-openai": "workspace:*",
"@opensdks/sdk-plaid": "workspace:*",
"@opensdks/sdk-qbo": "workspace:*",
"@opensdks/sdk-slack": "workspace:*",
"@opensdks/sdk-twilio_api_v2010": "workspace:*",
"@opensdks/sdk-twilio_messaging_v1": "workspace:*",
Expand Down
102 changes: 56 additions & 46 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,60 +3,70 @@
import {createClient} from './createClient'

// export type * from 'openapi-typescript-helpers'
// export {createClient} from './createClient'
export * from './HTTPError'
export type OpenAPISpec = oas30.OpenAPIObject | oas31.OpenAPIObject

// export interface SdkTypes {
// components: unknown
// external: unknown
// operations: unknown
// paths: unknown
// webhooks: unknown
// }

/** Get this from openapi */
export interface SdkDefinition<
Paths extends {},
T = unknown,
TOptions = Record<string, unknown>,
> {
_types: {
paths: Paths
}
oas: OpenAPISpec
options?: TOptions
extend?: (client: OpenAPIClient<Paths>, options: TOptions) => T
// MARK: - defineSdk

export interface OpenAPITypes {
components: {}
external: {}
operations: {}
paths: {}
webhooks: {}
}

export interface SDKTypes<T extends OpenAPITypes, TOptions = ClientOptions> {
oas: T
options: TOptions
}

export type SdkDefinition<
T extends SDKTypes<OpenAPITypes, ClientOptions>,
TClient = unknown,
> = RequireAtLeastOne<{
oas?: OpenAPISpec
defaultOptions?: ClientOptions
}> & {
types: T
createClient?: (
ctx: {
createClient: (opts: ClientOptions) => OpenAPIClient<T['oas']['paths']>
},
options: T['options'],
) => TClient
}

// This is necessary because we cannot publish inferred type otherwise
// @see https://share.cleanshot.com/06NvskP0
export type SDK<Paths extends {}, T> = OpenAPIClient<Paths> & {
// This should be made optional to keep the bundle size small
// company should be able to opt-in for things like validation
oas: OpenAPISpec
} & T
// MARK: - initSDK

// Can we make this optional to avoid needing to deal with json?
export function initSDK<TDef extends SdkDefinition<{}>>(
...[sdkDef, options]: 'options' extends keyof TDef
? [
sdkDef: TDef,
options: Omit<ClientOptions, keyof TDef['options']> & TDef['options'],
]
export function initSDK<
TDef extends SdkDefinition<SDKTypes<OpenAPITypes, any>>,

Check warning on line 44 in packages/core/src/index.ts

View workflow job for this annotation

GitHub Actions / Run type checks, lint, and tests

Unexpected any. Specify a different type

Check warning on line 44 in packages/core/src/index.ts

View workflow job for this annotation

GitHub Actions / Run type checks, lint, and tests

Unexpected any. Specify a different type
>(
...[sdkDef, options]: 'createClient' extends keyof TDef
? [sdkDef: TDef, options: TDef['types']['options']]
: [sdkDef: TDef] | [sdkDef: TDef, options?: ClientOptions]
): SDK<
TDef['_types']['paths'],
'extend' extends keyof TDef ? ReturnType<NonNullable<TDef['extend']>> : {}
> {
const {oas} = sdkDef
const client = createClient<TDef['_types']['paths']>({
baseUrl: oas.servers?.[0]?.url,
): ('createClient' extends keyof TDef
? ReturnType<NonNullable<TDef['createClient']>>
: OpenAPIClient<TDef['types']['oas']['paths']>) & {def: TDef} {
const {oas, defaultOptions} = sdkDef
const clientOptions = {
baseUrl: oas?.servers?.[0]?.url,
...defaultOptions,
...options,
})
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
const ret = sdkDef.extend?.(client as any, options as any) ?? client
}

/* eslint-disable @typescript-eslint/no-unsafe-return */
const client =
sdkDef.createClient?.({createClient}, clientOptions) ??
createClient(clientOptions)

// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any
return {...ret, oas} as any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {...client, def: sdkDef} as any
}

// MARK: -

type RequireAtLeastOne<T> = {
[K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>
}[keyof T]
Loading
Loading