Skip to content

Commit

Permalink
feat(api): api update (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-app[bot] authored and stainless-bot committed Oct 21, 2024
1 parent 4094526 commit f36f035
Show file tree
Hide file tree
Showing 25 changed files with 573 additions and 775 deletions.
2 changes: 1 addition & 1 deletion .stats.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
configured_endpoints: 39
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/plastic-labs%2Fhoncho-d259b106accde65e100275c3eee2d01d0b91792abc0e67ae807dae74fb32f4de.yml
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/plastic-labs%2Fhoncho-3b94ec668fd95755a2447237b113b61d5c82e62960832d065e8a6f06a1916286.yml
46 changes: 23 additions & 23 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ Other package managers may work but are not officially supported for development

To set up the repository, run:

```bash
yarn
yarn build
```sh
$ yarn
$ yarn build
```

This will install all the required dependencies and build output files to `dist/`.
Expand All @@ -22,7 +22,7 @@ modify the contents of the `src/lib/` and `examples/` directories.

All files in the `examples/` directory are not modified by the generator and can be freely edited or added to.

```bash
```ts
// add an example to examples/<your-example>.ts

#!/usr/bin/env -S npm run tsn -T
Expand All @@ -41,38 +41,38 @@ If you’d like to use the repository from source, you can either install from g

To install via git:

```bash
npm install git+ssh://git@github.com:plastic-labs/honcho-node.git
```sh
$ npm install git+ssh://git@github.com:plastic-labs/honcho-node.git
```

Alternatively, to link a local copy of the repo:

```bash
```sh
# Clone
git clone https://www.github.com/plastic-labs/honcho-node
cd honcho-node
$ git clone https://www.github.com/plastic-labs/honcho-node
$ cd honcho-node

# With yarn
yarn link
cd ../my-package
yarn link honcho
$ yarn link
$ cd ../my-package
$ yarn link honcho

# With pnpm
pnpm link --global
cd ../my-package
pnpm link -—global honcho
$ pnpm link --global
$ cd ../my-package
$ pnpm link -—global honcho
```

## Running tests

Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests.

```bash
npx prism mock path/to/your/openapi.yml
```sh
$ npx prism mock path/to/your/openapi.yml
```

```bash
yarn run test
```sh
$ yarn run test
```

## Linting and formatting
Expand All @@ -82,14 +82,14 @@ This repository uses [prettier](https://www.npmjs.com/package/prettier) and

To lint:

```bash
yarn lint
```sh
$ yarn lint
```

To format and fix all lint issues automatically:

```bash
yarn fix
```sh
$ yarn fix
```

## Publishing and releases
Expand Down
35 changes: 4 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,37 +137,6 @@ On timeout, an `APIConnectionTimeoutError` is thrown.

Note that requests which time out will be [retried twice by default](#retries).

## Auto-pagination

List methods in the Honcho API are paginated.
You can use `for await … of` syntax to iterate through items across all pages:

```ts
async function fetchAllAppsUsers(params) {
const allAppsUsers = [];
// Automatically fetches more pages as needed.
for await (const user of client.apps.users.list('REPLACE_ME')) {
allAppsUsers.push(user);
}
return allAppsUsers;
}
```

Alternatively, you can make request a single page at a time:

```ts
let page = await client.apps.users.list('REPLACE_ME');
for (const user of page.items) {
console.log(user);
}

// Convenience methods are provided for manually paginating:
while (page.hasNextPage()) {
page = page.getNextPage();
// ...
}
```

## Advanced Usage

### Accessing raw Response data (e.g., headers)
Expand Down Expand Up @@ -319,3 +288,7 @@ The following runtimes are supported:
Note that React Native is not supported at this time.

If you are interested in other runtime environments, please open or upvote an issue on GitHub.

## Contributing

See [the contributing documentation](./CONTRIBUTING.md).
78 changes: 39 additions & 39 deletions api.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"eslint": "^8.49.0",
"eslint-plugin-prettier": "^5.0.1",
"eslint-plugin-unused-imports": "^3.0.0",
"iconv-lite": "^0.6.3",
"jest": "^29.4.0",
"prettier": "^3.0.0",
"ts-jest": "^29.1.0",
Expand Down
2 changes: 1 addition & 1 deletion src/_shims/node-types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as fd from 'formdata-node';
export { type Agent } from 'node:http';
export { type Readable } from 'node:stream';
export { type ReadStream as FsReadStream } from 'node:fs';
export { ReadableStream } from 'web-streams-polyfill';
export { ReadableStream } from 'node:stream/web';

export const fetch: typeof nf.default;

Expand Down
42 changes: 34 additions & 8 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,10 @@ export class APIPromise<T> extends Promise<T> {
});
}

_thenUnwrap<U>(transform: (data: T) => U): APIPromise<U> {
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
_thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U> {
return new APIPromise(this.responsePromise, async (props) =>
transform(await this.parseResponse(props), props),
);
}

/**
Expand Down Expand Up @@ -274,7 +276,10 @@ export abstract class APIClient {
return null;
}

buildRequest<Req>(options: FinalRequestOptions<Req>): { req: RequestInit; url: string; timeout: number } {
buildRequest<Req>(
options: FinalRequestOptions<Req>,
{ retryCount = 0 }: { retryCount?: number } = {},
): { req: RequestInit; url: string; timeout: number } {
const { method, path, query, headers: headers = {} } = options;

const body =
Expand Down Expand Up @@ -306,7 +311,7 @@ export abstract class APIClient {
headers[this.idempotencyHeader] = options.idempotencyKey;
}

const reqHeaders = this.buildHeaders({ options, headers, contentLength });
const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });

const req: RequestInit = {
method,
Expand All @@ -325,10 +330,12 @@ export abstract class APIClient {
options,
headers,
contentLength,
retryCount,
}: {
options: FinalRequestOptions;
headers: Record<string, string | null | undefined>;
contentLength: string | null | undefined;
retryCount: number;
}): Record<string, string> {
const reqHeaders: Record<string, string> = {};
if (contentLength) {
Expand All @@ -344,6 +351,16 @@ export abstract class APIClient {
delete reqHeaders['content-type'];
}

// Don't set the retry count header if it was already set or removed through default headers or by the
// caller. We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to
// account for the removal case.
if (
getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&
getHeader(headers, 'x-stainless-retry-count') === undefined
) {
reqHeaders['x-stainless-retry-count'] = String(retryCount);
}

this.validateHeaders(reqHeaders, headers);

return reqHeaders;
Expand Down Expand Up @@ -395,13 +412,14 @@ export abstract class APIClient {
retriesRemaining: number | null,
): Promise<APIResponseProps> {
const options = await optionsInput;
const maxRetries = options.maxRetries ?? this.maxRetries;
if (retriesRemaining == null) {
retriesRemaining = options.maxRetries ?? this.maxRetries;
retriesRemaining = maxRetries;
}

await this.prepareOptions(options);

const { req, url, timeout } = this.buildRequest(options);
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });

await this.prepareRequest(req, { url, options });

Expand Down Expand Up @@ -1120,7 +1138,15 @@ export const isHeadersProtocol = (headers: any): headers is HeadersProtocol => {
return typeof headers?.get === 'function';
};

export const getRequiredHeader = (headers: HeadersLike, header: string): string => {
export const getRequiredHeader = (headers: HeadersLike | Headers, header: string): string => {
const foundHeader = getHeader(headers, header);
if (foundHeader === undefined) {
throw new Error(`Could not find ${header} header`);
}
return foundHeader;
};

export const getHeader = (headers: HeadersLike | Headers, header: string): string | undefined => {
const lowerCasedHeader = header.toLowerCase();
if (isHeadersProtocol(headers)) {
// to deal with the case where the header looks like Stainless-Event-Id
Expand All @@ -1146,7 +1172,7 @@ export const getRequiredHeader = (headers: HeadersLike, header: string): string
}
}

throw new Error(`Could not find ${header} header`);
return undefined;
};

/**
Expand Down
18 changes: 9 additions & 9 deletions src/resources/apps/apps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,30 +16,30 @@ export class Apps extends APIResource {
* Returns: schemas.App: Created App object
*/
create(body: AppCreateParams, options?: Core.RequestOptions): Core.APIPromise<App> {
return this._client.post('/apps', { body, ...options });
return this._client.post('/v1/apps', { body, ...options });
}

/**
* Update an App
*
* Args: app_id (uuid.UUID): The ID of the app to update app (schemas.AppUpdate):
* The App object containing any new metadata
* Args: app_id (str): The ID of the app to update app (schemas.AppUpdate): The App
* object containing any new metadata
*
* Returns: schemas.App: The App object of the updated App
*/
update(appId: string, body: AppUpdateParams, options?: Core.RequestOptions): Core.APIPromise<App> {
return this._client.put(`/apps/${appId}`, { body, ...options });
return this._client.put(`/v1/apps/${appId}`, { body, ...options });
}

/**
* Get an App by ID
*
* Args: app_id (uuid.UUID): The ID of the app
* Args: app_id (str): The ID of the app
*
* Returns: schemas.App: App object
*/
get(appId: string, options?: Core.RequestOptions): Core.APIPromise<App> {
return this._client.get(`/apps/${appId}`, options);
return this._client.get(`/v1/apps/${appId}`, options);
}

/**
Expand All @@ -50,7 +50,7 @@ export class Apps extends APIResource {
* Returns: schemas.App: App object
*/
getByName(name: string, options?: Core.RequestOptions): Core.APIPromise<App> {
return this._client.get(`/apps/name/${name}`, options);
return this._client.get(`/v1/apps/name/${name}`, options);
}

/**
Expand All @@ -61,7 +61,7 @@ export class Apps extends APIResource {
* Returns: schemas.App: App object
*/
getOrCreate(name: string, options?: Core.RequestOptions): Core.APIPromise<App> {
return this._client.get(`/apps/get_or_create/${name}`, options);
return this._client.get(`/v1/apps/get_or_create/${name}`, options);
}
}

Expand All @@ -78,7 +78,7 @@ export interface App {
export interface AppCreateParams {
name: string;

metadata?: Record<string, unknown> | null;
metadata?: Record<string, unknown>;
}

export interface AppUpdateParams {
Expand Down
Loading

0 comments on commit f36f035

Please sign in to comment.