Skip to content

Commit 39144ac

Browse files
committed
fix: update usage of fetch and socket.io
1 parent 0d7b31a commit 39144ac

1 file changed

Lines changed: 29 additions & 17 deletions

File tree

lib/CloudConvert.ts

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import io from 'socket.io-client';
1+
import { io, type Socket } from 'socket.io-client';
22
import { version } from '../package.json';
33
import JobsResource, { type JobEventData } from './JobsResource';
44
import SignedUrlResource from './SignedUrlResource';
@@ -10,7 +10,7 @@ import UsersResource from './UsersResource';
1010
import WebhooksResource from './WebhooksResource';
1111

1212
export default class CloudConvert {
13-
private socket: SocketIOClient.Socket | undefined;
13+
private socket: Socket | undefined;
1414
private subscribedChannels: Map<string, boolean> | undefined;
1515

1616
public readonly apiKey: string;
@@ -54,18 +54,36 @@ export default class CloudConvert {
5454
route: string,
5555
parameters?: FormData | object
5656
) {
57-
const res = await fetch(new URL(route, baseURL), {
57+
const url = new URL(route, baseURL);
58+
let body: RequestInit['body'] | undefined;
59+
if (parameters instanceof FormData) {
60+
body = parameters;
61+
} else {
62+
if (method === 'GET') {
63+
url.search = new URLSearchParams(
64+
Object.entries(parameters ?? {})
65+
).toString();
66+
} else {
67+
body = JSON.stringify(parameters);
68+
}
69+
}
70+
const res = await fetch(url, {
5871
method,
5972
headers: {
6073
Authorization: `Bearer ${this.apiKey}`,
6174
'User-Agent': `cloudconvert-node/v${version} (https://github.com/cloudconvert/cloudconvert-node)`
6275
},
63-
body:
64-
parameters instanceof FormData
65-
? parameters
66-
: JSON.stringify(parameters)
76+
body
6777
});
68-
return await res.json();
78+
if (
79+
!res.ok ||
80+
res.headers.get('Content-Type')?.toLowerCase() !==
81+
'application/json'
82+
) {
83+
return undefined;
84+
}
85+
const { data } = await res.json();
86+
return data;
6987
}
7088

7189
subscribe(
@@ -77,25 +95,19 @@ export default class CloudConvert {
7795
| ((event: JobTaskEventData) => void)
7896
): void {
7997
if (!this.socket) {
80-
this.socket = io.connect(
98+
this.socket = io(
8199
this.useSandbox
82100
? 'https://socketio.sandbox.cloudconvert.com'
83101
: 'https://socketio.cloudconvert.com',
84-
{
85-
transports: ['websocket']
86-
}
102+
{ transports: ['websocket'] }
87103
);
88104
this.subscribedChannels = new Map<string, boolean>();
89105
}
90106

91107
if (!this.subscribedChannels?.get(channel)) {
92108
this.socket.emit('subscribe', {
93109
channel,
94-
auth: {
95-
headers: {
96-
Authorization: `Bearer ${this.apiKey}`
97-
}
98-
}
110+
auth: { headers: { Authorization: `Bearer ${this.apiKey}` } }
99111
});
100112
this.subscribedChannels?.set(channel, true);
101113
}

0 commit comments

Comments
 (0)