@uploadx/gcs
Version:
Uploadx GCS module
69 lines (68 loc) • 2.55 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GCSMetaStorage = void 0;
const core_1 = require("@uploadx/core");
const google_auth_library_1 = require("google-auth-library");
const gcs_config_1 = require("./gcs-config");
class GCSMetaStorage extends core_1.MetaStorage {
options;
authClient;
storageBaseURI;
uploadBaseURI;
bucket;
constructor(options = {}) {
super(options);
this.options = options;
this.bucket = options.bucket || gcs_config_1.GCSConfig.bucketName;
this.storageBaseURI = [gcs_config_1.GCSConfig.storageAPI, this.bucket, 'o'].join('/');
this.uploadBaseURI = [gcs_config_1.GCSConfig.uploadAPI, this.bucket, 'o'].join('/');
options.scopes ||= gcs_config_1.GCSConfig.authScopes;
this.authClient = new google_auth_library_1.GoogleAuth(options);
}
/**
* Returns metafile url
* @param id - upload id
*/
getMetaPath(id) {
return `${this.storageBaseURI}/${this.getMetaName(id)}`;
}
async save(id, file) {
//TODO: use JSON API multipart POST?
await this.authClient.request({
body: JSON.stringify(file),
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: 'POST',
params: { name: encodeURIComponent(this.getMetaName(id)), uploadType: 'media' },
url: this.uploadBaseURI
});
return file;
}
async delete(id) {
const url = this.getMetaPath(id);
await this.authClient.request({ method: 'DELETE', url });
return;
}
async get(id) {
const url = this.getMetaPath(id);
const { data } = await this.authClient.request({ params: { alt: 'media' }, url });
return data;
}
async list(prefix) {
const baseURL = this.storageBaseURI;
const url = '/';
const options = { baseURL, url, params: { prefix: encodeURIComponent(this.prefix + prefix) } };
const { data } = await this.authClient.request(options);
return {
items: data.items
.filter(item => item.name.endsWith(this.suffix))
.map(({ name, timeCreated }) => ({
id: this.getIdFromMetaName(name),
createdAt: new Date(timeCreated)
}))
};
}
toString() {
return `[${this.constructor.name}: bucket="${this.bucket}", prefix="${this.prefix}", suffix="${this.suffix}"]`;
}
}
exports.GCSMetaStorage = GCSMetaStorage;