@neo4j/cypher-builder
Version:
A programmatic API for building Cypher queries for Neo4j
98 lines (97 loc) • 3.23 kB
JavaScript
;
/*
* 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.MapProjection = void 0;
const escape_1 = require("../../utils/escape");
const is_string_1 = require("../../utils/is-string");
const serialize_map_1 = require("../../utils/serialize-map");
const MapExpr_1 = require("./MapExpr");
/** Represents a Map projection
* @see {@link https://neo4j.com/docs/cypher-manual/current/syntax/maps/#cypher-map-projection | Cypher Documentation}
* @group Maps
* @example
* ```cypher
* this { .title }
* ```
*/
class MapProjection {
constructor(variable, projection = [], extraValues = {}) {
this.extraValues = new Map();
this.isStar = false;
this.variable = variable;
if (projection === "*") {
this.isStar = true;
this.projection = [];
}
else {
this.projection = projection;
}
this.setExtraValues(extraValues);
}
set(values) {
if ((0, is_string_1.isString)(values)) {
this.projection.push(values);
}
else {
this.setExtraValues(values);
}
}
/** Converts the Map projection expression into a normal Map expression
* @example
* Converts
* ```cypher
* this { .title }
* ```
* into:
* ```cypher
* { title: this.title }
* ```
*/
toMap() {
const projectionFields = this.projection.reduce((acc, field) => {
acc[field] = this.variable.property(field);
return acc;
}, {});
return new MapExpr_1.MapExpr({
...projectionFields,
...Object.fromEntries(this.extraValues),
});
}
/** @internal */
getCypher(env) {
const variableStr = this.variable.getCypher(env);
const extraValuesStr = (0, serialize_map_1.serializeMap)(env, this.extraValues, true);
const escapedColumns = this.projection.map((p) => `.${(0, escape_1.escapeProperty)(p)}`);
if (this.isStar) {
escapedColumns.unshift(".*");
}
const projectionStr = escapedColumns.join(", ");
const commaStr = extraValuesStr && projectionStr ? ", " : "";
return `${variableStr} { ${projectionStr}${commaStr}${extraValuesStr} }`;
}
setExtraValues(values) {
Object.entries(values).forEach(([key, value]) => {
if (!value)
throw new Error(`Missing value on map key ${key}`);
this.extraValues.set(key, value);
});
}
}
exports.MapProjection = MapProjection;