@uploadx/gcs
Version:
Uploadx GCS module
62 lines (61 loc) • 2.44 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 {
constructor(config = {}) {
super(config);
this.config = config;
config.keyFile || (config.keyFile = process.env.GCS_KEYFILE);
const bucketName = config.bucket || process.env.GCS_BUCKET || gcs_config_1.GCSConfig.bucketName;
this.storageBaseURI = [gcs_config_1.GCSConfig.storageAPI, bucketName, 'o'].join('/');
this.uploadBaseURI = [gcs_config_1.GCSConfig.uploadAPI, bucketName, 'o'].join('/');
config.scopes || (config.scopes = gcs_config_1.GCSConfig.authScopes);
this.authClient = new google_auth_library_1.GoogleAuth(config);
}
/**
* 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)
}))
};
}
}
exports.GCSMetaStorage = GCSMetaStorage;