Skip to content

Commit

Permalink
Merge pull request #1 from OnedocLabs/dsinghvi/patch-sdk
Browse files Browse the repository at this point in the history
patch sdk to get it working
  • Loading branch information
pierredge authored May 18, 2024
2 parents 3c8e36e + 3c8cd66 commit d74779f
Show file tree
Hide file tree
Showing 9 changed files with 255 additions and 229 deletions.
74 changes: 37 additions & 37 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,53 @@ name: ci
on: [push]

jobs:
compile:
runs-on: ubuntu-latest
compile:
runs-on: ubuntu-latest

steps:
- name: Checkout repo
uses: actions/checkout@v3
steps:
- name: Checkout repo
uses: actions/checkout@v3

- name: Set up node
uses: actions/setup-node@v3
- name: Set up node
uses: actions/setup-node@v3

- name: Compile
run: yarn && yarn build
- name: Compile
run: yarn && yarn build

test:
runs-on: ubuntu-latest
test:
runs-on: ubuntu-latest

steps:
- name: Checkout repo
uses: actions/checkout@v3
steps:
- name: Checkout repo
uses: actions/checkout@v3

- name: Set up node
uses: actions/setup-node@v3
- name: Set up node
uses: actions/setup-node@v3

- name: Compile
run: yarn && yarn test
- name: Compile
run: yarn && yarn test

publish:
needs: [ compile, test ]
if: github.event_name == 'push' && contains(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
publish:
needs: [compile, test]
if: github.event_name == 'push' && contains(github.ref, 'refs/tags/')
runs-on: ubuntu-latest

steps:
- name: Checkout repo
uses: actions/checkout@v3
steps:
- name: Checkout repo
uses: actions/checkout@v3

- name: Set up node
uses: actions/setup-node@v3
- name: Set up node
uses: actions/setup-node@v3

- name: Install dependencies
run: yarn install
- name: Install dependencies
run: yarn install

- name: Build
run: yarn build
- name: Build
run: yarn build

- name: Publish to npm
run: |
npm config set //registry.npmjs.org/:_authToken ${NPM_TOKEN}
npm publish --access public
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Publish to npm
run: |
npm config set //registry.npmjs.org/:_authToken ${NPM_TOKEN}
npm publish --access public
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
68 changes: 33 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,24 @@ yarn add fileforge
## Usage

```typescript
import { FileForgeClient, FileForge } from 'guesty';
import { FileForgeClient, FileForge } from "guesty";
import * as fs from "fs";

const fileforge = new FileForgeClient({
apiKey: "...",
apiKey: "...",
});

await fileforge.generate({
files: [
fs.readStream("index.html"),
],
files: [fs.readStream("index.html")],
options: {
fileName: "output.pdf"
}
fileName: "output.pdf",
},
});
```

## Exception Handling

When the API returns a non-success status code (4xx or 5xx response),
When the API returns a non-success status code (4xx or 5xx response),
a subclass of [FileForgeError](./src/errors/FileForgeError.ts) will be thrown:

```ts
Expand All @@ -48,9 +46,9 @@ try {
await fileforge.generate(...);
} catch (err) {
if (err instanceof FileForgeError) {
console.log(err.statusCode);
console.log(err.statusCode);
console.log(err.message);
console.log(err.body);
console.log(err.body);
}
}
```
Expand All @@ -63,11 +61,11 @@ than the configured retry limit (default: 2).

A request is deemed retriable when any of the following HTTP status codes is returned:

- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) (Internal Server Errors)
Use the `maxRetries` request option to configure this behavior.
- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) (Internal Server Errors)

Use the `maxRetries` request option to configure this behavior.

```ts
const response = await fileforge.generate(..., {
Expand All @@ -77,8 +75,8 @@ const response = await fileforge.generate(..., {

## Timeouts

The SDK defaults to a 60 second timout. Use the `timeoutInSeconds` option to
configure this behavior.
The SDK defaults to a 60 second timout. Use the `timeoutInSeconds` option to
configure this behavior.

```ts
const response = await fileforge.generate(..., {
Expand All @@ -88,23 +86,23 @@ const response = await fileforge.generate(..., {

## Runtime compatiblity

The SDK defaults to `node-fetch` but will use the global fetch client if present. The SDK
works in the following runtimes:
The SDK defaults to `node-fetch` but will use the global fetch client if present. The SDK
works in the following runtimes:

The following runtimes are supported:

- Node.js 18+
- Vercel
- Cloudflare Workers
- Deno v1.25+
- Bun 1.0+
- React Native
- Node.js 18+
- Vercel
- Cloudflare Workers
- Deno v1.25+
- Bun 1.0+
- React Native

### Customizing Fetch client

The SDK provides a way for you to customize the underlying HTTP client / Fetch function. If you're
running in an unsupported environment, this provides a way for you to break the glass and
ensure the SDK works.
The SDK provides a way for you to customize the underlying HTTP client / Fetch function. If you're
running in an unsupported environment, this provides a way for you to break the glass and
ensure the SDK works.

```ts
import { FileForge } from 'fileforge';
Expand All @@ -117,16 +115,16 @@ const guesty = new FileForge({

## Beta status

This SDK is in beta, and there may be breaking changes between versions without a major version update.
Therefore, we recommend pinning the package version to a specific version in your package.json file.
This way, you can install the same version each time without breaking changes unless you are
This SDK is in beta, and there may be breaking changes between versions without a major version update.
Therefore, we recommend pinning the package version to a specific version in your package.json file.
This way, you can install the same version each time without breaking changes unless you are
intentionally looking for the latest version.

## Contributing

While we value open-source contributions to this SDK, this library is generated programmatically.
Additions made directly to this library would have to be moved over to our generation code,
otherwise they would be overwritten upon the next generated release. Feel free to open a
PR as a proof of concept, but know that we will not be able to merge it as-is.
While we value open-source contributions to this SDK, this library is generated programmatically.
Additions made directly to this library would have to be moved over to our generation code,
otherwise they would be overwritten upon the next generated release. Feel free to open a
PR as a proof of concept, but know that we will not be able to merge it as-is.

We suggest [opening an issue](https://github.com/FlatFilers/flatfile-node/issues) first to discuss with us!
63 changes: 21 additions & 42 deletions src/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,22 @@ export class FileForgeClient {
request: FileForge.GenerateRequest,
requestOptions?: FileForgeClient.RequestOptions
): Promise<stream.Readable> {
const _request = new core.FormDataWrapper();
await _request.append("options", JSON.stringify(request.options), { contentType: "application/json"});
const _request = core.newFormData();
const options = await serializers.GenerateRequestOptions.jsonOrThrow(request.options, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: false,
allowUnrecognizedEnumValues: false,
breadcrumbsPrefix: [""],
});
console.log(options);
await _request.append(
"options",
JSON.stringify(options),
{ contentType: "application/json" }
);
for (const _file of files) {
await _request.append("files", _file);
}

const _maybeEncodedRequest = _request.getRequest();
const _response = await core.fetcher<stream.Readable>({
url: urlJoin(
(await core.Supplier.get(this._options.environment)) ?? environments.FileForgeEnvironment.Default,
Expand All @@ -58,54 +67,24 @@ export class FileForgeClient {
"X-Fern-SDK-Version": "0.0.1",
"X-Fern-Runtime": core.RUNTIME.type,
"X-Fern-Runtime-Version": core.RUNTIME.version,
...(await _maybeEncodedRequest.getHeaders()),
...(await _request.getHeaders()),
},
body: await _maybeEncodedRequest.getBody(),
body: await _request.getBody(),
responseType: "streaming",
timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
maxRetries: requestOptions?.maxRetries,
});
console.log("_response", JSON.stringify(_response))
if (_response.ok) {
console.log("_response.body", _response.body);
return _response.body;
}

if (_response.error.reason === "status-code") {
switch (_response.error.statusCode) {
case 400:
throw new FileForge.BadRequestError(
await serializers.ErrorSchema.parseOrThrow(_response.error.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
breadcrumbsPrefix: ["response"],
})
);
case 401:
throw new FileForge.UnauthorizedError(
await serializers.ErrorSchema.parseOrThrow(_response.error.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
breadcrumbsPrefix: ["response"],
})
);
case 500:
throw new FileForge.InternalServerError(_response.error.body);
case 502:
throw new FileForge.BadGatewayError(
await serializers.ErrorSchema.parseOrThrow(_response.error.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
breadcrumbsPrefix: ["response"],
})
);
default:
throw new errors.FileForgeError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}
throw new errors.FileForgeError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}

switch (_response.error.reason) {
Expand Down
30 changes: 22 additions & 8 deletions src/core/fetcher/Fetcher.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { default as FormData } from "form-data";
import qs from "qs";
import { RUNTIME } from "../runtime";
import { APIResponse } from "./APIResponse";
Expand Down Expand Up @@ -67,13 +66,28 @@ async function fetcherImpl<R = unknown>(args: Fetcher.Args): Promise<APIResponse
: args.url;

let body: BodyInit | undefined = undefined;
if (args.body instanceof FormData) {
// @ts-expect-error
body = args.body;
} else if (args.body instanceof Uint8Array) {
body = args.body;
const maybeStringifyBody = (body: any) => {
if (body instanceof Uint8Array) {
return body;
} else {
return JSON.stringify(body);
}
};

if (RUNTIME.type === "node") {
if (args.body instanceof (await import("formdata-node")).FormData) {
// @ts-expect-error
body = args.body;
} else {
body = maybeStringifyBody(args.body);
}
} else {
body = JSON.stringify(args.body);
if (args.body instanceof (await import("form-data")).default) {
// @ts-expect-error
body = args.body;
} else {
body = maybeStringifyBody(args.body);
}
}

// In Node.js environments, the SDK always uses`node-fetch`.
Expand Down Expand Up @@ -194,4 +208,4 @@ async function fetcherImpl<R = unknown>(args: Fetcher.Args): Promise<APIResponse
}
}

export const fetcher: FetchFunction = fetcherImpl;
export const fetcher: FetchFunction = fetcherImpl;
Loading

0 comments on commit d74779f

Please sign in to comment.