firebase-tools
Version:
Command-Line Interface for Firebase
72 lines (71 loc) • 2.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBillingEnabled = isBillingEnabled;
exports.clearCache = clearCache;
exports.checkBillingEnabled = checkBillingEnabled;
exports.setBillingAccount = setBillingAccount;
exports.listBillingAccounts = listBillingAccounts;
const api_1 = require("../api");
const apiv2_1 = require("../apiv2");
const utils = require("../utils");
const ensureApiEnabled_1 = require("../ensureApiEnabled");
const API_VERSION = "v1";
const client = new apiv2_1.Client({ urlPrefix: (0, api_1.cloudbillingOrigin)(), apiVersion: API_VERSION });
async function isBillingEnabled(setup) {
if (setup.isBillingEnabled !== undefined) {
return setup.isBillingEnabled;
}
if (!setup.projectId) {
return false;
}
setup.isBillingEnabled = await checkBillingEnabled(setup.projectId);
return setup.isBillingEnabled;
}
const billingEnabledCache = new Map();
function clearCache() {
billingEnabledCache.clear();
}
function checkBillingEnabled(projectId, forceRefresh = false) {
if (!forceRefresh) {
const cached = billingEnabledCache.get(projectId);
if (cached !== undefined) {
return cached;
}
}
const promise = (async () => {
await (0, ensureApiEnabled_1.ensure)(projectId, "cloudbilling.googleapis.com", "billing", true);
const res = await client.get(utils.endpoint(["projects", projectId, "billingInfo"]), {
retries: 3,
retryCodes: [429, 500, 503],
headers: { "x-goog-user-project": projectId },
});
return res.body.billingEnabled;
})().catch((err) => {
billingEnabledCache.delete(projectId);
throw err;
});
billingEnabledCache.set(projectId, promise);
return promise;
}
async function setBillingAccount(projectId, billingAccountName) {
await (0, ensureApiEnabled_1.ensure)(projectId, "cloudbilling.googleapis.com", "billing", true);
const res = await client.put(utils.endpoint(["projects", projectId, "billingInfo"]), {
billingAccountName: billingAccountName,
}, {
retryCodes: [429, 500, 503],
headers: { "x-goog-user-project": projectId },
});
const enabled = res.body.billingEnabled;
billingEnabledCache.set(projectId, Promise.resolve(enabled));
return enabled;
}
async function listBillingAccounts(projectId) {
if (projectId) {
await (0, ensureApiEnabled_1.ensure)(projectId, "cloudbilling.googleapis.com", "billing", true);
}
const res = await client.get(utils.endpoint(["billingAccounts"]), {
retryCodes: [429, 500, 503],
headers: projectId ? { "x-goog-user-project": projectId } : undefined,
});
return res.body.billingAccounts || [];
}