Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Harmonize fileBased backends and reduce boilerplate #99

Open
LeaVerou opened this issue Jul 30, 2024 · 0 comments
Open

Harmonize fileBased backends and reduce boilerplate #99

LeaVerou opened this issue Jul 30, 2024 · 0 comments

Comments

@LeaVerou
Copy link
Contributor

We have three backends with fileBased = true.

backends/dropbox/index.js:

async upload (file, path) {
	if (this.ref.path) {
		path = this.ref.path.replace(/[^/]+$/, "") + path; // make upload path relative to existing path
	}
	else {
		path = path.startsWith("/") ? path : "/" + path;
	}

	const ref = this._getRef(path);
	await this.put(file, {ref, isUploading: true});

	return this.getURL(path);
}

backends/github/file/github-file.js:

async upload (file, path = this.ref.path) {
	let dataURL = await readFile(file);

	let base64 = dataURL.slice(5); // remove data:
	let media = base64.match(/^\w+\/[\w+]+/)[0];
	media = media.replace("+", "\\+"); // Fix for #608
	base64 = base64.replace(RegExp(`^${media}(;base64)?,`), "");
	path = this.ref.path.replace(/[^/]+$/, "") + path; // make upload path relative to existing path

	let fileInfo = await this.put(base64, {ref: path, isEncoded: true});
	return this.getFileURL(path, {sha: fileInfo.commit.sha});
}
async upload (file, {filename = file.name, folder} = {}) {
	const metadata = {
		name: filename
	};

	if (folder) {
		const folderId = GoogleDrive.#getFolderId(folder);

		if (folderId) {
			metadata.parents = [folderId];
		}
	}

	const res = await this.request("upload/drive/v3/files?&fields=webViewLink&uploadType=resumable", metadata, "POST", {responseType: "response"});
	const call = res.headers.get("Location");

	try {
		const fileInfo = await this.request(call, file, "PATCH");
		return fileInfo.webViewLink;
	}
	catch ({ error }) {
		if (error.code === 401) {
			await this.logout(); // Access token we have is invalid. Discard it.
			throw new Error(this.constructor.phrase("access_token_invalid"));
		}
		else if (error.code === 403) {
			throw new Error(this.constructor.phrase("no_upload_permission"));
		}

		throw new Error(error.message);
	}
}
  1. We should harmonize these signatures.
  2. We should not be duplicating code that deals with relative paths in the actual backends. If we know it’s file based, we can do that in a superclass. That's the whole point of the fileBased key.

I haven't looked at put() but I suspect the findings will be similar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant