import { Datastore } from '@google-cloud/datastore';
import { createQueryFilter, isIterable } from 'cpb-common';
import grpc from '@grpc/grpc-js';
import Index from './datastoreIndex.js';
import Delete from './delete.js';
import query from './query.js';
import save from './save.js';
import update from './update.js';
/**
* @module cpb-datastore
* # Google Cloud Datastore Operations
* */
/**
* ## Datastore Instance
* GRPc is required as a workaround for Error 4: DEADLINE_EXCEEDED
* *type {import('@google-cloud/datastore').Datastore}
* @member module:cpb-datastore.datastore
*/
export const datastore = new Datastore({ grpc });
/**
* ## Development Datastore Emulator Instance
* ENV:DATASTORE_EMULATOR_HOST is required to be set
* type {import('@google-cloud/datastore').Datastore}
* @member module:cpb-datastore.datastoreEmulator
*/
export const datastoreEmulator = new Datastore({
// grpc,
apiEndpoint: process.env.DATASTORE_EMULATOR_HOST || `http://localhost:8081`,
});
/**
* ## Loose Compare datastore keys or key values for equality.
* If the values are supplied it converted to the {Datastore.KEY} instance.
* @member module:cpb-datastore.compareKeys
* @param {*} a - value or key to compare
* @param {*} b - value or key to compare
* @param {?string} [kind=undefined] - datastore kind. If the values are supplied the keys with such values are
* created and compared
* @returns {boolean} compareResult - the result of the comparison
*/
export function compareKeys(a, b, kind) {
const keyA = datastore.isKey(a) ? a : datastore.key([kind, a]),
keyB = datastore.isKey(b) ? b : datastore.key([kind, b]);
// console.debug('DataStore.compareKeys', util.inspect({ keyA: keyA.path.toString(), keyB: keyB.path.toString() }));
return keyA.path.toString() === keyB.path.toString();
}
/**
* Get Datastore Keys for the Datastore Record or Records
* param {{}|{}[]} records - records to get keys from
* @param {{}|Array()} records - records to get keys from
* @return {Datastore.KEY[]} keys - datastore keys for the records
*/
export function getRecordKeys(records) {
if (!records || !records.length) {
console.warn(`[datastore/getRecordKeys] NO_RECORDS`);
return;
}
const keys = [];
const rows = isIterable(records) ? records : [records];
for (const record of rows) keys.push(record[datastore.KEY]);
return keys;
}
export const Keys = {
compare: compareKeys,
get: getRecordKeys,
};
export { query, update, save, Index, Delete as delete, createQueryFilter };
export default {
query,
update,
save,
delete: Delete,
datastore,
compareKeys,
getRecordKeys,
Index,
Keys,
createQueryFilter,
};