11import { Axios , AxiosHeaders , AxiosRequestConfig , isAxiosError } from 'axios'
22
3+ import type { AsyncPdf , AsyncScreenshot , CreatePdf , CreateScreenshot , SyncPdf , SyncScreenshot } from '../generated'
4+
5+ type PdfRequests = CreatePdf | SyncPdf | AsyncPdf
6+ type ScreenshotRequests = CreateScreenshot | SyncScreenshot | AsyncScreenshot
7+ type RequestBody = PdfRequests | ScreenshotRequests
8+
39export class BaseService {
410
511 private rateLimit = {
@@ -16,11 +22,11 @@ export class BaseService {
1622
1723 constructor ( private readonly client : Axios ) { }
1824
19- protected async post < T > ( url : string , requestBody : object , config : AxiosRequestConfig = { } , retries = 1 ) : Promise < T > {
25+ protected async post < T > ( url : string , requestBody : RequestBody , config : AxiosRequestConfig = { } , retries = 1 ) : Promise < T > {
2026 try {
2127 await this . waitForRateLimit ( )
2228
23- const axiosResponse = await this . client . post < T > ( url , requestBody , config )
29+ const axiosResponse = await this . client . post < T > ( url , this . encodeRequestBody ( requestBody ) , config )
2430 this . processRateLimit ( new AxiosHeaders ( axiosResponse . headers ) )
2531
2632 if ( config . responseType === 'arraybuffer' ) {
@@ -37,6 +43,22 @@ export class BaseService {
3743 }
3844 }
3945
46+ private encodeRequestBody ( requestBody : PdfRequests ) : object {
47+ if ( requestBody . page . html ) {
48+ requestBody . page . html = this . baseEncodeContent ( requestBody . page . html )
49+ }
50+
51+ if ( requestBody . pdf ?. headerTemplate ) {
52+ requestBody . pdf . headerTemplate = this . baseEncodeContent ( requestBody . pdf . headerTemplate )
53+ }
54+
55+ if ( requestBody . pdf ?. footerTemplate ) {
56+ requestBody . pdf . footerTemplate = this . baseEncodeContent ( requestBody . pdf . footerTemplate )
57+ }
58+
59+ return requestBody
60+ }
61+
4062 private async waitForRateLimit ( ) : Promise < void > {
4163 // Minus 1 to be safe
4264 if ( ( this . rateLimit . remaining - 1 ) <= 0 ) {
@@ -56,4 +78,7 @@ export class BaseService {
5678 }
5779 }
5880
81+ private baseEncodeContent ( content : string ) : string {
82+ return Buffer . from ( content ) . toString ( 'base64' )
83+ }
5984}
0 commit comments