Skip to content

Commit

Permalink
Returns appropriate stream type depending on web or node environment
Browse files Browse the repository at this point in the history
  • Loading branch information
pierredge committed May 27, 2024
1 parent faea737 commit 558cfb0
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 50 deletions.
Binary file modified output.pdf
Binary file not shown.
Binary file added outputSnippet.pdf
Binary file not shown.
Binary file modified output_helper.pdf
Binary file not shown.
Binary file modified output_merged.pdf
Binary file not shown.
2 changes: 1 addition & 1 deletion src/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export class FileForgeClient {
files: File[] | fs.ReadStream[],
request: FileForge.MergeRequest,
requestOptions?: FileForgeClient.RequestOptions
): Promise<stream.Readable> {
): Promise<stream.Readable | any> {
const _request = core.newFormData();
const options = await serializers.GenerateRequestOptions.jsonOrThrow(request.options, {
unrecognizedObjectKeys: "passthrough",
Expand Down
20 changes: 8 additions & 12 deletions src/core/fetcher/Fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,25 +148,21 @@ async function fetcherImpl<R = unknown>(args: Fetcher.Args): Promise<APIResponse

if (response.headers.get('content-type')!.includes("application/json")){

const chunks: any[] = [];

for await (let chunk of readableStreamAsyncIterator(response.body)) {
chunks.push(chunk);
}

const buffer: Buffer = Buffer.concat(chunks);
const bufferString = buffer.toString();

body = JSON.parse(bufferString)
body = await response.json()

}else{
if(RUNTIME.type === "node"){
const { Readable } = await import('node:stream');
body = { "file":Readable.from(readableStreamAsyncIterator(response.body))}

body = response.body
}else{
body = { "file":response.body }
}

}

} else if (response.body != null && args.responseType === "text") {
console.log("TEXT")

body = await response.text();
} else {
const text = await response.text();
Expand Down
11 changes: 10 additions & 1 deletion src/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ export interface DocumentInput {
files?: AssetOrPathBuffer[];
}

export interface ResponseURL {
url: string;
}

export interface ResponseStream {
file: stream.Readable;
}

export type ResponseObject = ResponseStream | ResponseURL;

/**
* Generates a PDF document from web assets.
Expand All @@ -42,7 +51,7 @@ export interface DocumentInput {
export async function generate_from_html(
client: FileForgeClient,
document: DocumentInput
):Promise<any>{
):Promise<ResponseObject>{

const files: AssetOrPathBuffer[] = document.files ?? [];
files.push({ path: "/index.html", content: document.html });
Expand Down
82 changes: 46 additions & 36 deletions tests/custom.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import stream from "stream";
import * as core from "../src/core";
import { FileForgeClient } from "../src";
import { generate_from_html } from "../src/Helper";
import { generate_from_html, ResponseStream, ResponseURL } from "../src/Helper";
import * as error from "../src/errors/index";
import fs from "fs";
import { writeFile } from "fs/promises";
Expand Down Expand Up @@ -52,18 +52,12 @@ describe("test", () => {
{
options: {}
}
);

const chunks: any[] = [];

for await (let chunk of pdf) {
chunks.push(chunk);
}

const buffer: Buffer = Buffer.concat(chunks);
const bufferString = buffer.toString()

await writeFile("output.pdf", bufferString);
) as ResponseStream;

// Write the PDF stream to a file
const writeStream = fs.createWriteStream('output.pdf');
pdf.file.pipe(writeStream);

}, 10_000_000);


Expand All @@ -88,11 +82,11 @@ describe("test", () => {
host: true,
}
}
);
) as ResponseURL;

expect(pdf.url).not.toBeNull();

}, 10_000_000);
}, 10_000_000);

it("should fail because of invalid api key", async () => {
const htmlBlob = new Blob([HTML], {
Expand Down Expand Up @@ -150,18 +144,11 @@ describe("test", () => {
test:false
}

);
const chunks: any[] = [];

for await (let chunk of pdf) {
chunks.push(chunk);
}

const buffer: Buffer = Buffer.concat(chunks);
const bufferString = buffer.toString()


await writeFile("output_helper.pdf", bufferString);
) as ResponseStream;
// Write the PDF stream to a file
const writeStream = fs.createWriteStream('output_helper.pdf');
pdf.file.pipe(writeStream);

}, 10_000_000);

it("should generate a PDF url from helper", async () => {
Expand All @@ -186,7 +173,7 @@ describe("test", () => {
host:true,
}

);
) as ResponseURL;

expect(pdf.url).not.toBeNull();
}, 10_000_000);
Expand Down Expand Up @@ -215,16 +202,39 @@ describe("test", () => {
}
);

const chunks: any[] = [];
// Write the PDF stream to a file
const writeStream = fs.createWriteStream('output_merged.pdf');
pdf.file.pipe(writeStream);

}, 10_000_000);

it("should generate from html snippet", async () => {
try {

const client = new FileForgeClient({
apiKey: FILEFORGE_API_KEY
});
const documentInput = {
html: HTML,
fileName: 'example',
test: false,
host: false,
expiresAt: new Date(Date.now() + 48 * 60 * 60 * 1000),
files: [
{ path: '/style.css', content: CSS },
],
};

for await (let chunk of pdf) {
chunks.push(chunk);
}

const buffer: Buffer = Buffer.concat(chunks);
const bufferString = buffer.toString()
const response = await generate_from_html(client, documentInput) as ResponseStream;

// Write the PDF stream to a file
const writeStream = fs.createWriteStream('outputSnippet.pdf');
response.file.pipe(writeStream);
console.log('PDF generated successfully.');
} catch (error) {
console.error('Error generating PDF:', error);
}

await writeFile("output_merged.pdf", bufferString);
}, 10_000_000);

});

0 comments on commit 558cfb0

Please sign in to comment.