Skip to content

Commit 5042653

Browse files
committed
refactor of request util
1 parent ee1e965 commit 5042653

File tree

6 files changed

+227
-168
lines changed

6 files changed

+227
-168
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
1111
[![Twitter Follow](https://img.shields.io/twitter/follow/imagekitio?label=Follow&style=social)](https://twitter.com/ImagekitIo)
1212

13-
Javascript SDK for [ImageKit](https://imagekit.io/) provides URL generation for image & video resizing and provides an interface for file upload. This SDK is lightweight and has no dependency. You can also use this as an ES module.
13+
Javascript SDK for [ImageKit](https://imagekit.io/) provides URL generation for image & video resizing and provides an interface for file upload. This SDK is lightweight and you can also use this as an ES module.
1414

1515
ImageKit is complete media storage, optimization, and transformation solution that comes with an [image and video CDN](https://imagekit.io/features/imagekit-infrastructure). It can be integrated with your existing infrastructure - storage like AWS S3, web servers, your CDN, and custom domain names, allowing you to deliver optimized images in minutes with minimal code changes.
1616

package-lock.json

Lines changed: 3 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,5 +68,8 @@
6868
"bugs": {
6969
"url": "https://github.com/imagekit-developer/imagekit-javascript/issues"
7070
},
71-
"homepage": "https://github.com/imagekit-developer/imagekit-javascript#readme"
71+
"homepage": "https://github.com/imagekit-developer/imagekit-javascript#readme",
72+
"dependencies": {
73+
"regenerator-runtime": "^0.13.9"
74+
}
7275
}

src/constants/errorMessages.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@ export default {
66
MISSING_UPLOAD_FILE_PARAMETER: { message: "Missing file parameter for upload", help: "" },
77
MISSING_UPLOAD_FILENAME_PARAMETER: { message: "Missing fileName parameter for upload", help: "" },
88
MISSING_AUTHENTICATION_ENDPOINT: { message: "Missing authentication endpoint for upload", help: "" },
9-
MISSING_PUBLIC_KEY : { message: "Missing public key for upload", help: "" },
9+
MISSING_PUBLIC_KEY: { message: "Missing public key for upload", help: "" },
1010
AUTH_ENDPOINT_TIMEOUT: { message: "The authenticationEndpoint you provided timed out in 60 seconds", help: "" },
1111
AUTH_ENDPOINT_NETWORK_ERROR: { message: "Request to authenticationEndpoint failed due to network error", help: "" },
12+
AUTH_INVALID_RESPONSE: { message: "Invalid response from authenticationEndpoint. The SDK expects a JSON response with three fields i.e. signature, token and expire.", help: "" },
1213
UPLOAD_ENDPOINT_NETWORK_ERROR: {
1314
message: "Request to ImageKit upload endpoint failed due to network error",
1415
help: "",

src/utils/request.ts

Lines changed: 83 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import respond from "../utils/respond";
22
import errorMessages from "../constants/errorMessages"
33
import { ImageKitOptions, UploadResponse } from "../interfaces";
44
import IKResponse from "../interfaces/IKResponse";
5+
import 'regenerator-runtime/runtime'
56

67
interface SignatureResponse {
78
signature: string
@@ -38,96 +39,94 @@ const addResponseHeadersAndBody = (body: any, xhr: XMLHttpRequest): IKResponse<U
3839
return response as IKResponse<UploadResponse>;
3940
}
4041

41-
export const request = (uploadFileXHR: XMLHttpRequest, formData: FormData, options: ImageKitOptions & { authenticationEndpoint: string }, callback?: (err: Error | null, response: UploadResponse | null) => void) => {
42-
generateSignatureToken(options, (err, signaturObj) => {
43-
if (err) {
44-
return respond(true, err, callback)
45-
} else {
46-
formData.append("signature", signaturObj?.signature || "");
47-
formData.append("expire", String(signaturObj?.expire || 0));
48-
formData.append("token", signaturObj?.token || "");
42+
export const request = async (
43+
uploadFileXHR: XMLHttpRequest,
44+
formData: FormData,
45+
options: ImageKitOptions & { authenticationEndpoint: string },
46+
callback?: (err: Error | null, response: UploadResponse | null) => void) => {
47+
try {
48+
var signaturObj = await generateSignatureToken(options.authenticationEndpoint);
49+
} catch (ex) {
50+
return respond(true, ex, callback);
51+
}
4952

50-
uploadFile(uploadFileXHR, formData, (err, responseSucessText) => {
51-
if (err) {
52-
return respond(true, err, callback)
53-
}
54-
return respond(false, responseSucessText!, callback)
55-
});
56-
}
57-
});
58-
return uploadFileXHR;
59-
}
53+
formData.append("signature", signaturObj.signature);
54+
formData.append("expire", String(signaturObj.expire));
55+
formData.append("token", signaturObj.token);
6056

61-
export const generateSignatureToken = (options: ImageKitOptions & { authenticationEndpoint: string }, callback: (err: Error | null, response: SignatureResponse | null) => void) => {
62-
var xhr = new XMLHttpRequest();
63-
xhr.timeout = 60000;
64-
xhr.open('GET', options.authenticationEndpoint);
65-
xhr.ontimeout = function (e) {
66-
var body = errorMessages.AUTH_ENDPOINT_TIMEOUT;
67-
var result = addResponseHeadersAndBody(body, xhr);
68-
respond(true, result, callback);
69-
};
70-
xhr.onerror = function () {
71-
var body = errorMessages.AUTH_ENDPOINT_NETWORK_ERROR;
72-
var result = addResponseHeadersAndBody(body, xhr);
73-
respond(true, result, callback);
57+
try {
58+
var result = await uploadFile(uploadFileXHR, formData);
59+
return respond(false, result, callback);
60+
} catch (ex) {
61+
return respond(true, ex, callback);
7462
}
75-
xhr.onload = function () {
76-
if (xhr.status === 200) {
77-
try {
78-
var body = JSON.parse(xhr.responseText);
79-
var obj = {
80-
signature: body.signature,
81-
expire: body.expire,
82-
token: body.token
83-
}
84-
if (!obj.signature || !obj.expire || !obj.token) {
85-
respond(true, {}, callback);
86-
return;
87-
}
88-
var result = addResponseHeadersAndBody(obj, xhr);
89-
respond(false, result, callback);
90-
} catch (ex) {
91-
respond(true, ex, callback)
92-
}
93-
} else {
94-
try {
95-
var error = JSON.parse(xhr.responseText);
96-
var result = addResponseHeadersAndBody(error, xhr);
97-
respond(true, result, callback);
98-
} catch (ex) {
99-
respond(true, ex, callback);
100-
}
101-
}
102-
};
103-
xhr.send();
104-
return;
10563
}
10664

107-
export const uploadFile = (uploadFileXHR: XMLHttpRequest, formData: FormData, callback: (err: Error | IKResponse<UploadResponse> | null, response: UploadResponse | null) => void) => {
108-
uploadFileXHR.open('POST', 'https://upload.imagekit.io/api/v1/files/upload');
109-
uploadFileXHR.onerror = function () {
110-
var body = errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR;
111-
var result = addResponseHeadersAndBody(body, uploadFileXHR);
112-
respond(true, result, callback);
113-
return;
114-
}
115-
uploadFileXHR.onload = function () {
116-
if (uploadFileXHR.status === 200) {
117-
var body = JSON.parse(uploadFileXHR.responseText);
118-
var uploadResponse = addResponseHeadersAndBody(body, uploadFileXHR);
119-
callback(null, uploadResponse);
65+
export const generateSignatureToken = (
66+
authenticationEndpoint: string
67+
): Promise<SignatureResponse> => {
68+
return new Promise((resolve, reject) => {
69+
var xhr = new XMLHttpRequest();
70+
xhr.timeout = 60000;
71+
xhr.open('GET', authenticationEndpoint);
72+
xhr.ontimeout = function (e) {
73+
return reject(errorMessages.AUTH_ENDPOINT_TIMEOUT);
74+
};
75+
xhr.onerror = function () {
76+
return reject(errorMessages.AUTH_ENDPOINT_NETWORK_ERROR);
12077
}
121-
else if (uploadFileXHR.status !== 200) {
122-
try {
123-
var body = JSON.parse(uploadFileXHR.responseText);
124-
var uploadResponse = addResponseHeadersAndBody(body, uploadFileXHR);
125-
callback(uploadResponse, null);
126-
} catch (ex: any) {
127-
callback(ex, null);
78+
xhr.onload = function () {
79+
if (xhr.status === 200) {
80+
try {
81+
var body = JSON.parse(xhr.responseText);
82+
var obj = {
83+
signature: body.signature,
84+
expire: body.expire,
85+
token: body.token
86+
}
87+
if (!obj.signature || !obj.expire || !obj.token) {
88+
return reject(errorMessages.AUTH_INVALID_RESPONSE);
89+
}
90+
return resolve(obj);
91+
} catch (ex) {
92+
return reject(errorMessages.AUTH_INVALID_RESPONSE);
93+
}
94+
} else {
95+
return reject(errorMessages.AUTH_INVALID_RESPONSE);
12896
}
129-
}
130-
};
131-
uploadFileXHR.send(formData);
97+
};
98+
xhr.send();
99+
});
132100
}
133101

102+
export const uploadFile = (
103+
uploadFileXHR: XMLHttpRequest,
104+
formData: FormData
105+
): Promise<IKResponse<UploadResponse> | Error> => {
106+
return new Promise((resolve, reject) => {
107+
uploadFileXHR.open('POST', 'https://upload.imagekit.io/api/v1/files/upload');
108+
uploadFileXHR.onerror = function (e) {
109+
return reject(errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR);
110+
}
111+
uploadFileXHR.onload = function () {
112+
if (uploadFileXHR.status === 200) {
113+
try {
114+
var body = JSON.parse(uploadFileXHR.responseText);
115+
var uploadResponse = addResponseHeadersAndBody(body, uploadFileXHR);
116+
return resolve(uploadResponse);
117+
} catch (ex: any) {
118+
return reject(ex);
119+
}
120+
} else {
121+
try {
122+
var body = JSON.parse(uploadFileXHR.responseText);
123+
var uploadError = addResponseHeadersAndBody(body, uploadFileXHR);
124+
return reject(uploadError)
125+
} catch (ex: any) {
126+
return reject(ex);
127+
}
128+
}
129+
};
130+
uploadFileXHR.send(formData);
131+
});
132+
}

0 commit comments

Comments
 (0)