firebase-admin
Version:
Firebase admin SDK for Node.js
534 lines (532 loc) • 21.9 kB
JavaScript
/*! firebase-admin v14.2.0 */
;
/*!
* @license
* Copyright 2024 Google LLC
*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataConnectApiClient = exports.ALLOW_DIRECTIVE_MAX_COUNT = void 0;
exports.useEmulator = useEmulator;
exports.getFieldsString = getFieldsString;
const api_request_1 = require("../utils/api-request");
const error_1 = require("../utils/error");
const error_2 = require("./error");
const utils = require("../utils/index");
const validator = require("../utils/validator");
const API_VERSION = 'v1';
const FIREBASE_DATA_CONNECT_PROD_URL = 'https://firebasedataconnect.googleapis.com';
/** The Firebase Data Connect backend service URL format. */
const FIREBASE_DATA_CONNECT_SERVICES_URL_FORMAT = FIREBASE_DATA_CONNECT_PROD_URL +
'/{version}' +
'/projects/{projectId}' +
'/locations/{locationId}' +
'/services/{serviceId}' +
':{endpointId}';
/** The Firebase Data Connect backend connector URL format. */
const FIREBASE_DATA_CONNECT_CONNECTORS_URL_FORMAT = FIREBASE_DATA_CONNECT_PROD_URL +
'/{version}' +
'/projects/{projectId}' +
'/locations/{locationId}' +
'/services/{serviceId}' +
'/connectors/{connectorId}' +
':{endpointId}';
/** Firebase Data Connect service URL format when using the Data Connect emulator. */
const FIREBASE_DATA_CONNECT_EMULATOR_SERVICES_URL_FORMAT = 'http://{host}/{version}/projects/{projectId}/locations/{locationId}/services/{serviceId}:{endpointId}';
/** Firebase Data Connect connector URL format when using the Data Connect emulator. */
const FIREBASE_DATA_CONNECT_EMULATOR_CONNECTORS_URL_FORMAT = 'http://{host}/{version}/projects/{projectId}/locations/{locationId}/services/{serviceId}/connectors/{connectorId}:{endpointId}';
const EXECUTE_GRAPH_QL_ENDPOINT = 'executeGraphql';
const EXECUTE_GRAPH_QL_READ_ENDPOINT = 'executeGraphqlRead';
const IMPERSONATE_QUERY_ENDPOINT = 'impersonateQuery';
const IMPERSONATE_MUTATION_ENDPOINT = 'impersonateMutation';
/** @internal The maximum number of items allowed in the @allow directive's maxCount argument. */
exports.ALLOW_DIRECTIVE_MAX_COUNT = 10_000;
function getHeaders(isUsingGen) {
const headerValue = {
'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`,
'X-Goog-Api-Client': utils.getMetricsHeader(),
};
if (isUsingGen) {
headerValue['X-Goog-Api-Client'] += ' admin-js/gen';
}
return headerValue;
}
/**
* Class that facilitates sending requests to the Firebase Data Connect backend API.
*
* @internal
*/
class DataConnectApiClient {
constructor(connectorConfig, app) {
this.connectorConfig = connectorConfig;
this.app = app;
this.isUsingGen = false;
if (!validator.isNonNullObject(app) || !('options' in app)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: 'First argument passed to getDataConnect() must be a valid Firebase app instance.'
});
}
this.httpClient = new DataConnectHttpClient(app);
}
/**
* Update whether the SDK is using a generated one or not.
* @param isUsingGen
*/
setIsUsingGen(isUsingGen) {
this.isUsingGen = isUsingGen;
}
/**
* Execute arbitrary GraphQL, including both read and write queries
*
* @param query - The GraphQL string to be executed.
* @param options - GraphQL Options
* @returns A promise that fulfills with a `ExecuteGraphqlResponse`.
*/
async executeGraphql(query, options) {
return this.executeGraphqlHelper(query, EXECUTE_GRAPH_QL_ENDPOINT, options);
}
/**
* Execute arbitrary read-only GraphQL queries
*
* @param query - The GraphQL (read-only) string to be executed.
* @param options - GraphQL Options
* @returns A promise that fulfills with a `ExecuteGraphqlResponse`.
* @throws FirebaseDataConnectError
*/
async executeGraphqlRead(query, options) {
return this.executeGraphqlHelper(query, EXECUTE_GRAPH_QL_READ_ENDPOINT, options);
}
/**
* A helper function to execute GraphQL queries.
*
* @param query - The arbitrary GraphQL query to execute.
* @param endpoint - The endpoint to call.
* @param options - The GraphQL options.
* @returns A promise that fulfills with the GraphQL response, or throws an error.
*/
async executeGraphqlHelper(query, endpoint, options) {
if (!validator.isNonEmptyString(query)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: '`query` must be a non-empty string.'
});
}
if (typeof options !== 'undefined') {
if (!validator.isNonNullObject(options)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: 'GraphqlOptions must be a non-null object'
});
}
}
const data = {
query,
...(options?.variables && { variables: options?.variables }),
...(options?.operationName && { operationName: options?.operationName }),
...(options?.impersonate && { extensions: { impersonate: options?.impersonate } }),
};
const url = await this.getServicesUrl(API_VERSION, this.connectorConfig.location, this.connectorConfig.serviceId, endpoint);
try {
const resp = await this.makeGqlRequest(url, data);
return resp;
}
catch (err) {
throw this.toFirebaseError(err);
}
}
/**
* Executes a GraphQL query with impersonation.
*
* @param options - The GraphQL options. Must include impersonation details.
* @returns A promise that fulfills with the GraphQL response.
*/
async executeQuery(name, variables, options) {
return this.executeOperationHelper(IMPERSONATE_QUERY_ENDPOINT, name, variables, options);
}
/**
* Executes a GraphQL mutation with impersonation.
*
* @param options - The GraphQL options. Must include impersonation details.
* @returns A promise that fulfills with the GraphQL response.
*/
async executeMutation(name, variables, options) {
return this.executeOperationHelper(IMPERSONATE_MUTATION_ENDPOINT, name, variables, options);
}
/**
* A helper function to execute operations by making requests to FDC's impersonate
* operations endpoints.
*
* @param endpoint - The endpoint to call.
* @param options - The GraphQL options, including impersonation details.
* @returns A promise that fulfills with the GraphQL response.
*/
async executeOperationHelper(endpoint, name, variables, options) {
if (typeof name === 'undefined' ||
!validator.isNonEmptyString(name)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: '`name` must be a non-empty string.'
});
}
if (this.connectorConfig.connector === undefined || this.connectorConfig.connector === '') {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: `The 'connectorConfig.connector' field used to instantiate your Data Connect
instance must be a non-empty string (the connectorId) when calling executeQuery or executeMutation.`
});
}
const data = {
...(variables && { variables: variables }),
operationName: name,
extensions: { impersonate: options?.impersonate },
};
const url = await this.getConnectorsUrl(API_VERSION, this.connectorConfig.location, this.connectorConfig.serviceId, this.connectorConfig.connector, endpoint);
try {
const resp = await this.makeGqlRequest(url, data);
return resp;
}
catch (err) {
throw this.toFirebaseError(err);
}
}
/**
* Constructs the URL for a Data Connect request to a service endpoint.
*
* @param version - The API version.
* @param locationId - The location of the Data Connect service.
* @param serviceId - The ID of the Data Connect service.
* @param endpointId - The endpoint to call.
* @returns A promise which resolves to the formatted URL string.
*/
async getServicesUrl(version, locationId, serviceId, endpointId) {
const projectId = await this.getProjectId();
const params = {
version,
projectId,
locationId,
serviceId,
endpointId,
};
let urlFormat = FIREBASE_DATA_CONNECT_SERVICES_URL_FORMAT;
if (useEmulator()) {
urlFormat = FIREBASE_DATA_CONNECT_EMULATOR_SERVICES_URL_FORMAT;
params.host = emulatorHost();
}
return utils.formatString(urlFormat, params);
}
/**
* Constructs the URL for a Data Connect request to a connector endpoint.
*
* @param version - The API version.
* @param locationId - The location of the Data Connect service.
* @param serviceId - The ID of the Data Connect service.
* @param connectorId - The ID of the Connector.
* @param endpointId - The endpoint to call.
* @returns A promise which resolves to the formatted URL string.
*/
async getConnectorsUrl(version, locationId, serviceId, connectorId, endpointId) {
const projectId = await this.getProjectId();
const params = {
version,
projectId,
locationId,
serviceId,
connectorId,
endpointId,
};
let urlFormat = FIREBASE_DATA_CONNECT_CONNECTORS_URL_FORMAT;
if (useEmulator()) {
urlFormat = FIREBASE_DATA_CONNECT_EMULATOR_CONNECTORS_URL_FORMAT;
params.host = emulatorHost();
}
return utils.formatString(urlFormat, params);
}
getProjectId() {
if (this.projectId) {
return Promise.resolve(this.projectId);
}
return utils.findProjectId(this.app)
.then((projectId) => {
if (!validator.isNonEmptyString(projectId)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.UNKNOWN,
message: 'Failed to determine project ID. Initialize the '
+ 'SDK with service account credentials or set project ID as an app option. '
+ 'Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.'
});
}
this.projectId = projectId;
return projectId;
});
}
/**
* Makes a GraphQL request to the specified url.
*
* @param url - The URL to send the request to.
* @param data - The GraphQL request payload.
* @returns A promise that fulfills with the GraphQL response, or throws an error.
*/
async makeGqlRequest(url, data) {
const request = {
method: 'POST',
url,
headers: getHeaders(this.isUsingGen),
data,
};
const resp = await this.httpClient.send(request);
if (resp.data.errors && validator.isNonEmptyArray(resp.data.errors)) {
const allMessages = resp.data.errors.map((error) => error.message).join(' ');
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.QUERY_ERROR,
message: allMessages,
httpResponse: (0, error_1.toHttpResponse)(resp),
});
}
return Promise.resolve({
data: resp.data.data,
});
}
toFirebaseError(err) {
if (err instanceof error_1.FirebaseError) {
return err;
}
const response = err.response;
if (!response.isJson()) {
return new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.UNKNOWN,
message: `Unexpected response with status: ${response.status} and body: ${response.text}`,
httpResponse: (0, error_1.toHttpResponse)(response),
cause: err
});
}
const data = response.data;
const error = (validator.isNonNullObject(data) && validator.isNonNullObject(data.error))
? data.error
: (validator.isNonNullObject(data) ? data : {});
let status = error.status;
if (!status && validator.isNumber(error.code)) {
status = error_2.EMULATOR_GRPC_STATUS_CODE_TO_STRING[error.code];
}
let code = error_2.DATA_CONNECT_ERROR_CODE_MAPPING.UNKNOWN;
if (status && status in error_2.DATA_CONNECT_ERROR_CODE_MAPPING) {
code = error_2.DATA_CONNECT_ERROR_CODE_MAPPING[status];
}
const message = error.message || 'Unknown server error';
return new error_2.FirebaseDataConnectError({
code,
message,
httpResponse: (0, error_1.toHttpResponse)(response),
cause: err,
});
}
/**
* Generates both capitalized and camel-cased variations of a table name.
* Capitalization matches the schema types, and camel-case matches mutations.
*/
getTableNames(tableName) {
if (!tableName || tableName.length === 0) {
return { capitalized: tableName, camelCase: tableName };
}
const capitalized = tableName.charAt(0).toUpperCase() + tableName.slice(1);
const camelCase = tableName.charAt(0).toLowerCase() + tableName.slice(1);
return { capitalized, camelCase };
}
handleBulkImportErrors(err) {
if (err.code === `data-connect/${error_2.DATA_CONNECT_ERROR_CODE_MAPPING.QUERY_ERROR}`) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.QUERY_ERROR,
message: `${err.message}. Make sure that your table name passed in matches the type name in your `
+ 'GraphQL schema file.',
cause: err,
});
}
throw err;
}
/**
* Insert a single row into the specified table.
*/
async insert(tableName, data) {
return this.executeSingleMutation(tableName, data, 'insert');
}
/**
* Insert multiple rows into the specified table.
*/
async insertMany(tableName, data) {
return this.executeBulkMutation(tableName, data, 'insertMany');
}
/**
* Insert a single row into the specified table, or update it if it already exists.
*/
async upsert(tableName, data) {
return this.executeSingleMutation(tableName, data, 'upsert');
}
/**
* Insert multiple rows into the specified table, or update them if they already exist.
*/
async upsertMany(tableName, data) {
return this.executeBulkMutation(tableName, data, 'upsertMany');
}
async executeSingleMutation(tableName, data, operationType) {
if (!validator.isNonEmptyString(tableName)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: '`tableName` must be a non-empty string.'
});
}
if (validator.isArray(data)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: `\`data\` must be an object, not an array, for single ${operationType}.\
For arrays, please use \`${operationType}Many\` function.`
});
}
if (!validator.isNonNullObject(data)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: '`data` must be a non-null object.'
});
}
try {
const { capitalized, camelCase } = this.getTableNames(tableName);
const keys = getFieldsString(data);
const mutation = `mutation($data: ${capitalized}_Data! @allow(fields: "${keys}")) {
${camelCase}_${operationType}(data: $data)
}`;
return this.executeGraphql(mutation, { variables: { data } })
.catch(this.handleBulkImportErrors);
}
catch (e) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INTERNAL,
message: `Failed to construct ${operationType} mutation: ${e.message}`,
cause: e,
});
}
}
async executeBulkMutation(tableName, data, operationType) {
if (!validator.isNonEmptyString(tableName)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: '`tableName` must be a non-empty string.'
});
}
if (!validator.isNonEmptyArray(data)) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: `\`data\` must be a non-empty array for ${operationType}.`
});
}
if (data.length > exports.ALLOW_DIRECTIVE_MAX_COUNT) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT,
message: `\`data\` array exceeds the maximum limit of ${exports.ALLOW_DIRECTIVE_MAX_COUNT} items.`
});
}
try {
const { capitalized, camelCase } = this.getTableNames(tableName);
const keys = getFieldsString(data);
const mutation = `mutation($data: [${capitalized}_Data!]! @allow(fields: "${keys}", maxCount: ${exports.ALLOW_DIRECTIVE_MAX_COUNT})) {
${camelCase}_${operationType}(data: $data)
}`;
return this.executeGraphql(mutation, { variables: { data } })
.catch(this.handleBulkImportErrors);
}
catch (e) {
throw new error_2.FirebaseDataConnectError({
code: error_2.DATA_CONNECT_ERROR_CODE_MAPPING.INTERNAL,
message: `Failed to construct ${operationType} mutation: ${e.message}`,
cause: e,
});
}
}
}
exports.DataConnectApiClient = DataConnectApiClient;
/**
* Data Connect-specific HTTP client which uses the special "owner" token
* when communicating with the Data Connect Emulator.
*/
class DataConnectHttpClient extends api_request_1.AuthorizedHttpClient {
getToken() {
if (useEmulator()) {
return Promise.resolve('owner');
}
return super.getToken();
}
}
function emulatorHost() {
return process.env.DATA_CONNECT_EMULATOR_HOST;
}
/**
* When true the SDK should communicate with the Data Connect Emulator for all API
* calls and also produce unsigned tokens.
*/
function useEmulator() {
return !!emulatorHost();
}
/**
* Extracts property keys from an object or array of objects as a space-separated string,
* including recursively nested object/array fields for the `@allow(fields: ...)` directive.
* Leverages a hierarchical tree to deduplicate and merge fields.
*
* @internal
*/
function getFieldsString(data) {
const root = { children: new Map() };
mergeFieldsIntoTree(data, root);
return serializeFieldNode(root);
}
function mergeFieldsIntoTree(data, node, visited = new Set()) {
if (validator.isArray(data)) {
data.forEach((item) => mergeFieldsIntoTree(item, node, visited));
return;
}
if (!validator.isNonNullObject(data) || data instanceof Date) {
return;
}
if (visited.has(data)) {
throw new Error('Circular reference detected in input.');
}
visited.add(data);
const record = data;
for (const [key, val] of Object.entries(record)) {
if (val === undefined) {
continue;
}
let childNode = node.children.get(key);
if (!childNode) {
childNode = { children: new Map() };
node.children.set(key, childNode);
}
if (key.includes('_on_')) {
mergeFieldsIntoTree(val, childNode, visited);
}
}
visited.delete(data);
}
function serializeFieldNode(node) {
const parts = [];
const sortedKeys = Array.from(node.children.keys()).sort((a, b) => a.localeCompare(b));
for (const key of sortedKeys) {
const childNode = node.children.get(key);
if (childNode.children.size > 0) {
const nestedString = serializeFieldNode(childNode);
parts.push(`${key} { ${nestedString} }`);
}
else {
parts.push(key);
}
}
return parts.join(' ');
}