diff --git a/packages/core/src/graph-types.ts b/packages/core/src/graph-types.ts index b1f025c21..1001d0486 100644 --- a/packages/core/src/graph-types.ts +++ b/packages/core/src/graph-types.ts @@ -16,6 +16,7 @@ */ import Integer from './integer' import { stringify } from './json' +import { Rules, GenericConstructor, as } from './mapping.highlevel' type StandardDate = Date /** @@ -82,6 +83,22 @@ class Node identity.toString()) } + /** + * Hydrates an object of a given type with the properties of the node + * + * @param {GenericConstructor | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration + * @param {Rules} [rules] {@link Rules} for the hydration + * @returns {T} + */ + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): T + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + return as({ + get: (key) => this.properties[key] + }, constructorOrRules, rules) + } + /** * @ignore */ @@ -199,6 +216,22 @@ class Relationship end.toString()) } + /** + * Hydrates an object of a given type with the properties of the relationship + * + * @param {GenericConstructor | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration + * @param {Rules} [rules] {@link Rules} for the hydration + * @returns {T} + */ + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): T + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + return as({ + get: (key) => this.properties[key] + }, constructorOrRules, rules) + } + /** * @ignore */ @@ -320,6 +353,22 @@ class UnboundRelationship | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration + * @param {Rules} [rules] {@link Rules} for the hydration + * @returns {T} + */ + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): T + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + return as({ + get: (key) => this.properties[key] + }, constructorOrRules, rules) + } + /** * @ignore */ diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5c3871b9e..98e3838d4 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -82,7 +82,7 @@ import NotificationFilter, { notificationFilterMinimumSeverityLevel, NotificationFilterMinimumSeverityLevel } from './notification-filter' -import Result, { QueryResult, ResultObserver } from './result' +import Result, { MappedQueryResult, QueryResult, ResultObserver } from './result' import EagerResult from './result-eager' import ConnectionProvider, { Releasable } from './connection-provider' import Connection from './connection' @@ -101,6 +101,9 @@ import * as json from './json' import resultTransformers, { ResultTransformer } from './result-transformers' import ClientCertificate, { clientCertificateProviders, ClientCertificateProvider, ClientCertificateProviders, RotatingClientCertificateProvider, resolveCertificateProvider } from './client-certificate' import * as internal from './internal' // todo: removed afterwards +import { StandardCase } from './mapping.nameconventions' +import { Rule, Rules, RecordObjectMapping } from './mapping.highlevel' +import { RulesFactories } from './mapping.rulesfactories' /** * Object containing string constants representing predefined {@link Neo4jError} codes. @@ -186,7 +189,10 @@ const forExport = { notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, clientCertificateProviders, - resolveCertificateProvider + resolveCertificateProvider, + RulesFactories, + RecordObjectMapping, + StandardCase } export { @@ -263,7 +269,10 @@ export { notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, clientCertificateProviders, - resolveCertificateProvider + resolveCertificateProvider, + RulesFactories, + RecordObjectMapping, + StandardCase } export type { @@ -271,6 +280,7 @@ export type { NumberOrInteger, NotificationPosition, QueryResult, + MappedQueryResult, ResultObserver, TransactionConfig, BookmarkManager, @@ -294,7 +304,9 @@ export type { ClientCertificate, ClientCertificateProvider, ClientCertificateProviders, - RotatingClientCertificateProvider + RotatingClientCertificateProvider, + Rule, + Rules } export default forExport diff --git a/packages/core/src/internal/observers.ts b/packages/core/src/internal/observers.ts index 07e5b919b..e20a6185b 100644 --- a/packages/core/src/internal/observers.ts +++ b/packages/core/src/internal/observers.ts @@ -16,6 +16,7 @@ */ import Record from '../record' +import { GenericResultObserver } from '../result' import ResultSummary from '../result-summary' interface StreamObserver { @@ -115,7 +116,7 @@ export interface ResultStreamObserver extends StreamObserver { * @param {function(metadata: Object)} observer.onCompleted - Handle stream tail, the summary. * @param {function(error: Object)} observer.onError - Handle errors, should always be provided. */ - subscribe: (observer: ResultObserver) => void + subscribe: (observer: GenericResultObserver) => void } export class CompletedObserver implements ResultStreamObserver { diff --git a/packages/core/src/mapping.highlevel.ts b/packages/core/src/mapping.highlevel.ts new file mode 100644 index 000000000..7dced3475 --- /dev/null +++ b/packages/core/src/mapping.highlevel.ts @@ -0,0 +1,189 @@ +/** + * 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. + */ + +import { newError } from './error' +import { nameConventions, StandardCase } from './mapping.nameconventions' + +/** + * constructor function of any class + */ +export type GenericConstructor = new (...args: any[]) => T + +export interface Rule { + optional?: boolean + from?: string + convert?: (recordValue: any, field: string) => any + validate?: (recordValue: any, field: string) => void +} + +export type Rules = Record + +let rulesRegistry: Record = {} + +let nameMapping: (name: string) => string = (name) => name + +function register (constructor: GenericConstructor, rules: Rules): void { + rulesRegistry[constructor.toString()] = rules +} + +function clearMappingRegistry (): void { + rulesRegistry = {} +} + +function translateIdentifiers (translationFunction: (name: string) => string): void { + nameMapping = translationFunction +} + +function getCaseTranslator (databaseConvention: string | StandardCase, codeConvention: string | StandardCase): ((name: string) => string) { + const keys = Object.keys(nameConventions) + if (!keys.includes(databaseConvention)) { + throw newError( + `Naming convention ${databaseConvention} is not recognized, + please provide a recognized name convention or manually provide a translation function.` + ) + } + if (!keys.includes(codeConvention)) { + throw newError( + `Naming convention ${codeConvention} is not recognized, + please provide a recognized name convention or manually provide a translation function.` + ) + } + // @ts-expect-error + return (name: string) => nameConventions[databaseConvention].encode(nameConventions[codeConvention].tokenize(name)) +} + +export const RecordObjectMapping = Object.freeze({ + /** + * Clears all registered type mappings from the record object mapping registry. + * @experimental + */ + clearMappingRegistry, + /** + * Creates a translation frunction from record key names to object property names, for use with the {@link translateIdentifiers} function + * + * Recognized naming conventions are "camelCase", "PascalCase", "snake_case", "kebab-case", "SCREAMING_SNAKE_CASE" + * + * @experimental + * @param {string} databaseConvention The naming convention in use in database result Records + * @param {string} codeConvention The naming convention in use in JavaScript object properties + * @returns {function} translation function + */ + getCaseTranslator, + /** + * Registers a set of {@link Rules} to be used by {@link hydrated} for the provided class when no other rules are specified. This registry exists in global memory, not the driver instance. + * + * @example + * // The following code: + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydrated(Person, personClassRules) + * }) + * + * can instead be written: + * neo4j.RecordObjectMapping.register(Person, personClassRules) + * + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydrated(Person) + * }) + * + * @experimental + * @param {GenericConstructor} constructor The constructor function of the class to set rules for + * @param {Rules} rules The rules to set for the provided class + */ + register, + /** + * Sets a default name translation from record keys to object properties. + * If providing a function, provide a function that maps FROM your object properties names TO record key names. + * + * The function getCaseTranslator can be used to provide a prewritten translation function between some common naming conventions. + * + * @example + * //if the keys on records from the database are in ALLCAPS + * RecordObjectMapping.translateIdentifiers((name) => name.toUpperCase()) + * + * //if you utilize PacalCase in the database and camelCase in JavaScript code. + * RecordObjectMapping.translateIdentifiers(mapping.getCaseTranslator("PascalCase", "camelCase")) + * + * //if a type has one odd mapping you can override the translation with the rule + * const personRules = { + * firstName: neo4j.RulesFactories.asString(), + * bornAt: neo4j.RulesFactories.asNumber({ acceptBigInt: true, optional: true }) + * weird_name-property: neo4j.RulesFactories.asString({from: 'homeTown'}) + * } + * //These rules can then be used by providing them to a hydratedResultsMapper + * record.as(personRules) + * //or by registering them to the mapping registry + * RecordObjectMapping.register(Person, personRules) + * + * @experimental + * @param {function} translationFunction A function translating the names of your JS object property names to record key names + */ + translateIdentifiers +}) + +interface Gettable { get: (key: string) => V } + +export function as (gettable: Gettable, constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + const GenericConstructor = typeof constructorOrRules === 'function' ? constructorOrRules : Object + const theRules = getRules(constructorOrRules, rules) + const vistedKeys: string[] = [] + + const obj = new GenericConstructor() + + for (const [key, rule] of Object.entries(theRules ?? {})) { + vistedKeys.push(key) + _apply(gettable, obj, key, rule) + } + + for (const key of Object.getOwnPropertyNames(obj)) { + if (!vistedKeys.includes(key)) { + _apply(gettable, obj, key, theRules?.[key]) + } + } + + return obj as unknown as T +} + +function _apply (gettable: Gettable, obj: T, key: string, rule?: Rule): void { + const mappedkey = nameMapping(key) + const value = gettable.get(rule?.from ?? mappedkey) + const field = `${obj.constructor.name}#${key}` + const processedValue = valueAs(value, field, rule) + // @ts-expect-error + obj[key] = processedValue ?? obj[key] +} + +export function valueAs (value: unknown, field: string, rule?: Rule): unknown { + if (rule?.optional === true && value == null) { + return value + } + + if (typeof rule?.validate === 'function') { + rule.validate(value, field) + } + + return ((rule?.convert) != null) ? rule.convert(value, field) : value +} +function getRules (constructorOrRules: Rules | GenericConstructor, rules: Rules | undefined): Rules | undefined { + const rulesDefined = typeof constructorOrRules === 'object' ? constructorOrRules : rules + if (rulesDefined != null) { + return rulesDefined + } + + return typeof constructorOrRules !== 'object' ? rulesRegistry[constructorOrRules.toString()] : undefined +} diff --git a/packages/core/src/mapping.nameconventions.ts b/packages/core/src/mapping.nameconventions.ts new file mode 100644 index 000000000..75b2b00cd --- /dev/null +++ b/packages/core/src/mapping.nameconventions.ts @@ -0,0 +1,70 @@ +/** + * 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. + */ + +export interface NameConvention { + tokenize: (name: string) => string[] + encode: (tokens: string[]) => string +} + +export enum StandardCase { + SnakeCase = 'snake_case', + KebabCase = 'kebab-case', + ScreamingSnakeCase = 'SCREAMING_SNAKE_CASE', + PascalCase = 'PascalCase', + CamelCase = 'camelCase' +} + +export const nameConventions = { + snake_case: { + tokenize: (name: string) => name.split('_'), + encode: (tokens: string[]) => tokens.join('_') + }, + 'kebab-case': { + tokenize: (name: string) => name.split('-'), + encode: (tokens: string[]) => tokens.join('-') + }, + PascalCase: { + tokenize: (name: string) => name.split(/(?=[A-Z])/).map((token) => token.toLowerCase()), + encode: (tokens: string[]) => { + let name: string = '' + for (let token of tokens) { + token = token.charAt(0).toUpperCase() + token.slice(1) + name += token + } + return name + } + }, + camelCase: { + tokenize: (name: string) => name.split(/(?=[A-Z])/).map((token) => token.toLowerCase()), + encode: (tokens: string[]) => { + let name: string = '' + for (let [i, token] of tokens.entries()) { + if (i !== 0) { + token = token.charAt(0).toUpperCase() + token.slice(1) + } + name += token + } + return name + } + }, + SCREAMING_SNAKE_CASE: { + tokenize: (name: string) => name.split('_').map((token) => token.toLowerCase()), + encode: (tokens: string[]) => tokens.join('_').toUpperCase() + } +} diff --git a/packages/core/src/mapping.rulesfactories.ts b/packages/core/src/mapping.rulesfactories.ts new file mode 100644 index 000000000..f0f0b6f9f --- /dev/null +++ b/packages/core/src/mapping.rulesfactories.ts @@ -0,0 +1,378 @@ +/** + * 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. + */ + +import { Rule, valueAs } from './mapping.highlevel' +import { StandardDate, isNode, isPath, isRelationship, isUnboundRelationship } from './graph-types' +import { isPoint } from './spatial-types' +import { Date, DateTime, Duration, LocalDateTime, LocalTime, Time, isDate, isDateTime, isDuration, isLocalDateTime, isLocalTime, isTime } from './temporal-types' + +/** + * @property {function(rule: ?Rule)} asString Create a {@link Rule} that validates the value is a String. + * + * @property {function(rule: ?Rule & { acceptBigInt?: boolean })} asNumber Create a {@link Rule} that validates the value is a Number. + * + * @property {function(rule: ?Rule & { acceptNumber?: boolean })} AsBigInt Create a {@link Rule} that validates the value is a BigInt. + * + * @property {function(rule: ?Rule)} asNode Create a {@link Rule} that validates the value is a {@link Node}. + * + * @property {function(rule: ?Rule)} asRelationship Create a {@link Rule} that validates the value is a {@link Relationship}. + * + * @property {function(rule: ?Rule)} asPath Create a {@link Rule} that validates the value is a {@link Path}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asDuration Create a {@link Rule} that validates the value is a {@link Duration}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asLocalTime Create a {@link Rule} that validates the value is a {@link LocalTime}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asLocalDateTime Create a {@link Rule} that validates the value is a {@link LocalDateTime}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asTime Create a {@link Rule} that validates the value is a {@link Time}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asDateTime Create a {@link Rule} that validates the value is a {@link DateTime}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asDate Create a {@link Rule} that validates the value is a {@link Date}. + * + * @property {function(rule: ?Rule)} asPoint Create a {@link Rule} that validates the value is a {@link Point}. + * + * @property {function(rule: ?Rule & { apply?: Rule })} asList Create a {@link Rule} that validates the value is a List. + * + * @experimental + */ +export const RulesFactories = Object.freeze({ + /** + * Create a {@link Rule} that validates the value is a Boolean. + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asBoolean (rule?: Rule): Rule { + return { + validate: (value, field) => { + if (typeof value !== 'boolean') { + throw new TypeError(`${field} should be a boolean but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a String. + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asString (rule?: Rule): Rule { + return { + validate: (value, field) => { + if (typeof value !== 'string') { + throw new TypeError(`${field} should be a string but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Number}. + * + * @experimental + * @param {Rule & { acceptBigInt?: boolean }} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asNumber (rule?: Rule & { acceptBigInt?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (typeof value === 'object' && value.low !== undefined && value.high !== undefined && Object.keys(value).length === 2) { + throw new TypeError('Number returned as Object. To use asNumber mapping, set disableLosslessIntegers or useBigInt in driver config object') + } + if (typeof value !== 'number' && (rule?.acceptBigInt !== true || typeof value !== 'bigint')) { + throw new TypeError(`${field} should be a number but received ${typeof value}`) + } + }, + convert: (value: number | bigint) => { + if (typeof value === 'bigint') { + return Number(value) + } + return value + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link BigInt}. + * + * @experimental + * @param {Rule & { acceptNumber?: boolean }} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asBigInt (rule?: Rule & { acceptNumber?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (typeof value !== 'bigint' && (rule?.acceptNumber !== true || typeof value !== 'number')) { + throw new TypeError(`${field} should be a bigint but received ${typeof value}`) + } + }, + convert: (value: number | bigint) => { + if (typeof value === 'number') { + return BigInt(value) + } + return value + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Node}. + * + * @example + * const actingJobsRules: Rules = { + * // Converts the person node to a Person object in accordance with provided rules + * person: neo4j.RulesFactories.asNode({ + * convert: (node: Node) => node.as(Person, personRules) + * }), + * // Returns the movie node as a Node + * movie: neo4j.RulesFactories.asNode({}), + * } + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asNode (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isNode(value)) { + throw new TypeError(`${field} should be a Node but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Relationship}. + * + * @param {Rule} rule Configurations for the rule. + * @returns {Rule} A new rule for the value + */ + asRelationship (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isRelationship(value)) { + throw new TypeError(`${field} should be a Relationship but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is an {@link UnboundRelationship} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asUnboundRelationship (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isUnboundRelationship(value)) { + throw new TypeError(`${field} should be a UnboundRelationship but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Path} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asPath (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isPath(value)) { + throw new TypeError(`${field} should be a Path but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Point} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asPoint (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isPoint(value)) { + throw new TypeError(`${field} should be a Point but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Duration} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asDuration (rule?: Rule & { toString?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isDuration(value)) { + throw new TypeError(`${field} should be a Duration but received ${typeof value}`) + } + }, + convert: (value: Duration) => rule?.toString === true ? value.toString() : value, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link LocalTime} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asLocalTime (rule?: Rule & { toString?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isLocalTime(value)) { + throw new TypeError(`${field} should be a LocalTime but received ${typeof value}`) + } + }, + convert: (value: LocalTime) => rule?.toString === true ? value.toString() : value, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Time} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asTime (rule?: Rule & { toString?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isTime(value)) { + throw new TypeError(`${field} should be a Time but received ${typeof value}`) + } + }, + convert: (value: Time) => rule?.toString === true ? value.toString() : value, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Date} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asDate (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isDate(value)) { + throw new TypeError(`${field} should be a Date but received ${typeof value}`) + } + }, + convert: (value: Date) => convertStdDate(value, rule), + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link LocalDateTime} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asLocalDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isLocalDateTime(value)) { + throw new TypeError(`${field} should be a LocalDateTime but received ${typeof value}`) + } + }, + convert: (value: LocalDateTime) => convertStdDate(value, rule), + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link DateTime} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isDateTime(value)) { + throw new TypeError(`${field} should be a DateTime but received ${typeof value}`) + } + }, + convert: (value: DateTime) => convertStdDate(value, rule), + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a List. Optionally taking a rule for hydrating the contained values. + * + * @experimental + * @param {Rule & { apply?: Rule }} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asList (rule?: Rule & { apply?: Rule }): Rule { + return { + validate: (value: any, field: string) => { + if (!Array.isArray(value)) { + throw new TypeError(`${field} should be a list but received ${typeof value}`) + } + }, + convert: (list: any[], field: string) => { + if (rule?.apply != null) { + return list.map((value, index) => valueAs(value, `${field}[${index}]`, rule.apply)) + } + return list + }, + ...rule + } + } +}) + +interface ConvertableToStdDateOrStr { toStandardDate: () => StandardDate, toString: () => string } + +function convertStdDate (value: V, rule?: { toString?: boolean, toStandardDate?: boolean }): string | V | StandardDate { + if (rule != null) { + if (rule.toString === true) { + return value.toString() + } else if (rule.toStandardDate === true) { + return value.toStandardDate() + } + } + return value +} diff --git a/packages/core/src/record.ts b/packages/core/src/record.ts index 0b5dfc374..d8052189c 100644 --- a/packages/core/src/record.ts +++ b/packages/core/src/record.ts @@ -16,6 +16,7 @@ */ import { newError } from './error' +import { Rules, GenericConstructor, as } from './mapping.highlevel' type RecordShape = { [K in Key]: Value @@ -132,6 +133,20 @@ class Record< return resultArray } + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): T + /** + * Maps the record to a provided type and/or according to provided Rules. + * + * @param {GenericConstructor | Rules} constructorOrRules + * @param {Rules} rules + * @returns {T} + */ + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + return as(this, constructorOrRules, rules) + } + /** * Iterate over results. Each iteration will yield an array * of exactly two items - the key, and the value (in order). diff --git a/packages/core/src/result-transformers.ts b/packages/core/src/result-transformers.ts index 1cf22d701..df9a5c8ca 100644 --- a/packages/core/src/result-transformers.ts +++ b/packages/core/src/result-transformers.ts @@ -20,6 +20,7 @@ import Result from './result' import EagerResult from './result-eager' import ResultSummary from './result-summary' import { newError } from './error' +import { GenericConstructor, Rules } from './mapping.highlevel' import { NumberOrInteger } from './graph-types' import Integer from './integer' @@ -266,6 +267,46 @@ class ResultTransformers { summary (): ResultTransformer> { return summary } + + hydrated (rules: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + hydrated (genericConstructor: GenericConstructor, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + /** + * Creates a {@link ResultTransformer} which maps each record of the result to a hydrated object of a provided type and/or according to provided rules. + * + * @example + * + * class Person { + * constructor (name) { + * this.name = name + * } + * + * const personRules: Rules = { + * name: neo4j.RulesFactories.asString() + * } + * + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydrated(Person, personClassRules) + * }) + * + * // Alternatively, the rules can be registered in the mapping registry. + * // This registry exists in global memory and will persist even between driver instances. + * + * neo4j.RecordObjectMapping.register(Person, PersonRules) + * + * // after registering the rule the transformer will follow them when mapping to the provided type + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydrated(Person) + * }) + * + * // A hydrated can be used without providing or registering Rules beforehand, but in such case the mapping will be done without any type validation + * + * @returns {ResultTransformer>} The result transformer + * @see {@link Driver#executeQuery} + * @experimental This is a preview feature + */ + hydrated (constructorOrRules: GenericConstructor | Rules, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> { + return async result => await result.as(constructorOrRules as unknown as GenericConstructor, rules).then() + } } /** diff --git a/packages/core/src/result.ts b/packages/core/src/result.ts index a83a116c7..42d1a1427 100644 --- a/packages/core/src/result.ts +++ b/packages/core/src/result.ts @@ -23,6 +23,7 @@ import { Query, PeekableAsyncIterator } from './types' import { observer, util, connectionHolder } from './internal' import { newError, PROTOCOL_ERROR } from './error' import { NumberOrInteger } from './graph-types' +import { GenericConstructor, Rules } from './mapping.highlevel' import Integer from './integer' const { EMPTY_CONNECTION_HOLDER } = connectionHolder @@ -51,20 +52,28 @@ const DEFAULT_ON_COMPLETED = (summary: ResultSummary): void => {} */ const DEFAULT_ON_KEYS = (keys: string[]): void => {} +interface GenericQueryResult { + records: R[] + summary: ResultSummary +} + /** * The query result is the combination of the {@link ResultSummary} and * the array {@link Record[]} produced by the query */ -interface QueryResult { - records: Array> - summary: ResultSummary -} +interface QueryResult extends GenericQueryResult> {} + +/** + * The query result is the combination of the {@link ResultSummary} and + * an array of mapped objects produced by the query. + */ +interface MappedQueryResult extends GenericQueryResult {} /** * Interface to observe updates on the Result which is being produced. * */ -interface ResultObserver { +interface GenericResultObserver { /** * Receive the keys present on the record whenever this information is available * @@ -76,7 +85,7 @@ interface ResultObserver { * Receive the each record present on the {@link @Result} * @param {Record} record The {@link Record} produced */ - onNext?: (record: Record) => void + onNext?: (record: R) => void /** * Called when the result is fully received @@ -91,29 +100,47 @@ interface ResultObserver { onError?: (error: Error) => void } +interface ResultObserver extends GenericResultObserver> {} + /** * Defines a ResultObserver interface which can be used to enqueue records and dequeue * them until the result is fully received. * @access private */ -interface QueuedResultObserver extends ResultObserver { - dequeue: () => Promise> - dequeueUntilDone: () => Promise> - head: () => Promise> +interface QueuedResultObserver extends GenericResultObserver { + dequeue: () => Promise> + dequeueUntilDone: () => Promise> + head: () => Promise> size: number } +function captureStacktrace (): string | null { + const error = new Error('') + if (error.stack != null) { + return error.stack.replace(/^Error(\n\r)*/, '') // we don't need the 'Error\n' part, if only it exists + } + return null +} + /** - * A stream of {@link Record} representing the result of a query. - * Can be consumed eagerly as {@link Promise} resolved with array of records and {@link ResultSummary} - * summary, or rejected with error that contains {@link string} code and {@link string} message. - * Alternatively can be consumed lazily using {@link Result#subscribe} function. - * @access public + * @private + * @param {Error} error The error + * @param {string| null} newStack The newStack + * @returns {void} */ -class Result implements Promise> { +function replaceStacktrace (error: Error, newStack?: string | null): void { + if (newStack != null) { + // Error.prototype.toString() concatenates error.name and error.message nicely + // then we add the rest of the stack trace + // eslint-disable-next-line @typescript-eslint/no-base-to-string + error.stack = error.toString() + '\n' + newStack + } +} + +class GenericResult> implements Promise { private readonly _stack: string | null private readonly _streamObserverPromise: Promise - private _p: Promise | null + private _p: Promise | null private readonly _query: Query private readonly _parameters: any private readonly _connectionHolder: connectionHolder.ConnectionHolder @@ -121,6 +148,7 @@ class Result implements Promise implements Promise(rules: Rules): MappedResult + as (genericConstructor: GenericConstructor, rules?: Rules): MappedResult + /** + * Maps the records of this result to a provided type and/or according to provided Rules. + * + * NOTE: This modifies the Result object itself, and can not be run on a Result that is already being consumed. + * + * @example + * class Person { + * constructor ( + * public readonly name: string, + * public readonly born?: number + * ) {} + * } + * + * const personRules: Rules = { + * name: RulesFactories.asString(), + * born: RulesFactories.asNumber({ acceptBigInt: true, optional: true }) + * } + * + * await session.executeRead(async (tx: Transaction) => { + * let txres = tx.run(`MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)<-[:ACTED_IN]-(c:Person) + * WHERE id(p) <> id(c) + * RETURN p.name as name, p.born as born`).as(personRules) + * + * @param {GenericConstructor | Rules} constructorOrRules + * @param {Rules} rules + * @returns {MappedResult} + */ + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): MappedResult { + if (this._p != null) { + throw newError('Cannot call .as() on a Result that is being consumed') + } + // @ts-expect-error + this._mapper = r => r.as(constructorOrRules, rules) + // @ts-expect-error + return this + } + /** * Returns a promise for the field keys. * @@ -215,16 +283,20 @@ class Result implements Promise> { + private _getOrCreatePromise (): Promise { if (this._p == null) { this._p = new Promise((resolve, reject) => { - const records: Array> = [] + const records: R[] = [] const observer = { - onNext: (record: Record) => { - records.push(record) + onNext: (record: R) => { + if (this._mapper != null) { + records.push(this._mapper(record) as unknown as R) + } else { + records.push(record as unknown as R) + } }, onCompleted: (summary: ResultSummary) => { - resolve({ records, summary }) + resolve({ records, summary } as unknown as T) }, onError: (error: Error) => { reject(error) @@ -243,9 +315,9 @@ class Result implements Promise, ResultSummary>} The async iterator for the Results + * @returns {PeekableAsyncIterator} The async iterator for the Results */ - [Symbol.asyncIterator] (): PeekableAsyncIterator, ResultSummary> { + [Symbol.asyncIterator] (): PeekableAsyncIterator { if (!this.isOpen()) { const error = newError('Result is already consumed') return { @@ -348,9 +420,9 @@ class Result implements Promise, TResult2 = never>( + then( onFulfilled?: - | ((value: QueryResult) => TResult1 | PromiseLike) + | ((value: T) => TResult1 | PromiseLike) | null, onRejected?: ((reason: any) => TResult2 | PromiseLike) | null ): Promise { @@ -367,7 +439,7 @@ class Result implements Promise( onRejected?: ((reason: any) => TResult | PromiseLike) | null - ): Promise | TResult> { + ): Promise { return this._getOrCreatePromise().catch(onRejected) } @@ -379,7 +451,7 @@ class Result implements Promise void) | null): Promise> { + finally (onfinally?: (() => void) | null): Promise { return this._getOrCreatePromise().finally(onfinally) } @@ -394,7 +466,7 @@ class Result implements Promise): void { + subscribe (observer: GenericResultObserver): void { this._subscribe(observer) .catch(() => {}) } @@ -412,11 +484,11 @@ class Result implements Promise} The result stream observer. */ - _subscribe (observer: ResultObserver, paused: boolean = false): Promise { + _subscribe (observer: GenericResultObserver, paused: boolean = false): Promise { const _observer = this._decorateObserver(observer) return this._streamObserverPromise @@ -442,7 +514,7 @@ class Result implements Promise): GenericResultObserver { const onCompletedOriginal = observer.onCompleted ?? DEFAULT_ON_COMPLETED const onErrorOriginal = observer.onError ?? DEFAULT_ON_ERROR const onKeysOriginal = observer.onKeys ?? DEFAULT_ON_KEYS @@ -537,7 +609,7 @@ class Result implements Promise any | undefined } - function createResolvablePromise (): ResolvablePromise> { + function createResolvablePromise (): ResolvablePromise> { const resolvablePromise: any = {} resolvablePromise.promise = new Promise((resolve, reject) => { resolvablePromise.resolve = resolve @@ -546,13 +618,13 @@ class Result implements Promise | Error + type QueuedResultElementOrError = IteratorResult | Error function isError (elementOrError: QueuedResultElementOrError): elementOrError is Error { return elementOrError instanceof Error } - async function dequeue (): Promise> { + async function dequeue (): Promise> { if (buffer.length > 0) { const element = buffer.shift() ?? newError('Unexpected empty buffer', PROTOCOL_ERROR) onQueueSizeChanged() @@ -567,12 +639,16 @@ class Result implements Promise> | null + resolvable: ResolvablePromise> | null } = { resolvable: null } const observer = { - onNext: (record: Record) => { - observer._push({ done: false, value: record }) + onNext: (record: any) => { + if (this._mapper != null) { + observer._push({ done: false, value: this._mapper(record) }) + } else { + observer._push({ done: false, value: record }) + } }, onCompleted: (summary: ResultSummary) => { observer._push({ done: true, value: summary }) @@ -631,29 +707,27 @@ class Result implements Promise extends GenericResult, QueryResult> { -function captureStacktrace (): string | null { - const error = new Error('') - if (error.stack != null) { - return error.stack.replace(/^Error(\n\r)*/, '') // we don't need the 'Error\n' part, if only it exists - } - return null } /** - * @private - * @param {Error} error The error - * @param {string| null} newStack The newStack - * @returns {void} + * A stream of mapped Objects representing the result of a query as mapped with a Record Object Mapping function. + * Can be consumed eagerly as {@link Promise} resolved with array of records and {@link ResultSummary} + * summary, or rejected with error that contains {@link string} code and {@link string} message. + * Alternatively can be consumed lazily using {@link MappedResult#subscribe} function. + * @access public */ -function replaceStacktrace (error: Error, newStack?: string | null): void { - if (newStack != null) { - // Error.prototype.toString() concatenates error.name and error.message nicely - // then we add the rest of the stack trace - // eslint-disable-next-line @typescript-eslint/no-base-to-string - error.stack = error.toString() + '\n' + newStack - } +class MappedResult extends GenericResult> { + } export default Result -export type { QueryResult, ResultObserver } +export type { MappedQueryResult, QueryResult, ResultObserver, GenericResultObserver } diff --git a/packages/core/test/mapping.highlevel.test.ts b/packages/core/test/mapping.highlevel.test.ts new file mode 100644 index 000000000..ca761e47e --- /dev/null +++ b/packages/core/test/mapping.highlevel.test.ts @@ -0,0 +1,163 @@ +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [https://neo4j.com] + * + * 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. + */ + +import { Date, DateTime, Duration, RecordObjectMapping, Node, Relationship, Rules, RulesFactories, Time } from '../src' +import { as } from '../src/mapping.highlevel' + +describe('#unit Record Object Mapping', () => { + describe('as', () => { + it('should use rules set with register', () => { + class Person { + name + constructor ( + name: String + ) { + this.name = name + } + } + + const personRules: Rules = { + name: RulesFactories.asString({ from: 'firstname' }) + } + + const gettable = { + get: (index: string) => { + if (index === 'firstname') { + return 'hi' + } + if (index === 'name') { + return 'hello' + } + return undefined + } + } + + RecordObjectMapping.register(Person, personRules) + // @ts-expect-error + expect(as(gettable, Person).name).toBe('hi') + RecordObjectMapping.clearMappingRegistry() + // @ts-expect-error + expect(as(gettable, Person).name).toBe('hello') + }) + it('should perform typechecks according to rules', () => { + const personRules: Rules = { + name: RulesFactories.asNumber({ from: 'firstname' }) + } + + const gettable = { + get: (index: string) => { + if (index === 'firstname') { + return 'hi' + } + if (index === 'name') { + return 'hello' + } + return undefined + } + } + // @ts-expect-error + expect(() => as(gettable, personRules)).toThrow('Object#name should be a number but received string') + }) + it('should be able to read all property types', () => { + class Person { + name + constructor ( + name: String + ) { + this.name = name + } + } + + const personRules: Rules = { + name: RulesFactories.asString({ from: 'firstname' }) + } + const rules: Rules = { + number: RulesFactories.asNumber(), + string: RulesFactories.asString(), + bigint: RulesFactories.asBigInt(), + date: RulesFactories.asDate(), + dateTime: RulesFactories.asDateTime(), + duration: RulesFactories.asDuration(), + time: RulesFactories.asTime(), + list: RulesFactories.asList({ apply: RulesFactories.asString() }), + node: RulesFactories.asNode({ convert: (node) => node.as(Person, personRules) }), + rel: RulesFactories.asRelationship({ convert: (rel) => rel.as(Person, personRules) }) + } + + const gettable = { + get: (index: string) => { + switch (index) { + case 'string': + return 'hi' + case 'number': + return 1 + case 'bigint': + return BigInt(1) + case 'date': + return new Date(1, 1, 1) + case 'dateTime': + return new DateTime(1, 1, 1, 1, 1, 1, 1, 1) + case 'duration': + return new Duration(1, 1, 1, 1) + case 'time': + return new Time(1, 1, 1, 1, 1) + case 'list': + return ['hello'] + case 'node': + return new Node(1, [], { firstname: 'hi' }) + case 'rel': + return new Relationship(2, 1, 1, 'test', { firstname: 'bye' }) + default: + return undefined + } + } + } + // @ts-expect-error + const result = as(gettable, rules) + + // @ts-expect-error + expect(result.string).toBe('hi') + + // @ts-expect-error + expect(result.number).toBe(1) + + // @ts-expect-error + expect(result.bigint).toBe(BigInt(1)) + + // @ts-expect-error + expect(result.list[0]).toBe('hello') + + // @ts-expect-error + expect(result.date.toString()).toBe('0001-01-01') + + // @ts-expect-error + expect(result.dateTime.toString()).toBe('0001-01-01T01:01:01.000000001+00:00:01') + + // @ts-expect-error + expect(result.duration.toString()).toBe('P1M1DT1.000000001S') + + // @ts-expect-error + expect(result.time.toString()).toBe('01:01:01.000000001+00:00:01') + + // @ts-expect-error + expect(result.node.name).toBe('hi') + + // @ts-expect-error + expect(result.rel.name).toBe('bye') + }) + }) +}) diff --git a/packages/core/test/mapping.nameconventions.test.ts b/packages/core/test/mapping.nameconventions.test.ts new file mode 100644 index 000000000..1dda301ec --- /dev/null +++ b/packages/core/test/mapping.nameconventions.test.ts @@ -0,0 +1,37 @@ +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [https://neo4j.com] + * + * 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. + */ + +import { RecordObjectMapping } from '../src' + +describe('#unit getCaseTranslator', () => { + // Each convention has "tokenize" and "encode" functions, so testing each twice is sufficient. + it('camelCase to SCREAMING_SNAKE_CASE', () => { + expect(RecordObjectMapping.getCaseTranslator(RecordObjectMapping.StandardCase.CamelCase, 'SCREAMING_SNAKE_CASE')('I_AM_COOL')).toBe('iAmCool') + }) + it('SCREAMING_SNAKE_CASE to PascalCase', () => { + expect(RecordObjectMapping.getCaseTranslator(RecordObjectMapping.StandardCase.ScreamingSnakeCase, 'PascalCase')('IAmCool')).toBe('I_AM_COOL') + }) + it('PascalCase to snake_case', () => { + expect(RecordObjectMapping.getCaseTranslator(RecordObjectMapping.StandardCase.PascalCase, 'snake_case')('i_am_cool')).toBe('IAmCool') + }) + it('snake_case to kebab-case', () => { + expect(RecordObjectMapping.getCaseTranslator(RecordObjectMapping.StandardCase.SnakeCase, 'kebab-case')('i-am-cool')).toBe('i_am_cool') + }) + it('kebab-case to camelCase', () => { + expect(RecordObjectMapping.getCaseTranslator(RecordObjectMapping.StandardCase.KebabCase, 'camelCase')('iAmCool')).toBe('i-am-cool') + }) +}) diff --git a/packages/neo4j-driver-deno/lib/core/graph-types.ts b/packages/neo4j-driver-deno/lib/core/graph-types.ts index 9d754f9e2..15d88d3ef 100644 --- a/packages/neo4j-driver-deno/lib/core/graph-types.ts +++ b/packages/neo4j-driver-deno/lib/core/graph-types.ts @@ -16,6 +16,7 @@ */ import Integer from './integer.ts' import { stringify } from './json.ts' +import { Rules, GenericConstructor, as } from './mapping.highlevel.ts' type StandardDate = Date /** @@ -82,6 +83,22 @@ class Node identity.toString()) } + /** + * Hydrates an object of a given type with the properties of the node + * + * @param {GenericConstructor | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration + * @param {Rules} [rules] {@link Rules} for the hydration + * @returns {T} + */ + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): T + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + return as({ + get: (key) => this.properties[key] + }, constructorOrRules, rules) + } + /** * @ignore */ @@ -199,6 +216,22 @@ class Relationship end.toString()) } + /** + * Hydrates an object of a given type with the properties of the relationship + * + * @param {GenericConstructor | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration + * @param {Rules} [rules] {@link Rules} for the hydration + * @returns {T} + */ + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): T + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + return as({ + get: (key) => this.properties[key] + }, constructorOrRules, rules) + } + /** * @ignore */ @@ -320,6 +353,22 @@ class UnboundRelationship | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration + * @param {Rules} [rules] {@link Rules} for the hydration + * @returns {T} + */ + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): T + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + return as({ + get: (key) => this.properties[key] + }, constructorOrRules, rules) + } + /** * @ignore */ diff --git a/packages/neo4j-driver-deno/lib/core/index.ts b/packages/neo4j-driver-deno/lib/core/index.ts index 1a0a7203f..c758bd33e 100644 --- a/packages/neo4j-driver-deno/lib/core/index.ts +++ b/packages/neo4j-driver-deno/lib/core/index.ts @@ -82,7 +82,7 @@ import NotificationFilter, { notificationFilterMinimumSeverityLevel, NotificationFilterMinimumSeverityLevel } from './notification-filter.ts' -import Result, { QueryResult, ResultObserver } from './result.ts' +import Result, { MappedQueryResult, QueryResult, ResultObserver } from './result.ts' import EagerResult from './result-eager.ts' import ConnectionProvider, { Releasable } from './connection-provider.ts' import Connection from './connection.ts' @@ -101,6 +101,9 @@ import * as json from './json.ts' import resultTransformers, { ResultTransformer } from './result-transformers.ts' import ClientCertificate, { clientCertificateProviders, ClientCertificateProvider, ClientCertificateProviders, RotatingClientCertificateProvider, resolveCertificateProvider } from './client-certificate.ts' import * as internal from './internal/index.ts' +import { StandardCase } from './mapping.nameconventions.ts' +import { Rule, Rules, RecordObjectMapping } from './mapping.highlevel.ts' +import { RulesFactories } from './mapping.rulesfactories.ts' /** * Object containing string constants representing predefined {@link Neo4jError} codes. @@ -186,7 +189,10 @@ const forExport = { notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, clientCertificateProviders, - resolveCertificateProvider + resolveCertificateProvider, + RulesFactories, + RecordObjectMapping, + StandardCase } export { @@ -263,7 +269,10 @@ export { notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, clientCertificateProviders, - resolveCertificateProvider + resolveCertificateProvider, + RulesFactories, + RecordObjectMapping, + StandardCase } export type { @@ -271,6 +280,7 @@ export type { NumberOrInteger, NotificationPosition, QueryResult, + MappedQueryResult, ResultObserver, TransactionConfig, BookmarkManager, @@ -294,7 +304,9 @@ export type { ClientCertificate, ClientCertificateProvider, ClientCertificateProviders, - RotatingClientCertificateProvider + RotatingClientCertificateProvider, + Rule, + Rules } export default forExport diff --git a/packages/neo4j-driver-deno/lib/core/internal/observers.ts b/packages/neo4j-driver-deno/lib/core/internal/observers.ts index cc3223f0a..91a53e206 100644 --- a/packages/neo4j-driver-deno/lib/core/internal/observers.ts +++ b/packages/neo4j-driver-deno/lib/core/internal/observers.ts @@ -16,6 +16,7 @@ */ import Record from '../record.ts' +import { GenericResultObserver } from '../result.ts' import ResultSummary from '../result-summary.ts' interface StreamObserver { @@ -115,7 +116,7 @@ export interface ResultStreamObserver extends StreamObserver { * @param {function(metadata: Object)} observer.onCompleted - Handle stream tail, the summary. * @param {function(error: Object)} observer.onError - Handle errors, should always be provided. */ - subscribe: (observer: ResultObserver) => void + subscribe: (observer: GenericResultObserver) => void } export class CompletedObserver implements ResultStreamObserver { diff --git a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts new file mode 100644 index 000000000..a020f3025 --- /dev/null +++ b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts @@ -0,0 +1,189 @@ +/** + * 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. + */ + +import { newError } from './error.ts' +import { nameConventions, StandardCase } from './mapping.nameconventions.ts' + +/** + * constructor function of any class + */ +export type GenericConstructor = new (...args: any[]) => T + +export interface Rule { + optional?: boolean + from?: string + convert?: (recordValue: any, field: string) => any + validate?: (recordValue: any, field: string) => void +} + +export type Rules = Record + +let rulesRegistry: Record = {} + +let nameMapping: (name: string) => string = (name) => name + +function register (constructor: GenericConstructor, rules: Rules): void { + rulesRegistry[constructor.toString()] = rules +} + +function clearMappingRegistry (): void { + rulesRegistry = {} +} + +function translateIdentifiers (translationFunction: (name: string) => string): void { + nameMapping = translationFunction +} + +function getCaseTranslator (databaseConvention: string | StandardCase, codeConvention: string | StandardCase): ((name: string) => string) { + const keys = Object.keys(nameConventions) + if (!keys.includes(databaseConvention)) { + throw newError( + `Naming convention ${databaseConvention} is not recognized, + please provide a recognized name convention or manually provide a translation function.` + ) + } + if (!keys.includes(codeConvention)) { + throw newError( + `Naming convention ${codeConvention} is not recognized, + please provide a recognized name convention or manually provide a translation function.` + ) + } + // @ts-expect-error + return (name: string) => nameConventions[databaseConvention].encode(nameConventions[codeConvention].tokenize(name)) +} + +export const RecordObjectMapping = Object.freeze({ + /** + * Clears all registered type mappings from the record object mapping registry. + * @experimental + */ + clearMappingRegistry, + /** + * Creates a translation frunction from record key names to object property names, for use with the {@link translateIdentifiers} function + * + * Recognized naming conventions are "camelCase", "PascalCase", "snake_case", "kebab-case", "SCREAMING_SNAKE_CASE" + * + * @experimental + * @param {string} databaseConvention The naming convention in use in database result Records + * @param {string} codeConvention The naming convention in use in JavaScript object properties + * @returns {function} translation function + */ + getCaseTranslator, + /** + * Registers a set of {@link Rules} to be used by {@link hydrated} for the provided class when no other rules are specified. This registry exists in global memory, not the driver instance. + * + * @example + * // The following code: + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydrated(Person, personClassRules) + * }) + * + * can instead be written: + * neo4j.RecordObjectMapping.register(Person, personClassRules) + * + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydrated(Person) + * }) + * + * @experimental + * @param {GenericConstructor} constructor The constructor function of the class to set rules for + * @param {Rules} rules The rules to set for the provided class + */ + register, + /** + * Sets a default name translation from record keys to object properties. + * If providing a function, provide a function that maps FROM your object properties names TO record key names. + * + * The function getCaseTranslator can be used to provide a prewritten translation function between some common naming conventions. + * + * @example + * //if the keys on records from the database are in ALLCAPS + * RecordObjectMapping.translateIdentifiers((name) => name.toUpperCase()) + * + * //if you utilize PacalCase in the database and camelCase in JavaScript code. + * RecordObjectMapping.translateIdentifiers(mapping.getCaseTranslator("PascalCase", "camelCase")) + * + * //if a type has one odd mapping you can override the translation with the rule + * const personRules = { + * firstName: neo4j.RulesFactories.asString(), + * bornAt: neo4j.RulesFactories.asNumber({ acceptBigInt: true, optional: true }) + * weird_name-property: neo4j.RulesFactories.asString({from: 'homeTown'}) + * } + * //These rules can then be used by providing them to a hydratedResultsMapper + * record.as(personRules) + * //or by registering them to the mapping registry + * RecordObjectMapping.register(Person, personRules) + * + * @experimental + * @param {function} translationFunction A function translating the names of your JS object property names to record key names + */ + translateIdentifiers +}) + +interface Gettable { get: (key: string) => V } + +export function as (gettable: Gettable, constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + const GenericConstructor = typeof constructorOrRules === 'function' ? constructorOrRules : Object + const theRules = getRules(constructorOrRules, rules) + const vistedKeys: string[] = [] + + const obj = new GenericConstructor() + + for (const [key, rule] of Object.entries(theRules ?? {})) { + vistedKeys.push(key) + _apply(gettable, obj, key, rule) + } + + for (const key of Object.getOwnPropertyNames(obj)) { + if (!vistedKeys.includes(key)) { + _apply(gettable, obj, key, theRules?.[key]) + } + } + + return obj as unknown as T +} + +function _apply (gettable: Gettable, obj: T, key: string, rule?: Rule): void { + const mappedkey = nameMapping(key) + const value = gettable.get(rule?.from ?? mappedkey) + const field = `${obj.constructor.name}#${key}` + const processedValue = valueAs(value, field, rule) + // @ts-expect-error + obj[key] = processedValue ?? obj[key] +} + +export function valueAs (value: unknown, field: string, rule?: Rule): unknown { + if (rule?.optional === true && value == null) { + return value + } + + if (typeof rule?.validate === 'function') { + rule.validate(value, field) + } + + return ((rule?.convert) != null) ? rule.convert(value, field) : value +} +function getRules (constructorOrRules: Rules | GenericConstructor, rules: Rules | undefined): Rules | undefined { + const rulesDefined = typeof constructorOrRules === 'object' ? constructorOrRules : rules + if (rulesDefined != null) { + return rulesDefined + } + + return typeof constructorOrRules !== 'object' ? rulesRegistry[constructorOrRules.toString()] : undefined +} diff --git a/packages/neo4j-driver-deno/lib/core/mapping.nameconventions.ts b/packages/neo4j-driver-deno/lib/core/mapping.nameconventions.ts new file mode 100644 index 000000000..75b2b00cd --- /dev/null +++ b/packages/neo4j-driver-deno/lib/core/mapping.nameconventions.ts @@ -0,0 +1,70 @@ +/** + * 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. + */ + +export interface NameConvention { + tokenize: (name: string) => string[] + encode: (tokens: string[]) => string +} + +export enum StandardCase { + SnakeCase = 'snake_case', + KebabCase = 'kebab-case', + ScreamingSnakeCase = 'SCREAMING_SNAKE_CASE', + PascalCase = 'PascalCase', + CamelCase = 'camelCase' +} + +export const nameConventions = { + snake_case: { + tokenize: (name: string) => name.split('_'), + encode: (tokens: string[]) => tokens.join('_') + }, + 'kebab-case': { + tokenize: (name: string) => name.split('-'), + encode: (tokens: string[]) => tokens.join('-') + }, + PascalCase: { + tokenize: (name: string) => name.split(/(?=[A-Z])/).map((token) => token.toLowerCase()), + encode: (tokens: string[]) => { + let name: string = '' + for (let token of tokens) { + token = token.charAt(0).toUpperCase() + token.slice(1) + name += token + } + return name + } + }, + camelCase: { + tokenize: (name: string) => name.split(/(?=[A-Z])/).map((token) => token.toLowerCase()), + encode: (tokens: string[]) => { + let name: string = '' + for (let [i, token] of tokens.entries()) { + if (i !== 0) { + token = token.charAt(0).toUpperCase() + token.slice(1) + } + name += token + } + return name + } + }, + SCREAMING_SNAKE_CASE: { + tokenize: (name: string) => name.split('_').map((token) => token.toLowerCase()), + encode: (tokens: string[]) => tokens.join('_').toUpperCase() + } +} diff --git a/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts b/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts new file mode 100644 index 000000000..feafc087d --- /dev/null +++ b/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts @@ -0,0 +1,378 @@ +/** + * 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. + */ + +import { Rule, valueAs } from './mapping.highlevel.ts' +import { StandardDate, isNode, isPath, isRelationship, isUnboundRelationship } from './graph-types.ts' +import { isPoint } from './spatial-types.ts' +import { Date, DateTime, Duration, LocalDateTime, LocalTime, Time, isDate, isDateTime, isDuration, isLocalDateTime, isLocalTime, isTime } from './temporal-types.ts' + +/** + * @property {function(rule: ?Rule)} asString Create a {@link Rule} that validates the value is a String. + * + * @property {function(rule: ?Rule & { acceptBigInt?: boolean })} asNumber Create a {@link Rule} that validates the value is a Number. + * + * @property {function(rule: ?Rule & { acceptNumber?: boolean })} AsBigInt Create a {@link Rule} that validates the value is a BigInt. + * + * @property {function(rule: ?Rule)} asNode Create a {@link Rule} that validates the value is a {@link Node}. + * + * @property {function(rule: ?Rule)} asRelationship Create a {@link Rule} that validates the value is a {@link Relationship}. + * + * @property {function(rule: ?Rule)} asPath Create a {@link Rule} that validates the value is a {@link Path}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asDuration Create a {@link Rule} that validates the value is a {@link Duration}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asLocalTime Create a {@link Rule} that validates the value is a {@link LocalTime}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asLocalDateTime Create a {@link Rule} that validates the value is a {@link LocalDateTime}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asTime Create a {@link Rule} that validates the value is a {@link Time}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asDateTime Create a {@link Rule} that validates the value is a {@link DateTime}. + * + * @property {function(rule: ?Rule & { toString?: boolean })} asDate Create a {@link Rule} that validates the value is a {@link Date}. + * + * @property {function(rule: ?Rule)} asPoint Create a {@link Rule} that validates the value is a {@link Point}. + * + * @property {function(rule: ?Rule & { apply?: Rule })} asList Create a {@link Rule} that validates the value is a List. + * + * @experimental + */ +export const RulesFactories = Object.freeze({ + /** + * Create a {@link Rule} that validates the value is a Boolean. + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asBoolean (rule?: Rule): Rule { + return { + validate: (value, field) => { + if (typeof value !== 'boolean') { + throw new TypeError(`${field} should be a boolean but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a String. + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asString (rule?: Rule): Rule { + return { + validate: (value, field) => { + if (typeof value !== 'string') { + throw new TypeError(`${field} should be a string but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Number}. + * + * @experimental + * @param {Rule & { acceptBigInt?: boolean }} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asNumber (rule?: Rule & { acceptBigInt?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (typeof value === 'object' && value.low !== undefined && value.high !== undefined && Object.keys(value).length === 2) { + throw new TypeError('Number returned as Object. To use asNumber mapping, set disableLosslessIntegers or useBigInt in driver config object') + } + if (typeof value !== 'number' && (rule?.acceptBigInt !== true || typeof value !== 'bigint')) { + throw new TypeError(`${field} should be a number but received ${typeof value}`) + } + }, + convert: (value: number | bigint) => { + if (typeof value === 'bigint') { + return Number(value) + } + return value + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link BigInt}. + * + * @experimental + * @param {Rule & { acceptNumber?: boolean }} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asBigInt (rule?: Rule & { acceptNumber?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (typeof value !== 'bigint' && (rule?.acceptNumber !== true || typeof value !== 'number')) { + throw new TypeError(`${field} should be a bigint but received ${typeof value}`) + } + }, + convert: (value: number | bigint) => { + if (typeof value === 'number') { + return BigInt(value) + } + return value + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Node}. + * + * @example + * const actingJobsRules: Rules = { + * // Converts the person node to a Person object in accordance with provided rules + * person: neo4j.RulesFactories.asNode({ + * convert: (node: Node) => node.as(Person, personRules) + * }), + * // Returns the movie node as a Node + * movie: neo4j.RulesFactories.asNode({}), + * } + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asNode (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isNode(value)) { + throw new TypeError(`${field} should be a Node but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Relationship}. + * + * @param {Rule} rule Configurations for the rule. + * @returns {Rule} A new rule for the value + */ + asRelationship (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isRelationship(value)) { + throw new TypeError(`${field} should be a Relationship but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is an {@link UnboundRelationship} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asUnboundRelationship (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isUnboundRelationship(value)) { + throw new TypeError(`${field} should be a UnboundRelationship but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Path} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asPath (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isPath(value)) { + throw new TypeError(`${field} should be a Path but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Point} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asPoint (rule?: Rule): Rule { + return { + validate: (value: any, field: string) => { + if (!isPoint(value)) { + throw new TypeError(`${field} should be a Point but received ${typeof value}`) + } + }, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Duration} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asDuration (rule?: Rule & { toString?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isDuration(value)) { + throw new TypeError(`${field} should be a Duration but received ${typeof value}`) + } + }, + convert: (value: Duration) => rule?.toString === true ? value.toString() : value, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link LocalTime} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asLocalTime (rule?: Rule & { toString?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isLocalTime(value)) { + throw new TypeError(`${field} should be a LocalTime but received ${typeof value}`) + } + }, + convert: (value: LocalTime) => rule?.toString === true ? value.toString() : value, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Time} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asTime (rule?: Rule & { toString?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isTime(value)) { + throw new TypeError(`${field} should be a Time but received ${typeof value}`) + } + }, + convert: (value: Time) => rule?.toString === true ? value.toString() : value, + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link Date} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asDate (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isDate(value)) { + throw new TypeError(`${field} should be a Date but received ${typeof value}`) + } + }, + convert: (value: Date) => convertStdDate(value, rule), + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link LocalDateTime} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asLocalDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isLocalDateTime(value)) { + throw new TypeError(`${field} should be a LocalDateTime but received ${typeof value}`) + } + }, + convert: (value: LocalDateTime) => convertStdDate(value, rule), + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a {@link DateTime} + * + * @experimental + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }): Rule { + return { + validate: (value: any, field: string) => { + if (!isDateTime(value)) { + throw new TypeError(`${field} should be a DateTime but received ${typeof value}`) + } + }, + convert: (value: DateTime) => convertStdDate(value, rule), + ...rule + } + }, + /** + * Create a {@link Rule} that validates the value is a List. Optionally taking a rule for hydrating the contained values. + * + * @experimental + * @param {Rule & { apply?: Rule }} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ + asList (rule?: Rule & { apply?: Rule }): Rule { + return { + validate: (value: any, field: string) => { + if (!Array.isArray(value)) { + throw new TypeError(`${field} should be a list but received ${typeof value}`) + } + }, + convert: (list: any[], field: string) => { + if (rule?.apply != null) { + return list.map((value, index) => valueAs(value, `${field}[${index}]`, rule.apply)) + } + return list + }, + ...rule + } + } +}) + +interface ConvertableToStdDateOrStr { toStandardDate: () => StandardDate, toString: () => string } + +function convertStdDate (value: V, rule?: { toString?: boolean, toStandardDate?: boolean }): string | V | StandardDate { + if (rule != null) { + if (rule.toString === true) { + return value.toString() + } else if (rule.toStandardDate === true) { + return value.toStandardDate() + } + } + return value +} diff --git a/packages/neo4j-driver-deno/lib/core/record.ts b/packages/neo4j-driver-deno/lib/core/record.ts index f71b09731..9b669c042 100644 --- a/packages/neo4j-driver-deno/lib/core/record.ts +++ b/packages/neo4j-driver-deno/lib/core/record.ts @@ -16,6 +16,7 @@ */ import { newError } from './error.ts' +import { Rules, GenericConstructor, as } from './mapping.highlevel.ts' type RecordShape = { [K in Key]: Value @@ -132,6 +133,20 @@ class Record< return resultArray } + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): T + /** + * Maps the record to a provided type and/or according to provided Rules. + * + * @param {GenericConstructor | Rules} constructorOrRules + * @param {Rules} rules + * @returns {T} + */ + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { + return as(this, constructorOrRules, rules) + } + /** * Iterate over results. Each iteration will yield an array * of exactly two items - the key, and the value (in order). diff --git a/packages/neo4j-driver-deno/lib/core/result-transformers.ts b/packages/neo4j-driver-deno/lib/core/result-transformers.ts index f48e160ce..32dc6d1c2 100644 --- a/packages/neo4j-driver-deno/lib/core/result-transformers.ts +++ b/packages/neo4j-driver-deno/lib/core/result-transformers.ts @@ -20,6 +20,7 @@ import Result from './result.ts' import EagerResult from './result-eager.ts' import ResultSummary from './result-summary.ts' import { newError } from './error.ts' +import { GenericConstructor, Rules } from './mapping.highlevel.ts' import { NumberOrInteger } from './graph-types.ts' import Integer from './integer.ts' @@ -266,6 +267,46 @@ class ResultTransformers { summary (): ResultTransformer> { return summary } + + hydrated (rules: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + hydrated (genericConstructor: GenericConstructor, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + /** + * Creates a {@link ResultTransformer} which maps each record of the result to a hydrated object of a provided type and/or according to provided rules. + * + * @example + * + * class Person { + * constructor (name) { + * this.name = name + * } + * + * const personRules: Rules = { + * name: neo4j.RulesFactories.asString() + * } + * + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydrated(Person, personClassRules) + * }) + * + * // Alternatively, the rules can be registered in the mapping registry. + * // This registry exists in global memory and will persist even between driver instances. + * + * neo4j.RecordObjectMapping.register(Person, PersonRules) + * + * // after registering the rule the transformer will follow them when mapping to the provided type + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydrated(Person) + * }) + * + * // A hydrated can be used without providing or registering Rules beforehand, but in such case the mapping will be done without any type validation + * + * @returns {ResultTransformer>} The result transformer + * @see {@link Driver#executeQuery} + * @experimental This is a preview feature + */ + hydrated (constructorOrRules: GenericConstructor | Rules, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> { + return async result => await result.as(constructorOrRules as unknown as GenericConstructor, rules).then() + } } /** diff --git a/packages/neo4j-driver-deno/lib/core/result.ts b/packages/neo4j-driver-deno/lib/core/result.ts index 901d70e2c..635b6df2c 100644 --- a/packages/neo4j-driver-deno/lib/core/result.ts +++ b/packages/neo4j-driver-deno/lib/core/result.ts @@ -23,6 +23,7 @@ import { Query, PeekableAsyncIterator } from './types.ts' import { observer, util, connectionHolder } from './internal/index.ts' import { newError, PROTOCOL_ERROR } from './error.ts' import { NumberOrInteger } from './graph-types.ts' +import { GenericConstructor, Rules } from './mapping.highlevel.ts' import Integer from './integer.ts' const { EMPTY_CONNECTION_HOLDER } = connectionHolder @@ -51,20 +52,28 @@ const DEFAULT_ON_COMPLETED = (summary: ResultSummary): void => {} */ const DEFAULT_ON_KEYS = (keys: string[]): void => {} +interface GenericQueryResult { + records: R[] + summary: ResultSummary +} + /** * The query result is the combination of the {@link ResultSummary} and * the array {@link Record[]} produced by the query */ -interface QueryResult { - records: Array> - summary: ResultSummary -} +interface QueryResult extends GenericQueryResult> {} + +/** + * The query result is the combination of the {@link ResultSummary} and + * an array of mapped objects produced by the query. + */ +interface MappedQueryResult extends GenericQueryResult {} /** * Interface to observe updates on the Result which is being produced. * */ -interface ResultObserver { +interface GenericResultObserver { /** * Receive the keys present on the record whenever this information is available * @@ -76,7 +85,7 @@ interface ResultObserver { * Receive the each record present on the {@link @Result} * @param {Record} record The {@link Record} produced */ - onNext?: (record: Record) => void + onNext?: (record: R) => void /** * Called when the result is fully received @@ -91,29 +100,47 @@ interface ResultObserver { onError?: (error: Error) => void } +interface ResultObserver extends GenericResultObserver> {} + /** * Defines a ResultObserver interface which can be used to enqueue records and dequeue * them until the result is fully received. * @access private */ -interface QueuedResultObserver extends ResultObserver { - dequeue: () => Promise> - dequeueUntilDone: () => Promise> - head: () => Promise> +interface QueuedResultObserver extends GenericResultObserver { + dequeue: () => Promise> + dequeueUntilDone: () => Promise> + head: () => Promise> size: number } +function captureStacktrace (): string | null { + const error = new Error('') + if (error.stack != null) { + return error.stack.replace(/^Error(\n\r)*/, '') // we don't need the 'Error\n' part, if only it exists + } + return null +} + /** - * A stream of {@link Record} representing the result of a query. - * Can be consumed eagerly as {@link Promise} resolved with array of records and {@link ResultSummary} - * summary, or rejected with error that contains {@link string} code and {@link string} message. - * Alternatively can be consumed lazily using {@link Result#subscribe} function. - * @access public + * @private + * @param {Error} error The error + * @param {string| null} newStack The newStack + * @returns {void} */ -class Result implements Promise> { +function replaceStacktrace (error: Error, newStack?: string | null): void { + if (newStack != null) { + // Error.prototype.toString() concatenates error.name and error.message nicely + // then we add the rest of the stack trace + // eslint-disable-next-line @typescript-eslint/no-base-to-string + error.stack = error.toString() + '\n' + newStack + } +} + +class GenericResult> implements Promise { private readonly _stack: string | null private readonly _streamObserverPromise: Promise - private _p: Promise | null + private _p: Promise | null private readonly _query: Query private readonly _parameters: any private readonly _connectionHolder: connectionHolder.ConnectionHolder @@ -121,6 +148,7 @@ class Result implements Promise implements Promise(rules: Rules): MappedResult + as (genericConstructor: GenericConstructor, rules?: Rules): MappedResult + /** + * Maps the records of this result to a provided type and/or according to provided Rules. + * + * NOTE: This modifies the Result object itself, and can not be run on a Result that is already being consumed. + * + * @example + * class Person { + * constructor ( + * public readonly name: string, + * public readonly born?: number + * ) {} + * } + * + * const personRules: Rules = { + * name: RulesFactories.asString(), + * born: RulesFactories.asNumber({ acceptBigInt: true, optional: true }) + * } + * + * await session.executeRead(async (tx: Transaction) => { + * let txres = tx.run(`MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)<-[:ACTED_IN]-(c:Person) + * WHERE id(p) <> id(c) + * RETURN p.name as name, p.born as born`).as(personRules) + * + * @param {GenericConstructor | Rules} constructorOrRules + * @param {Rules} rules + * @returns {MappedResult} + */ + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): MappedResult { + if (this._p != null) { + throw newError('Cannot call .as() on a Result that is being consumed') + } + // @ts-expect-error + this._mapper = r => r.as(constructorOrRules, rules) + // @ts-expect-error + return this + } + /** * Returns a promise for the field keys. * @@ -215,16 +283,20 @@ class Result implements Promise> { + private _getOrCreatePromise (): Promise { if (this._p == null) { this._p = new Promise((resolve, reject) => { - const records: Array> = [] + const records: R[] = [] const observer = { - onNext: (record: Record) => { - records.push(record) + onNext: (record: R) => { + if (this._mapper != null) { + records.push(this._mapper(record) as unknown as R) + } else { + records.push(record as unknown as R) + } }, onCompleted: (summary: ResultSummary) => { - resolve({ records, summary }) + resolve({ records, summary } as unknown as T) }, onError: (error: Error) => { reject(error) @@ -243,9 +315,9 @@ class Result implements Promise, ResultSummary>} The async iterator for the Results + * @returns {PeekableAsyncIterator} The async iterator for the Results */ - [Symbol.asyncIterator] (): PeekableAsyncIterator, ResultSummary> { + [Symbol.asyncIterator] (): PeekableAsyncIterator { if (!this.isOpen()) { const error = newError('Result is already consumed') return { @@ -348,9 +420,9 @@ class Result implements Promise, TResult2 = never>( + then( onFulfilled?: - | ((value: QueryResult) => TResult1 | PromiseLike) + | ((value: T) => TResult1 | PromiseLike) | null, onRejected?: ((reason: any) => TResult2 | PromiseLike) | null ): Promise { @@ -367,7 +439,7 @@ class Result implements Promise( onRejected?: ((reason: any) => TResult | PromiseLike) | null - ): Promise | TResult> { + ): Promise { return this._getOrCreatePromise().catch(onRejected) } @@ -379,7 +451,7 @@ class Result implements Promise void) | null): Promise> { + finally (onfinally?: (() => void) | null): Promise { return this._getOrCreatePromise().finally(onfinally) } @@ -394,7 +466,7 @@ class Result implements Promise): void { + subscribe (observer: GenericResultObserver): void { this._subscribe(observer) .catch(() => {}) } @@ -412,11 +484,11 @@ class Result implements Promise} The result stream observer. */ - _subscribe (observer: ResultObserver, paused: boolean = false): Promise { + _subscribe (observer: GenericResultObserver, paused: boolean = false): Promise { const _observer = this._decorateObserver(observer) return this._streamObserverPromise @@ -442,7 +514,7 @@ class Result implements Promise): GenericResultObserver { const onCompletedOriginal = observer.onCompleted ?? DEFAULT_ON_COMPLETED const onErrorOriginal = observer.onError ?? DEFAULT_ON_ERROR const onKeysOriginal = observer.onKeys ?? DEFAULT_ON_KEYS @@ -537,7 +609,7 @@ class Result implements Promise any | undefined } - function createResolvablePromise (): ResolvablePromise> { + function createResolvablePromise (): ResolvablePromise> { const resolvablePromise: any = {} resolvablePromise.promise = new Promise((resolve, reject) => { resolvablePromise.resolve = resolve @@ -546,13 +618,13 @@ class Result implements Promise | Error + type QueuedResultElementOrError = IteratorResult | Error function isError (elementOrError: QueuedResultElementOrError): elementOrError is Error { return elementOrError instanceof Error } - async function dequeue (): Promise> { + async function dequeue (): Promise> { if (buffer.length > 0) { const element = buffer.shift() ?? newError('Unexpected empty buffer', PROTOCOL_ERROR) onQueueSizeChanged() @@ -567,12 +639,16 @@ class Result implements Promise> | null + resolvable: ResolvablePromise> | null } = { resolvable: null } const observer = { - onNext: (record: Record) => { - observer._push({ done: false, value: record }) + onNext: (record: any) => { + if (this._mapper != null) { + observer._push({ done: false, value: this._mapper(record) }) + } else { + observer._push({ done: false, value: record }) + } }, onCompleted: (summary: ResultSummary) => { observer._push({ done: true, value: summary }) @@ -631,29 +707,27 @@ class Result implements Promise extends GenericResult, QueryResult> { -function captureStacktrace (): string | null { - const error = new Error('') - if (error.stack != null) { - return error.stack.replace(/^Error(\n\r)*/, '') // we don't need the 'Error\n' part, if only it exists - } - return null } /** - * @private - * @param {Error} error The error - * @param {string| null} newStack The newStack - * @returns {void} + * A stream of mapped Objects representing the result of a query as mapped with a Record Object Mapping function. + * Can be consumed eagerly as {@link Promise} resolved with array of records and {@link ResultSummary} + * summary, or rejected with error that contains {@link string} code and {@link string} message. + * Alternatively can be consumed lazily using {@link MappedResult#subscribe} function. + * @access public */ -function replaceStacktrace (error: Error, newStack?: string | null): void { - if (newStack != null) { - // Error.prototype.toString() concatenates error.name and error.message nicely - // then we add the rest of the stack trace - // eslint-disable-next-line @typescript-eslint/no-base-to-string - error.stack = error.toString() + '\n' + newStack - } +class MappedResult extends GenericResult> { + } export default Result -export type { QueryResult, ResultObserver } +export type { MappedQueryResult, QueryResult, ResultObserver, GenericResultObserver } diff --git a/packages/neo4j-driver-deno/lib/mod.ts b/packages/neo4j-driver-deno/lib/mod.ts index 41f775d59..2a3727fc0 100644 --- a/packages/neo4j-driver-deno/lib/mod.ts +++ b/packages/neo4j-driver-deno/lib/mod.ts @@ -108,7 +108,13 @@ import { ClientCertificateProviders, RotatingClientCertificateProvider, clientCertificateProviders, - resolveCertificateProvider + resolveCertificateProvider, + Rule, + Rules, + RulesFactories, + RecordObjectMapping, + StandardCase, + MappedQueryResult } from './core/index.ts' // @deno-types=./bolt-connection/types/index.d.ts import { DirectConnectionProvider, RoutingConnectionProvider } from './bolt-connection/index.js' @@ -207,7 +213,7 @@ function driver ( routing = true break default: - throw new Error(`Unknown scheme: ${parsedUrl.scheme ?? 'null'}`) + throw new Error(`Unknown scheme: ${(parsedUrl.scheme as string) ?? 'null'}`) } // Encryption enabled on URL, propagate trust to the config. @@ -259,7 +265,7 @@ function driver ( routingContext: parsedUrl.query }) } else { - if (!isEmptyObjectOrNull(parsedUrl.query)) { + if (!(isEmptyObjectOrNull(parsedUrl.query) === true)) { throw new Error( `Parameters are not supported with none routed scheme. Given URL: '${url}'` ) @@ -440,7 +446,10 @@ const forExport = { notificationFilterDisabledCategory, notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, - clientCertificateProviders + clientCertificateProviders, + RulesFactories, + RecordObjectMapping, + StandardCase } export { @@ -511,7 +520,10 @@ export { notificationFilterDisabledCategory, notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, - clientCertificateProviders + clientCertificateProviders, + RulesFactories, + RecordObjectMapping, + StandardCase } export type { QueryResult, @@ -542,6 +554,9 @@ export type { ClientCertificate, ClientCertificateProvider, ClientCertificateProviders, - RotatingClientCertificateProvider + RotatingClientCertificateProvider, + Rule, + Rules, + MappedQueryResult } export default forExport diff --git a/packages/neo4j-driver-lite/src/index.ts b/packages/neo4j-driver-lite/src/index.ts index 2e078aa48..2bb01a76d 100644 --- a/packages/neo4j-driver-lite/src/index.ts +++ b/packages/neo4j-driver-lite/src/index.ts @@ -108,7 +108,13 @@ import { ClientCertificateProviders, RotatingClientCertificateProvider, clientCertificateProviders, - resolveCertificateProvider + resolveCertificateProvider, + Rule, + Rules, + RulesFactories, + RecordObjectMapping, + StandardCase, + MappedQueryResult } from 'neo4j-driver-core' import { DirectConnectionProvider, RoutingConnectionProvider } from 'neo4j-driver-bolt-connection' @@ -206,7 +212,7 @@ function driver ( routing = true break default: - throw new Error(`Unknown scheme: ${parsedUrl.scheme ?? 'null'}`) + throw new Error(`Unknown scheme: ${(parsedUrl.scheme as string) ?? 'null'}`) } // Encryption enabled on URL, propagate trust to the config. @@ -258,7 +264,7 @@ function driver ( routingContext: parsedUrl.query }) } else { - if (!isEmptyObjectOrNull(parsedUrl.query)) { + if (!(isEmptyObjectOrNull(parsedUrl.query) === true)) { throw new Error( `Parameters are not supported with none routed scheme. Given URL: '${url}'` ) @@ -439,7 +445,10 @@ const forExport = { notificationFilterDisabledCategory, notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, - clientCertificateProviders + clientCertificateProviders, + RulesFactories, + RecordObjectMapping, + StandardCase } export { @@ -510,7 +519,10 @@ export { notificationFilterDisabledCategory, notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, - clientCertificateProviders + clientCertificateProviders, + RulesFactories, + RecordObjectMapping, + StandardCase } export type { QueryResult, @@ -541,6 +553,9 @@ export type { ClientCertificate, ClientCertificateProvider, ClientCertificateProviders, - RotatingClientCertificateProvider + RotatingClientCertificateProvider, + Rule, + Rules, + MappedQueryResult } export default forExport diff --git a/packages/neo4j-driver/src/index.js b/packages/neo4j-driver/src/index.js index 911ad9fcd..2a0f1045f 100644 --- a/packages/neo4j-driver/src/index.js +++ b/packages/neo4j-driver/src/index.js @@ -78,7 +78,12 @@ import { notificationFilterMinimumSeverityLevel, staticAuthTokenManager, clientCertificateProviders, - resolveCertificateProvider + resolveCertificateProvider, + Rule, + Rules, + RulesFactories, + RecordObjectMapping, + StandardCase } from 'neo4j-driver-core' import { DirectConnectionProvider, @@ -282,7 +287,9 @@ const types = { LocalDateTime, LocalTime, Time, - Integer + Integer, + Rule, + Rules } /** @@ -402,7 +409,10 @@ const forExport = { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - clientCertificateProviders + clientCertificateProviders, + RulesFactories, + RecordObjectMapping, + StandardCase } export { @@ -474,6 +484,11 @@ export { notificationFilterDisabledCategory, notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, - clientCertificateProviders + clientCertificateProviders, + Rule, + Rules, + RulesFactories, + RecordObjectMapping, + StandardCase } export default forExport diff --git a/packages/neo4j-driver/test/examples.test.js b/packages/neo4j-driver/test/examples.test.js index d282e54ca..6ef9e4d54 100644 --- a/packages/neo4j-driver/test/examples.test.js +++ b/packages/neo4j-driver/test/examples.test.js @@ -1564,6 +1564,154 @@ describe('#integration examples', () => { }) }) + describe('Record Object Mapping', () => { + it('Record mapping', async () => { + const driver = neo4j.driver(uri, sharedNeo4j.authToken, { disableLosslessIntegers: true }) + + // Setting up the contents of the database for the test. + await driver.executeQuery( + `MERGE (p1:Person {name: $name1, born: $born1}) + MERGE (p2:Person {name: $name2, born: $born2}) + MERGE (m:Movie {title: $title, release: $release, tagline: $tagline}) + MERGE (p1)-[:ACTED_IN {characterName: $char1}]->(m) + MERGE (p2)-[:ACTED_IN {characterName: $char2}]->(m) + `, { + name1: 'Max', + born1: 2024, + name2: 'TBD', + born2: 2030, + release: 2015, + title: 'Neo4j JavaScript Driver', + tagline: 'The best driver for the best database!', + char1: 'current dev', + char2: 'next dev' + }) + + // A few dummy classes for the test. + class ActingJobs { + constructor ( + Person, + Movie, + Costars + ) { + this.Person = Person + this.Movie = Movie + this.Costars = Costars + } + } + + class Movie { + constructor ( + Title, + Released, + Tagline + ) { + this.Title = Title + this.Released = Released + this.Tagline = Tagline + } + } + + class Person { + constructor ( + Name, + Born + ) { + this.Name = Name + this.Born = Born + } + } + + class Role { + constructor ( + Name + ) { + this.Name = Name + } + } + + // Create rules for the hydration of the created types + const personRules = { + Name: neo4j.RulesFactories.asString(), + Born: neo4j.RulesFactories.asNumber({ acceptBigInt: true, optional: true }) + } + + const movieRules = { + Title: neo4j.RulesFactories.asString(), + Released: neo4j.RulesFactories.asNumber({ acceptBigInt: true, optional: true, from: 'release' }), + Tagline: neo4j.RulesFactories.asString({ optional: true }) + } + + const roleRules = { + Name: neo4j.RulesFactories.asString({ from: 'characterName' }) + } + + const actingJobsRules = { + // The following rule unpacks the person node from the result into a Person object. + // The rules for the types don't need to be provided as we will be registering the rules for Person, Role and Movie in the mapping registry + Person: neo4j.RulesFactories.asNode({ + convert: (node) => node.as(Person) + }), + Role: neo4j.RulesFactories.asRelationship({ + convert: (rel) => rel.as(Role) + }), + Movie: neo4j.RulesFactories.asNode({ + convert: (node) => node.as(Movie) + }), + Costars: neo4j.RulesFactories.asList({ + apply: neo4j.RulesFactories.asNode({ + convert: (node) => node.as(Person) + }) + }) + } + + // Register the rules for the custom types in the mapping registry. + // This is optional, but not doing it means that rules must be provided for every conversion. + neo4j.RecordObjectMapping.register(Role, roleRules) + neo4j.RecordObjectMapping.register(Person, personRules) + neo4j.RecordObjectMapping.register(Movie, movieRules) + neo4j.RecordObjectMapping.register(ActingJobs, actingJobsRules) + + // The code uses PascalCase for property names, while the cypher has camelCase. This issue can be solved with the following line. + neo4j.RecordObjectMapping.translateIdentifiers(neo4j.RecordObjectMapping.getCaseTranslator('camelCase', 'PascalCase')) + + const session = driver.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + `MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)<-[:ACTED_IN]-(c:Person) + WHERE id(p) <> id(c) AND p.name = "Max" + RETURN p AS person, r as role, m AS movie, COLLECT(c) AS costars` + ) + return txres.as(ActingJobs) + }) + + expect(res.records[0].Person.Born).toBe(2024) + expect(res.records[0].Role.Name).toBe('current dev') + expect(res.records[0].Costars[0].Name).toBe('TBD') + + session.close() + + // alternatively, conversions can be performed with hydrated + const executeQueryRes = await driver.executeQuery( + `MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)<-[:ACTED_IN]-(c:Person) + WHERE id(p) <> id(c) AND p.name = "Max" + RETURN p AS person, r as role, m AS movie, COLLECT(c) AS costars`, + {}, + { resultTransformer: neo4j.resultTransformers.hydrated(ActingJobs) } + ) + + expect(executeQueryRes.records[0].Person.Born).toBe(2024) + expect(executeQueryRes.records[0].Role.Name).toBe('current dev') + expect(executeQueryRes.records[0].Costars[0].Name).toBe('TBD') + + // The following line removes all rules from the mapping registry, this is run here just to not interfere with other tests. + neo4j.RecordObjectMapping.clearMappingRegistry() + + driver.close() + }) + }) + it('should control flow by resume and pause the stream', async () => { const driver = driverGlobal const callCostlyApi = async () => {} diff --git a/packages/neo4j-driver/test/record-object-mapping.test.js b/packages/neo4j-driver/test/record-object-mapping.test.js new file mode 100644 index 000000000..ac12e22b5 --- /dev/null +++ b/packages/neo4j-driver/test/record-object-mapping.test.js @@ -0,0 +1,303 @@ +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [https://neo4j.com] + * + * 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. + */ + +import neo4j, { Date, Duration, Time, Point, DateTime, LocalDateTime, LocalTime } from '../src' +import sharedNeo4j from './internal/shared-neo4j' + +describe('#integration record object mapping', () => { + let driverGlobal + + class ActingJobs { + person + movie + } + class Movie { + title + released + tagline + } + + class Person { + name + born + } + + class Role { + name + } + + // Create rules for the hydration of the created types + const personRules = { + name: neo4j.RulesFactories.asString(), + born: neo4j.RulesFactories.asNumber({ acceptBigInt: true, optional: true }) + } + + const movieRules = { + title: neo4j.RulesFactories.asString(), + released: neo4j.RulesFactories.asNumber({ acceptBigInt: true, optional: true, from: 'release' }), + tagline: neo4j.RulesFactories.asString({ optional: true }) + } + + const roleRules = { + name: neo4j.RulesFactories.asString({ from: 'characterName' }) + } + + const actingJobsRules = { + person: neo4j.RulesFactories.asNode({ + convert: (node) => node.as(Person) + }), + role: neo4j.RulesFactories.asRelationship({ + convert: (rel) => rel.as(Role) + }), + movie: neo4j.RulesFactories.asNode({ + convert: (node) => node.as(Movie) + }), + costars: neo4j.RulesFactories.asList({ + apply: neo4j.RulesFactories.asNode({ + convert: (node) => node.as(Person) + }) + }) + } + + const actingJobsNestedRules = { + person: neo4j.RulesFactories.asNode({ + convert: (node) => node.as(Person, personRules) + }), + role: neo4j.RulesFactories.asRelationship({ + convert: (rel) => rel.as(Role, roleRules) + }), + movie: neo4j.RulesFactories.asNode({ + convert: (node) => node.as(Movie, movieRules) + }), + costars: neo4j.RulesFactories.asList({ + apply: neo4j.RulesFactories.asNode({ + convert: (node) => node.as(Person, personRules) + }) + }) + } + const uri = `bolt://${sharedNeo4j.hostnameWithBoltPort}` + + beforeAll(() => { + driverGlobal = neo4j.driver(uri, sharedNeo4j.authToken, { disableLosslessIntegers: true }) + }) + + afterAll(async () => { + await driverGlobal.close() + }) + + it('map transaction result with registered mappings', async () => { + await driverGlobal.executeQuery( + `MERGE (p1:Person {name: $name1, born: $born1}) + MERGE (p2:Person {name: $name2, born: $born2}) + MERGE (m:Movie {title: $title, release: 2015, tagline: $tagline}) + MERGE (p1)-[:ACTED_IN {characterName: $char1}]->(m) + MERGE (p2)-[:ACTED_IN {characterName: $char2}]->(m) + `, { + name1: 'Max', + born1: 2024, + name2: 'TBD', + born2: 2030, + title: 'Neo4j JavaScript Driver', + tagline: 'The best driver for the best database!', + char1: 'current dev', + char2: 'next dev' + }) + + neo4j.RecordObjectMapping.register(Role, roleRules) + neo4j.RecordObjectMapping.register(Person, personRules) + neo4j.RecordObjectMapping.register(Movie, movieRules) + neo4j.RecordObjectMapping.register(ActingJobs, actingJobsRules) + const session = driverGlobal.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + `MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)<-[:ACTED_IN]-(c:Person) + WHERE id(p) <> id(c) AND p.name = "Max" + RETURN p AS person, r as role, m AS movie, COLLECT(c) AS costars` + ) + return txres.as(ActingJobs) + }) + + expect(res.records[0].person.born).toBe(2024) + expect(res.records[0].role.name).toBe('current dev') + expect(res.records[0].costars[0].name).toBe('TBD') + + session.close() + + neo4j.RecordObjectMapping.clearMappingRegistry() + }) + + it('map transaction result with registered mappings', async () => { + await driverGlobal.executeQuery( + `MERGE (p1:Person {name: $name1, born: $born1}) + MERGE (p2:Person {name: $name2, born: $born2}) + MERGE (m:Movie {title: $title, release: 2015, tagline: $tagline}) + MERGE (p1)-[:ACTED_IN {characterName: $char1}]->(m) + MERGE (p2)-[:ACTED_IN {characterName: $char2}]->(m) + `, { + name1: 'Max', + born1: 2024, + name2: 'TBD', + born2: 2030, + title: 'Neo4j JavaScript Driver', + tagline: 'The best driver for the best database!', + char1: 'current dev', + char2: 'next dev' + }) + + const session = driverGlobal.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + `MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)<-[:ACTED_IN]-(c:Person) + WHERE id(p) <> id(c) AND p.name = "Max" + RETURN p AS person, r as role, m AS movie, COLLECT(c) AS costars` + ) + return txres.as(ActingJobs, actingJobsNestedRules) + }) + + expect(res.records[0].person.born).toBe(2024) + expect(res.records[0].role.name).toBe('current dev') + expect(res.records[0].costars[0].name).toBe('TBD') + + session.close() + }) + + it('map duration', async () => { + const session = driverGlobal.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + 'RETURN $obj as obj', + { + obj: new Duration(1, 1, 1, 1) + } + ) + return txres.as({ obj: neo4j.RulesFactories.asDuration() }) + }) + expect(res.records[0].obj.months).toBe(1) + + session.close() + }) + + it('map local time', async () => { + const session = driverGlobal.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + 'RETURN $obj as obj', + { + obj: new LocalTime(1, 1, 1, 1) + } + ) + return txres.as({ obj: neo4j.RulesFactories.asLocalTime() }) + }) + expect(res.records[0].obj.hour).toBe(1) + + session.close() + }) + + it('map time', async () => { + const session = driverGlobal.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + 'RETURN $obj as obj', + { + obj: new Time(1, 1, 1, 1, 42) + } + ) + return txres.as({ obj: neo4j.RulesFactories.asTime() }) + }) + expect(res.records[0].obj.hour).toBe(1) + expect(res.records[0].obj.timeZoneOffsetSeconds).toBe(42) + + session.close() + }) + + it('map date', async () => { + const session = driverGlobal.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + 'RETURN $obj as obj', + { + obj: new Date(1, 1, 1, 1) + } + ) + return txres.as({ obj: neo4j.RulesFactories.asDate() }) + }) + expect(res.records[0].obj.month).toBe(1) + + session.close() + }) + + it('map datetime', async () => { + const session = driverGlobal.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + 'RETURN $obj as obj', + { + obj: new DateTime(1, 1, 1, 1, 1, 1, 1, 42) + } + ) + return txres.as({ obj: neo4j.RulesFactories.asDateTime() }) + }) + expect(res.records[0].obj.month).toBe(1) + expect(res.records[0].obj.hour).toBe(1) + expect(res.records[0].obj.timeZoneOffsetSeconds).toBe(42) + + session.close() + }) + + it('map local datetime', async () => { + const session = driverGlobal.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + 'RETURN $obj as obj', + { + obj: new LocalDateTime(1, 1, 1, 1, 1, 1, 1) + } + ) + return txres.as({ obj: neo4j.RulesFactories.asLocalDateTime() }) + }) + expect(res.records[0].obj.month).toBe(1) + expect(res.records[0].obj.hour).toBe(1) + + session.close() + }) + + it('map point', async () => { + const session = driverGlobal.session() + + const res = await session.executeRead(async (tx) => { + const txres = tx.run( + 'RETURN $obj as obj', + { + obj: new Point(4326, 32.812493, 42.983216) + } + ) + return txres.as({ obj: neo4j.RulesFactories.asPoint() }) + }) + expect(res.records[0].obj.x).toBe(32.812493) + expect(res.records[0].obj.srid).toBe(4326) + + session.close() + }) +}) diff --git a/packages/neo4j-driver/types/index.d.ts b/packages/neo4j-driver/types/index.d.ts index 659ea07bf..246b135ff 100644 --- a/packages/neo4j-driver/types/index.d.ts +++ b/packages/neo4j-driver/types/index.d.ts @@ -97,6 +97,12 @@ import { ClientCertificateProviders, RotatingClientCertificateProvider, clientCertificateProviders, + Rule, + Rules, + RulesFactories, + RecordObjectMapping, + StandardCase, + MappedQueryResult, types as coreTypes } from 'neo4j-driver-core' import { @@ -400,7 +406,13 @@ export type { ClientCertificate, ClientCertificateProvider, ClientCertificateProviders, - RotatingClientCertificateProvider + RotatingClientCertificateProvider, + Rule, + Rules, + RulesFactories, + RecordObjectMapping, + StandardCase, + MappedQueryResult } export default forExport diff --git a/packages/testkit-backend/package.json b/packages/testkit-backend/package.json index 45ae6e92b..e01cccb1e 100644 --- a/packages/testkit-backend/package.json +++ b/packages/testkit-backend/package.json @@ -15,7 +15,8 @@ "start::deno": "deno run --allow-read --allow-write --allow-net --allow-env --allow-sys --allow-run deno/index.ts", "clean": "rm -fr node_modules public/index.js", "prepare": "npm run build", - "node": "node" + "node": "node", + "deno": "deno run --allow-read --allow-write --allow-net --allow-env --allow-sys --allow-run" }, "repository": { "type": "git",