@neo4j/cypher-builder
Version:
A programmatic API for building Cypher queries for Neo4j
97 lines (96 loc) • 3.06 kB
JavaScript
"use strict";
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.CypherEnvironment = void 0;
const Param_1 = require("./references/Param");
const defaultConfig = {
labelOperator: ":",
unsafeEscapeOptions: {},
cypherVersion: undefined,
};
/** Hold the internal references of Cypher parameters and variables
* @group Internal
*/
class CypherEnvironment {
/**
* @internal
*/
constructor(prefix, config = {}) {
this.references = new Map();
this.params = [];
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) {
Object.entries(params).forEach(([key, param]) => {
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;