@neo4j/cypher-builder
Version:
A programmatic API for building Cypher queries for Neo4j
84 lines (83 loc) • 2.46 kB
JavaScript
;
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.CypherEnvironment = void 0;
const Param_1 = require("./references/Param");
const defaultConfig = {
unsafeEscapeOptions: {},
cypherVersion: undefined,
};
/** Hold the internal references of Cypher parameters and variables
* @group Internal
*/
class CypherEnvironment {
globalPrefix;
references = new Map();
params = [];
config;
/**
* @internal
*/
constructor(prefix, config = {}) {
this.globalPrefix = prefix ?? "";
this.config = {
...defaultConfig,
...config,
};
}
getReferenceId(reference) {
if (this.isNamedReference(reference))
return reference.id; // Overrides ids for compatibility reasons
const id = this.references.get(reference);
if (!id) {
return this.addVariableReference(reference);
}
return id;
}
getParams() {
return this.params.reduce((acc, param) => {
const key = this.getReferenceId(param);
if (param.hasValue) {
acc[key] = param.value;
}
return acc;
}, {});
}
addExtraParams(params) {
for (const [key, param] of Object.entries(params)) {
this.addNamedParamReference(key, param);
}
}
addNamedParamReference(name, param) {
if (!this.references.has(param)) {
this.addParam(name, param);
}
}
getParamsSize() {
return this.params.length;
}
addParam(id, param) {
const paramId = id;
this.references.set(param, paramId);
this.params.push(param);
return paramId;
}
addVariableReference(variable) {
const paramIndex = this.getParamsSize(); // Indexes are separate for readability reasons
if (variable instanceof Param_1.Param) {
const varId = `${this.globalPrefix}${variable.prefix}${paramIndex}`;
return this.addParam(varId, variable);
}
const varIndex = this.references.size - paramIndex;
const varId = `${this.globalPrefix}${variable.prefix}${varIndex}`;
this.references.set(variable, varId);
return varId;
}
isNamedReference(ref) {
return "id" in ref;
}
}
exports.CypherEnvironment = CypherEnvironment;