@google-cloud/storage
Version:
Cloud Storage Client Library for Node.js
329 lines (328 loc) • 12.9 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceObject = void 0;
/*!
* Copyright 2022 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const promisify_1 = require("@google-cloud/promisify");
const events_1 = require("events");
const util_js_1 = require("./util.js");
function isBucket(parent) {
if (!parent || typeof parent !== 'object') {
return false;
}
const obj = parent;
return (typeof obj.getFiles === 'function' &&
typeof obj.upload === 'function' &&
typeof obj.exists === 'function');
}
/**
* ServiceObject is a base class, meant to be inherited from by a "service
* object," like a BigQuery dataset or Storage bucket.
*
* Most of the time, these objects share common functionality; they can be
* created or deleted, and you can get or set their metadata.
*
* By inheriting from this class, a service object will be extended with these
* shared behaviors. Note that any method can be overridden when the service
* object requires specific behavior.
*/
class ServiceObject extends events_1.EventEmitter {
metadata;
baseUrl;
storageTransport;
parent;
id;
name;
createMethod;
methods;
interceptors;
projectId;
/*
* @constructor
* @alias module:common/service-object
*
* @private
*
* @param {object} config - Configuration object.
* @param {string} config.baseUrl - The base URL to make API requests to.
* @param {string} config.createMethod - The method which creates this object.
* @param {string=} config.id - The identifier of the object. For example, the
* name of a Storage bucket or Pub/Sub topic.
* @param {object=} config.methods - A map of each method name that should be inherited.
* @param {object} config.methods[].reqOpts - Default request options for this
* particular method. A common use case is when `setMetadata` requires a
* `PUT` method to override the default `PATCH`.
* @param {object} config.parent - The parent service instance. For example, an
* instance of Storage if the object is Bucket.
*/
constructor(config) {
super();
this.metadata = {};
this.baseUrl = config.baseUrl;
this.parent = config.parent; // Parent class.
this.id = config.id; // Name or ID (e.g. dataset ID, bucket name, etc).
this.createMethod = config.createMethod;
this.methods = config.methods || {};
this.interceptors = [];
this.projectId = config.projectId;
this.storageTransport = config.storageTransport;
if (config.methods) {
// This filters the ServiceObject instance (e.g. a "File") to only have
// the configured methods. We make a couple of exceptions for core-
// functionality ("request()" and "getRequestInterceptors()")
Object.getOwnPropertyNames(ServiceObject.prototype)
.filter(methodName => {
return (
// All ServiceObjects need `request` and `getRequestInterceptors`.
// clang-format off
!/^request/.test(methodName) &&
!/^getRequestInterceptors/.test(methodName) &&
// clang-format on
// The ServiceObject didn't redefine the method.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this[methodName] ===
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ServiceObject.prototype[methodName] &&
// This method isn't wanted.
!config.methods[methodName]);
})
.forEach(methodName => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this[methodName] = undefined;
});
}
}
create(optionsOrCallback, callback) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
const args = [this.id];
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
}
if (typeof optionsOrCallback === 'object') {
args.push(optionsOrCallback);
}
// Wrap the callback to return *this* instance of the object, not the
// newly-created one.
// tslint: disable-next-line no-any
function onCreate(...args) {
const [err, instance] = args;
if (!err) {
self.metadata = instance.metadata;
if (self.id && instance.metadata) {
self.id = instance.metadata.id;
}
args[1] = self; // replace the created `instance` with this one.
}
callback(...args);
}
args.push(onCreate);
// eslint-disable-next-line prefer-spread
this.createMethod.apply(null, args);
}
delete(optionsOrCallback, cb) {
const [options, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
const ignoreNotFound = options.ignoreNotFound;
delete options.ignoreNotFound;
const methodConfig = (typeof this.methods.delete === 'object' && this.methods.delete) || {};
let url = `${this.baseUrl}/${this.id}`;
if (isBucket(this.parent)) {
// TODO: remove any suppression during follow up PR to improve type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
url = `${this.parent.baseUrl}/${this.parent.id}${url}`;
}
const req = {
method: 'DELETE',
responseType: 'json',
url,
...methodConfig.reqOpts,
queryParameters: {
...methodConfig.reqOpts?.queryParameters,
...options,
},
};
if (callback) {
this.storageTransport
.makeRequest(req, (err, data, resp) => {
if (err) {
if (err.status === 404 && ignoreNotFound) {
err = null;
}
}
callback(err, resp);
})
.catch(err => callback(err));
return;
}
return this.storageTransport
.makeRequest(req)
.then(resp => [resp])
.catch(err => {
if (err.status === 404 && ignoreNotFound) {
return [err.response];
}
throw err;
});
}
exists(optionsOrCallback, cb) {
const [options, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
this.get(options, err => {
if (err) {
if (err.status === 404) {
callback(null, false);
}
else {
callback(err);
}
return;
}
callback(null, true);
});
}
get(optionsOrCallback, cb) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
const [opts, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
const options = Object.assign({}, opts);
const autoCreate = options.autoCreate && typeof this.create === 'function';
delete options.autoCreate;
function onCreate(err, instance) {
if (err) {
if (err.status === 409) {
self.get(options, callback);
return;
}
callback(err);
return;
}
callback(null, instance);
}
this.getMetadata(options, async (err) => {
if (err) {
if (err.status === 404 && autoCreate) {
const args = [];
if (Object.keys(options).length > 0) {
args.push(options);
}
args.push(onCreate);
await self.create(...args);
return;
}
callback(err);
return;
}
callback(null, self);
});
}
getMetadata(optionsOrCallback, cb) {
const [options, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
const methodConfig = (typeof this.methods.getMetadata === 'object' &&
this.methods.getMetadata) ||
{};
let url = `${this.baseUrl}/${this.id}`;
if (isBucket(this.parent)) {
// TODO: remove any suppression during follow up PR to improve type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
url = `${this.parent.baseUrl}/${this.parent.id}${url}`;
}
// TODO: remove any suppression during follow up PR to improve type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const encryptionHeaders = this.encryptionKeyHeaders || {};
const headers = {
...encryptionHeaders,
...methodConfig.reqOpts?.headers,
// TODO: remove any suppression during follow up PR to improve type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...options.headers,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const query = { ...options };
delete query.headers;
const req = {
method: 'GET',
responseType: 'json',
url,
...methodConfig.reqOpts,
headers,
queryParameters: {
...methodConfig.reqOpts?.queryParameters,
...query,
},
};
if (callback) {
this.storageTransport
.makeRequest(req, (err, data, resp) => {
if (!err && data) {
this.metadata = data;
}
callback(err, data, resp);
})
.catch(err => callback(err));
return;
}
return this.storageTransport.makeRequest(req).then(resp => {
this.metadata = resp.data;
return [this.metadata, resp];
});
}
setMetadata(metadata, optionsOrCallback, cb) {
const [options, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
const methodConfig = (typeof this.methods.setMetadata === 'object' &&
this.methods.setMetadata) ||
{};
let url = `${this.baseUrl}/${this.id || this.name}`;
if (isBucket(this.parent)) {
// TODO: remove any suppression during follow up PR to improve type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
url = `${this.parent.baseUrl}/${this.parent.name}${url}`;
}
const body = Object.assign({}, methodConfig.reqOpts?.body, metadata);
const req = {
method: 'PATCH',
responseType: 'json',
url,
...methodConfig.reqOpts,
body: JSON.stringify(body),
queryParameters: {
...methodConfig.reqOpts?.queryParameters,
...options,
},
headers: {
'Content-Type': 'application/json',
},
};
if (callback) {
this.storageTransport
.makeRequest(req, (err, data, resp) => {
if (err) {
callback(err, undefined, resp);
return;
}
this.metadata = data;
callback(null, this.metadata, resp);
})
// eslint-disable-next-line promise/no-callback-in-promise
.catch(err => callback(err));
return;
}
return this.storageTransport.makeRequest(req).then(resp => {
this.metadata = resp.data;
return [this.metadata];
});
}
}
exports.ServiceObject = ServiceObject;
(0, promisify_1.promisifyAll)(ServiceObject, { exclude: ['getRequestInterceptors'] });