diff --git a/src/multer.ts b/src/multer.ts index 0bed9b8..8bdfdac 100644 --- a/src/multer.ts +++ b/src/multer.ts @@ -4,6 +4,8 @@ import type { StorageEngine } from "multer"; import type { Request } from "express"; import type { CloudflareCDNUploadResponse } from "./typings"; +type CallbackFunction = (error: Error | null, info?: Partial) => void; + class CloudflareStorage implements StorageEngine { private destURL: string; public constructor(private accountID: string, private accountToken: string) { @@ -12,40 +14,49 @@ class CloudflareStorage implements StorageEngine { this.destURL = `https://api.cloudflare.com/client/v4/accounts/${this.accountID}/images/v1`; } - public _handleFile(_req: Request, file: Express.Multer.File, callback: (error: Error | null, info?: Partial) => void): void { + public _handleFile(_req: Request, file: Express.Multer.File, callback: CallbackFunction): void { const body = new FormData(); body.append("file", file.stream, file.originalname); - void fetch(this.destURL, { + this._uploadFile(body, callback); + } + + private async _uploadFile(body: FormData, callback: CallbackFunction) { + const request = await fetch(this.destURL, { method: "POST", headers: { Authorization: `Bearer ${this.accountToken}`, ...body.getHeaders() }, body - }).then((response) => { - void (response.json() as Promise).then((data) => { - if (response.ok) - return callback(null, { - path: data.result.variants[0], - filename: data.result.filename, - destination: data.result.id - }); - return callback(new Error("There was an error in uploading an asset to Cloudflare Images.")); + }) + + const response: CloudflareCDNUploadResponse = await request.json(); + if (request.ok) { + return callback(null, { + path: response.result.variants[0], + filename: response.result.filename, + destination: response.result.id }); - }); + } + + return callback(new Error("There was an error in uploading an asset to Cloudflare Images.")); } public _removeFile(_req: Request, file: Express.Multer.File, callback: (error: Error | null) => void): void { - void fetch(`${this.destURL}/${file.destination}`, { + this._deleteFile(file.destination, callback); + } + + private async _deleteFile(filedestination: string, callback: CallbackFunction) { + const request = await fetch(`${this.destURL}/${filedestination}`, { method: "DELETE", headers: { Authorization: `Bearer ${this.accountToken}` } - }).then((response) => { - if (response.ok) return callback(null); - return callback(new Error("There was an error in deleting the asset from Cloudflare Images.")); }); + + if (request.ok) return callback(null); + return callback(new Error("There was an error in deleting the asset from Cloudflare Images.")); } }