Skip to content

Commit

Permalink
feat(api): update via SDK Studio
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot committed May 12, 2024
1 parent dfbfdd4 commit 38ca16c
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 46 deletions.
22 changes: 10 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ import Terminal from 'terminal';
const terminal = new Terminal();

async function main() {
const userRetrieveResponse = await terminal.user.retrieve('REPLACE_ME');
const productRetrieveResponse = await terminal.product.retrieve();

console.log(userRetrieveResponse.result);
console.log(productRetrieveResponse.result);
}

main();
Expand All @@ -47,7 +47,7 @@ import Terminal from 'terminal';
const terminal = new Terminal();

async function main() {
const userRetrieveResponse: Terminal.UserRetrieveResponse = await terminal.user.retrieve('REPLACE_ME');
const productRetrieveResponse: Terminal.ProductRetrieveResponse = await terminal.product.retrieve();
}

main();
Expand All @@ -64,7 +64,7 @@ a subclass of `APIError` will be thrown:
<!-- prettier-ignore -->
```ts
async function main() {
const userRetrieveResponse = await terminal.user.retrieve('REPLACE_ME').catch(async (err) => {
const productRetrieveResponse = await terminal.product.retrieve().catch(async (err) => {
if (err instanceof Terminal.APIError) {
console.log(err.status); // 400
console.log(err.name); // BadRequestError
Expand Down Expand Up @@ -107,7 +107,7 @@ const terminal = new Terminal({
});

// Or, configure per-request:
await terminal.user.retrieve('REPLACE_ME', {
await terminal.product.retrieve({
maxRetries: 5,
});
```
Expand All @@ -124,7 +124,7 @@ const terminal = new Terminal({
});

// Override per-request:
await terminal.user.retrieve('REPLACE_ME', {
await terminal.product.retrieve({
timeout: 5 * 1000,
});
```
Expand All @@ -145,15 +145,13 @@ You can also use the `.withResponse()` method to get the raw `Response` along wi
```ts
const terminal = new Terminal();

const response = await terminal.user.retrieve('REPLACE_ME').asResponse();
const response = await terminal.product.retrieve().asResponse();
console.log(response.headers.get('X-My-Header'));
console.log(response.statusText); // access the underlying Response object

const { data: userRetrieveResponse, response: raw } = await terminal.user
.retrieve('REPLACE_ME')
.withResponse();
const { data: productRetrieveResponse, response: raw } = await terminal.product.retrieve().withResponse();
console.log(raw.headers.get('X-My-Header'));
console.log(userRetrieveResponse.result);
console.log(productRetrieveResponse.result);
```

### Making custom/undocumented requests
Expand Down Expand Up @@ -257,7 +255,7 @@ const terminal = new Terminal({
});

// Override per-request:
await terminal.user.retrieve('REPLACE_ME', {
await terminal.product.retrieve({
httpAgent: new http.Agent({ keepAlive: false }),
});
```
Expand Down
4 changes: 2 additions & 2 deletions api.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

Types:

- <code><a href="./src/resources/product.ts">ProductListResponse</a></code>
- <code><a href="./src/resources/product.ts">ProductRetrieveResponse</a></code>

Methods:

- <code title="get /product">client.product.<a href="./src/resources/product.ts">list</a>() -> ProductListResponse</code>
- <code title="get /product">client.product.<a href="./src/resources/product.ts">retrieve</a>() -> ProductRetrieveResponse</code>

# User

Expand Down
33 changes: 29 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import * as Uploads from './uploads';
import * as API from 'terminal/resources/index';

export interface ClientOptions {
/**
* Defaults to process.env['TERMINAL_BEARER_TOKEN'].
*/
bearerToken?: string | undefined;

/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*
Expand Down Expand Up @@ -66,23 +71,37 @@ export interface ClientOptions {

/** API Client for interfacing with the Terminal API. */
export class Terminal extends Core.APIClient {
bearerToken: string;

private _options: ClientOptions;

/**
* API Client for interfacing with the Terminal API.
*
* @param {string} [opts.baseURL=process.env['TERMINAL_BASE_URL'] ?? https://localhost:8080/test-api] - Override the default base URL for the API.
* @param {string | undefined} [opts.bearerToken=process.env['TERMINAL_BEARER_TOKEN'] ?? undefined]
* @param {string} [opts.baseURL=process.env['TERMINAL_BASE_URL'] ?? https://openapi.terminal.shop/] - Override the default base URL for the API.
* @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
*/
constructor({ baseURL = Core.readEnv('TERMINAL_BASE_URL'), ...opts }: ClientOptions = {}) {
constructor({
baseURL = Core.readEnv('TERMINAL_BASE_URL'),
bearerToken = Core.readEnv('TERMINAL_BEARER_TOKEN'),
...opts
}: ClientOptions = {}) {
if (bearerToken === undefined) {
throw new Errors.TerminalError(
"The TERMINAL_BEARER_TOKEN environment variable is missing or empty; either provide it, or instantiate the Terminal client with an bearerToken option, like new Terminal({ bearerToken: 'My Bearer Token' }).",
);
}

const options: ClientOptions = {
bearerToken,
...opts,
baseURL: baseURL || `https://localhost:8080/test-api`,
baseURL: baseURL || `https://openapi.terminal.shop/`,
};

super({
Expand All @@ -93,6 +112,8 @@ export class Terminal extends Core.APIClient {
fetch: options.fetch,
});
this._options = options;

this.bearerToken = bearerToken;
}

product: API.Product = new API.Product(this);
Expand All @@ -109,6 +130,10 @@ export class Terminal extends Core.APIClient {
};
}

protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {
return { Authorization: `Bearer ${this.bearerToken}` };
}

static Terminal = this;

static TerminalError = Errors.TerminalError;
Expand Down Expand Up @@ -152,7 +177,7 @@ export namespace Terminal {
export import RequestOptions = Core.RequestOptions;

export import Product = API.Product;
export import ProductListResponse = API.ProductListResponse;
export import ProductRetrieveResponse = API.ProductRetrieveResponse;

export import UserResource = API.UserResource;
export import User = API.User;
Expand Down
2 changes: 1 addition & 1 deletion src/resources/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

export { ProductListResponse, Product } from './product';
export { ProductRetrieveResponse, Product } from './product';
export { User, UserRetrieveResponse, UserResource } from './user';
10 changes: 5 additions & 5 deletions src/resources/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import { APIResource } from 'terminal/resource';
import * as ProductAPI from 'terminal/resources/product';

export class Product extends APIResource {
list(options?: Core.RequestOptions): Core.APIPromise<ProductListResponse> {
retrieve(options?: Core.RequestOptions): Core.APIPromise<ProductRetrieveResponse> {
return this._client.get('/product', options);
}
}

export interface ProductListResponse {
result: Array<ProductListResponse.Result>;
export interface ProductRetrieveResponse {
result: Array<ProductRetrieveResponse.Result>;
}

export namespace ProductListResponse {
export namespace ProductRetrieveResponse {
export interface Result {
id: string;

Expand All @@ -39,5 +39,5 @@ export namespace ProductListResponse {
}

export namespace Product {
export import ProductListResponse = ProductAPI.ProductListResponse;
export import ProductRetrieveResponse = ProductAPI.ProductRetrieveResponse;
}
13 changes: 8 additions & 5 deletions tests/api-resources/product.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
import Terminal from 'terminal';
import { Response } from 'node-fetch';

const terminal = new Terminal({ baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010' });
const terminal = new Terminal({
bearerToken: 'My Bearer Token',
baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010',
});

describe('resource product', () => {
test('list', async () => {
const responsePromise = terminal.product.list();
test('retrieve', async () => {
const responsePromise = terminal.product.retrieve();
const rawResponse = await responsePromise.asResponse();
expect(rawResponse).toBeInstanceOf(Response);
const response = await responsePromise;
Expand All @@ -17,9 +20,9 @@ describe('resource product', () => {
expect(dataAndResponse.response).toBe(rawResponse);
});

test('list: request options instead of params are passed correctly', async () => {
test('retrieve: request options instead of params are passed correctly', async () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(terminal.product.list({ path: '/_stainless_unknown_path' })).rejects.toThrow(
await expect(terminal.product.retrieve({ path: '/_stainless_unknown_path' })).rejects.toThrow(
Terminal.NotFoundError,
);
});
Expand Down
5 changes: 4 additions & 1 deletion tests/api-resources/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import Terminal from 'terminal';
import { Response } from 'node-fetch';

const terminal = new Terminal({ baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010' });
const terminal = new Terminal({
bearerToken: 'My Bearer Token',
baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010',
});

describe('resource user', () => {
test('retrieve', async () => {
Expand Down
Loading

0 comments on commit 38ca16c

Please sign in to comment.