From 5c45b0c5a08c5077fff2f4e6238d0ff4363e4ae8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20Barc=C3=A9los?= Date: Wed, 8 Nov 2023 12:17:41 +0100 Subject: [PATCH 01/12] Introduce Result, Record and Graph types mappping --- packages/core/src/graph-types.ts | 28 +++ packages/core/src/index.ts | 12 +- packages/core/src/mapping.highlevel.ts | 72 ++++++ packages/core/src/mapping.rulesfactories.ts | 214 +++++++++++++++++ packages/core/src/record.ts | 8 + packages/core/src/result-transformers.ts | 7 + packages/core/src/result.ts | 12 +- .../neo4j-driver-deno/lib/core/graph-types.ts | 29 +++ packages/neo4j-driver-deno/lib/core/index.ts | 12 +- .../lib/core/mapping.highlevel.ts | 76 ++++++ .../lib/core/mapping.rulesfactories.ts | 217 ++++++++++++++++++ packages/neo4j-driver-deno/lib/core/record.ts | 8 + .../lib/core/result-transformers.ts | 7 + packages/neo4j-driver-deno/lib/core/result.ts | 12 +- packages/neo4j-driver-deno/lib/mod.ts | 15 +- packages/neo4j-driver-lite/src/index.ts | 15 +- 16 files changed, 726 insertions(+), 18 deletions(-) create mode 100644 packages/core/src/mapping.highlevel.ts create mode 100644 packages/core/src/mapping.rulesfactories.ts create mode 100644 packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts create mode 100644 packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts diff --git a/packages/core/src/graph-types.ts b/packages/core/src/graph-types.ts index 538d546ba..b7bd1069f 100644 --- a/packages/core/src/graph-types.ts +++ b/packages/core/src/graph-types.ts @@ -18,6 +18,7 @@ */ import Integer from './integer' import { stringify } from './json' +import { Rules, GenericConstructor, as } from './mapping.highlevel' type StandardDate = Date /** @@ -84,6 +85,15 @@ class Node identity.toString()) } + 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 */ @@ -201,6 +211,15 @@ class Relationship end.toString()) } + 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 */ @@ -322,6 +341,15 @@ class UnboundRelationship(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 82f0c76cd..5200fb846 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -94,6 +94,8 @@ import * as types from './types' import * as json from './json' import resultTransformers, { ResultTransformer } from './result-transformers' import * as internal from './internal' // todo: removed afterwards +import { Rule, Rules } from './mapping.highlevel' +import { RulesFactories } from './mapping.rulesfactories' /** * Object containing string constants representing predefined {@link Neo4jError} codes. @@ -171,7 +173,8 @@ const forExport = { notificationCategory, notificationSeverityLevel, notificationFilterDisabledCategory, - notificationFilterMinimumSeverityLevel + notificationFilterMinimumSeverityLevel, + RulesFactories } export { @@ -240,7 +243,8 @@ export { notificationCategory, notificationSeverityLevel, notificationFilterDisabledCategory, - notificationFilterMinimumSeverityLevel + notificationFilterMinimumSeverityLevel, + RulesFactories } export type { @@ -265,7 +269,9 @@ export type { NotificationSeverityLevel, NotificationFilter, NotificationFilterDisabledCategory, - NotificationFilterMinimumSeverityLevel + NotificationFilterMinimumSeverityLevel, + Rule, + Rules } export default forExport diff --git a/packages/core/src/mapping.highlevel.ts b/packages/core/src/mapping.highlevel.ts new file mode 100644 index 000000000..31dcd0bd7 --- /dev/null +++ b/packages/core/src/mapping.highlevel.ts @@ -0,0 +1,72 @@ +/** + * 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 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 + +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 = typeof constructorOrRules === 'object' ? 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 value = gettable.get(rule?.from ?? key) + 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 +} diff --git a/packages/core/src/mapping.rulesfactories.ts b/packages/core/src/mapping.rulesfactories.ts new file mode 100644 index 000000000..629431668 --- /dev/null +++ b/packages/core/src/mapping.rulesfactories.ts @@ -0,0 +1,214 @@ +/** + * 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' + +export const RulesFactories = Object.freeze({ + 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 + } + }, + asNumber (rule?: Rule & { acceptBigInt?: boolean }) { + return { + validate: (value: any, field: string) => { + 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 + } + }, + asBigInt (rule?: Rule & { acceptNumber?: boolean }) { + 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 + } + }, + asNode (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isNode(value)) { + throw new TypeError(`${field} should be a Node but received ${typeof value}`) + } + }, + ...rule + } + }, + asRelationship (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isRelationship(value)) { + throw new TypeError(`${field} should be a Relationship but received ${typeof value}`) + } + }, + ...rule + } + }, + asUnboundRelationship (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isUnboundRelationship(value)) { + throw new TypeError(`${field} should be a UnboundRelationship but received ${typeof value}`) + } + }, + ...rule + } + }, + asPath (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isPath(value)) { + throw new TypeError(`${field} should be a Path but received ${typeof value}`) + } + }, + ...rule + } + }, + asPoint (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isPoint(value)) { + throw new TypeError(`${field} should be a Point but received ${typeof value}`) + } + }, + ...rule + } + }, + asDuration (rule?: Rule & { toString?: boolean }) { + 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 + } + }, + asLocalTime (rule?: Rule & { toString?: boolean }) { + 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 + } + }, + asTime (rule?: Rule & { toString?: boolean }) { + 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 + } + }, + asDate (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + 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 + } + }, + asLocalDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + 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 + } + }, + asDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + 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 + } + }, + asList (rule?: Rule & { apply?: Rule }) { + return { + validate: (value: any, field: string) => { + if (!Array.isArray(value)) { + throw new TypeError(`${field} should be a string 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 cac99dd01..059122116 100644 --- a/packages/core/src/record.ts +++ b/packages/core/src/record.ts @@ -18,6 +18,7 @@ */ import { newError } from './error' +import { Rules, GenericConstructor, as } from './mapping.highlevel' type RecordShape = { [K in Key]: Value @@ -134,6 +135,13 @@ class Record< return resultArray } + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): 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 8dbc4e9e1..4794f085b 100644 --- a/packages/core/src/result-transformers.ts +++ b/packages/core/src/result-transformers.ts @@ -22,6 +22,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' async function createEagerResultFromResult (result: Result): Promise> { const { summary, records } = await result @@ -164,6 +165,12 @@ class ResultTransformers { }) } } + + hydratedResultTransformer (rules: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + hydratedResultTransformer (genericConstructor: GenericConstructor, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + hydratedResultTransformer (constructorOrRules: GenericConstructor | Rules, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> { + return async result => await result.as(constructorOrRules as unknown as GenericConstructor, rules) + } } /** diff --git a/packages/core/src/result.ts b/packages/core/src/result.ts index 938f04ff1..c25d6f20d 100644 --- a/packages/core/src/result.ts +++ b/packages/core/src/result.ts @@ -25,6 +25,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' const { EMPTY_CONNECTION_HOLDER } = connectionHolder @@ -151,6 +152,13 @@ class Result implements Promise(rules: Rules): Promise<{ records: T[], summary: ResultSummary }> + as (genericConstructor: GenericConstructor, rules?: Rules): Promise<{ records: T[], summary: ResultSummary }> + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): Promise<{ records: T[], summary: ResultSummary }> { + // @ts-expect-error + return this._getOrCreatePromise(r => r.as(constructorOrRules, rules)) + } + /** * Returns a promise for the field keys. * @@ -212,13 +220,13 @@ class Result implements Promise> { + private _getOrCreatePromise (mapper: (r: Record) => O = r => r as unknown as R): Promise> { if (this._p == null) { this._p = new Promise((resolve, reject) => { const records: Array> = [] const observer = { onNext: (record: Record) => { - records.push(record) + records.push(mapper(record) as unknown as Record) }, onCompleted: (summary: ResultSummary) => { resolve({ records, summary }) diff --git a/packages/neo4j-driver-deno/lib/core/graph-types.ts b/packages/neo4j-driver-deno/lib/core/graph-types.ts index 735f0105d..62d5c5656 100644 --- a/packages/neo4j-driver-deno/lib/core/graph-types.ts +++ b/packages/neo4j-driver-deno/lib/core/graph-types.ts @@ -18,6 +18,8 @@ */ import Integer from './integer.ts' import { stringify } from './json.ts' +import { Rules, GenericConstructor, as } from './mapping.highlevel.ts' + type StandardDate = Date /** @@ -84,6 +86,15 @@ class Node identity.toString()) } + 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 */ @@ -201,6 +212,15 @@ class Relationship end.toString()) } + 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 */ @@ -322,6 +342,15 @@ class UnboundRelationship(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 0242df6c3..a0c85b0c4 100644 --- a/packages/neo4j-driver-deno/lib/core/index.ts +++ b/packages/neo4j-driver-deno/lib/core/index.ts @@ -94,6 +94,8 @@ import * as types from './types.ts' import * as json from './json.ts' import resultTransformers, { ResultTransformer } from './result-transformers.ts' import * as internal from './internal/index.ts' +import { Rule, Rules } from './mapping.highlevel.ts' +import { RulesFactories } from './mapping.rulesfactories.ts' /** * Object containing string constants representing predefined {@link Neo4jError} codes. @@ -171,7 +173,8 @@ const forExport = { notificationCategory, notificationSeverityLevel, notificationFilterDisabledCategory, - notificationFilterMinimumSeverityLevel + notificationFilterMinimumSeverityLevel, + RulesFactories } export { @@ -240,7 +243,8 @@ export { notificationCategory, notificationSeverityLevel, notificationFilterDisabledCategory, - notificationFilterMinimumSeverityLevel + notificationFilterMinimumSeverityLevel, + RulesFactories } export type { @@ -265,7 +269,9 @@ export type { NotificationSeverityLevel, NotificationFilter, NotificationFilterDisabledCategory, - NotificationFilterMinimumSeverityLevel + NotificationFilterMinimumSeverityLevel, + Rule, + Rules } export default forExport 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..35831c256 --- /dev/null +++ b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts @@ -0,0 +1,76 @@ +/** + * 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 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 + +type 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 = typeof constructorOrRules === 'object' ? 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 value = gettable.get(rule?.from ?? key) + const field = `${obj.constructor.name}#${key}` + const processedValue = valueAs(value, field, rule) + + // @ts-ignore + 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 ? rule.convert(value, field) : value +} + + 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..23648ab40 --- /dev/null +++ b/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts @@ -0,0 +1,217 @@ +/** + * 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' + + +export const RulesFactories = Object.freeze({ + 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 + } + }, + asNumber (rule?: Rule & { acceptBigInt?: boolean }) { + return { + validate: (value: any, field: string) => { + 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 + } + }, + asBigInt (rule?: Rule & { acceptNumber?: boolean }) { + 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 + } + }, + asNode (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isNode(value)) { + throw new TypeError(`${field} should be a Node but received ${typeof value}`) + } + }, + ...rule + } + }, + asRelationship (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isRelationship(value)) { + throw new TypeError(`${field} should be a Relationship but received ${typeof value}`) + } + }, + ...rule + } + }, + asUnboundRelationship (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isUnboundRelationship(value)) { + throw new TypeError(`${field} should be a UnboundRelationship but received ${typeof value}`) + } + }, + ...rule + } + }, + asPath (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isPath(value)) { + throw new TypeError(`${field} should be a Path but received ${typeof value}`) + } + }, + ...rule + } + }, + asPoint (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isPoint(value)) { + throw new TypeError(`${field} should be a Point but received ${typeof value}`) + } + }, + ...rule + } + }, + asDuration (rule?: Rule & { toString?: boolean }) { + 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 + } + }, + asLocalTime (rule?: Rule & { toString?: boolean }) { + 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 + } + }, + asTime (rule?: Rule & { toString?: boolean }) { + 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 + } + }, + asDate (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + 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 + } + }, + asLocalDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + 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 + } + }, + asDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + 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 + } + }, + asList (rule?: Rule & { apply?: Rule }) { + return { + validate: (value: any, field: string) => { + if (!Array.isArray(value)) { + throw new TypeError(`${field} should be a string 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 + } + + } +}) + +type 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 71ba02742..0dcae2b62 100644 --- a/packages/neo4j-driver-deno/lib/core/record.ts +++ b/packages/neo4j-driver-deno/lib/core/record.ts @@ -18,6 +18,7 @@ */ import { newError } from './error.ts' +import { Rules, GenericConstructor, as } from './mapping.highlevel.ts' type RecordShape = { [K in Key]: Value @@ -134,6 +135,13 @@ class Record< return resultArray } + as (rules: Rules): T + as (genericConstructor: GenericConstructor): T + as (genericConstructor: GenericConstructor, rules?: Rules): 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 0ac8d94f6..5ff951f7d 100644 --- a/packages/neo4j-driver-deno/lib/core/result-transformers.ts +++ b/packages/neo4j-driver-deno/lib/core/result-transformers.ts @@ -22,6 +22,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' async function createEagerResultFromResult (result: Result): Promise> { const { summary, records } = await result @@ -164,6 +165,12 @@ class ResultTransformers { }) } } + + hydratedResultTransformer (rules: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + hydratedResultTransformer (genericConstructor: GenericConstructor, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + hydratedResultTransformer (constructorOrRules: GenericConstructor | Rules, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> { + return result => result.as(constructorOrRules as unknown as GenericConstructor, rules) + } } /** diff --git a/packages/neo4j-driver-deno/lib/core/result.ts b/packages/neo4j-driver-deno/lib/core/result.ts index 43ba35dfe..b56635353 100644 --- a/packages/neo4j-driver-deno/lib/core/result.ts +++ b/packages/neo4j-driver-deno/lib/core/result.ts @@ -25,6 +25,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' const { EMPTY_CONNECTION_HOLDER } = connectionHolder @@ -151,6 +152,13 @@ class Result implements Promise(rules: Rules): Promise<{ records: T[], summary: ResultSummary }> + as (genericConstructor: GenericConstructor, rules?: Rules): Promise<{ records: T[], summary: ResultSummary }> + as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): Promise<{ records: T[], summary: ResultSummary }> { + // @ts-expect-error + return this._getOrCreatePromise(r => r.as(constructorOrRules, rules)) + } + /** * Returns a promise for the field keys. * @@ -212,13 +220,13 @@ class Result implements Promise> { + private _getOrCreatePromise (mapper: (r: Record) => O = r => r as unknown as R ): Promise> { if (this._p == null) { this._p = new Promise((resolve, reject) => { const records: Array> = [] const observer = { onNext: (record: Record) => { - records.push(record) + records.push(mapper(record) as unknown as Record) }, onCompleted: (summary: ResultSummary) => { resolve({ records, summary }) diff --git a/packages/neo4j-driver-deno/lib/mod.ts b/packages/neo4j-driver-deno/lib/mod.ts index d32a84300..346b34fe6 100644 --- a/packages/neo4j-driver-deno/lib/mod.ts +++ b/packages/neo4j-driver-deno/lib/mod.ts @@ -99,7 +99,10 @@ import { Transaction, TransactionPromise, types as coreTypes, - UnboundRelationship + UnboundRelationship, + Rule, + Rules, + RulesFactories } from './core/index.ts' // @deno-types=./bolt-connection/types/index.d.ts import { DirectConnectionProvider, RoutingConnectionProvider } from './bolt-connection/index.js' @@ -426,7 +429,8 @@ const forExport = { notificationCategory, notificationSeverityLevel, notificationFilterDisabledCategory, - notificationFilterMinimumSeverityLevel + notificationFilterMinimumSeverityLevel, + RulesFactories } export { @@ -493,7 +497,8 @@ export { notificationCategory, notificationSeverityLevel, notificationFilterDisabledCategory, - notificationFilterMinimumSeverityLevel + notificationFilterMinimumSeverityLevel, + RulesFactories } export type { QueryResult, @@ -518,6 +523,8 @@ export type { NotificationSeverityLevel, NotificationFilter, NotificationFilterDisabledCategory, - NotificationFilterMinimumSeverityLevel + NotificationFilterMinimumSeverityLevel, + Rule, + Rules } export default forExport diff --git a/packages/neo4j-driver-lite/src/index.ts b/packages/neo4j-driver-lite/src/index.ts index 994491996..fc01bcd44 100644 --- a/packages/neo4j-driver-lite/src/index.ts +++ b/packages/neo4j-driver-lite/src/index.ts @@ -99,7 +99,10 @@ import { Transaction, TransactionPromise, types as coreTypes, - UnboundRelationship + UnboundRelationship, + Rule, + Rules, + RulesFactories } from 'neo4j-driver-core' import { DirectConnectionProvider, RoutingConnectionProvider } from 'neo4j-driver-bolt-connection' @@ -425,7 +428,8 @@ const forExport = { notificationCategory, notificationSeverityLevel, notificationFilterDisabledCategory, - notificationFilterMinimumSeverityLevel + notificationFilterMinimumSeverityLevel, + RulesFactories } export { @@ -492,7 +496,8 @@ export { notificationCategory, notificationSeverityLevel, notificationFilterDisabledCategory, - notificationFilterMinimumSeverityLevel + notificationFilterMinimumSeverityLevel, + RulesFactories } export type { QueryResult, @@ -517,6 +522,8 @@ export type { NotificationSeverityLevel, NotificationFilter, NotificationFilterDisabledCategory, - NotificationFilterMinimumSeverityLevel + NotificationFilterMinimumSeverityLevel, + Rule, + Rules } export default forExport From 0a93a376e83ef99972d3c29bf09bccc7c875af3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20Barc=C3=A9los?= Date: Wed, 8 Nov 2023 16:38:22 +0100 Subject: [PATCH 02/12] Add global registry --- packages/core/src/index.ts | 8 +- packages/core/src/mapping.highlevel.ts | 20 +- .../neo4j-driver-deno/lib/core/graph-types.ts | 7 +- packages/neo4j-driver-deno/lib/core/index.ts | 8 +- .../lib/core/mapping.highlevel.ts | 85 ++-- .../lib/core/mapping.rulesfactories.ts | 369 +++++++++--------- packages/neo4j-driver-deno/lib/core/record.ts | 2 +- .../lib/core/result-transformers.ts | 2 +- packages/neo4j-driver-deno/lib/core/result.ts | 2 +- packages/neo4j-driver-deno/lib/mod.ts | 9 +- packages/neo4j-driver-lite/src/index.ts | 9 +- packages/testkit-backend/package.json | 3 +- 12 files changed, 282 insertions(+), 242 deletions(-) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5200fb846..2a5c1f670 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -94,7 +94,7 @@ import * as types from './types' import * as json from './json' import resultTransformers, { ResultTransformer } from './result-transformers' import * as internal from './internal' // todo: removed afterwards -import { Rule, Rules } from './mapping.highlevel' +import { Rule, Rules, mapping } from './mapping.highlevel' import { RulesFactories } from './mapping.rulesfactories' /** @@ -174,7 +174,8 @@ const forExport = { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - RulesFactories + RulesFactories, + mapping } export { @@ -244,7 +245,8 @@ export { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - RulesFactories + RulesFactories, + mapping } export type { diff --git a/packages/core/src/mapping.highlevel.ts b/packages/core/src/mapping.highlevel.ts index 31dcd0bd7..82de717ab 100644 --- a/packages/core/src/mapping.highlevel.ts +++ b/packages/core/src/mapping.highlevel.ts @@ -27,11 +27,21 @@ export interface Rule { export type Rules = Record +const rulesRegistry: Record = {} + +export function register (constructor: GenericConstructor, rules: Rules): void { + rulesRegistry[constructor.toString()] = rules +} + +export const mapping = { + register +} + 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 = typeof constructorOrRules === 'object' ? constructorOrRules : rules + const theRules = getRules(constructorOrRules, rules) const vistedKeys: string[] = [] const obj = new GenericConstructor() @@ -70,3 +80,11 @@ export function valueAs (value: unknown, field: string, rule?: Rule): unknown { 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/graph-types.ts b/packages/neo4j-driver-deno/lib/core/graph-types.ts index 62d5c5656..75707ab1e 100644 --- a/packages/neo4j-driver-deno/lib/core/graph-types.ts +++ b/packages/neo4j-driver-deno/lib/core/graph-types.ts @@ -20,7 +20,6 @@ import Integer from './integer.ts' import { stringify } from './json.ts' import { Rules, GenericConstructor, as } from './mapping.highlevel.ts' - type StandardDate = Date /** * @typedef {number | Integer | bigint} NumberOrInteger @@ -92,7 +91,7 @@ class Node(constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { return as({ get: (key) => this.properties[key] - }, constructorOrRules, rules) + }, constructorOrRules, rules) } /** @@ -218,7 +217,7 @@ class Relationship(constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { return as({ get: (key) => this.properties[key] - }, constructorOrRules, rules) + }, constructorOrRules, rules) } /** @@ -348,7 +347,7 @@ class UnboundRelationship(constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { return as({ get: (key) => this.properties[key] - }, constructorOrRules, rules) + }, constructorOrRules, rules) } /** diff --git a/packages/neo4j-driver-deno/lib/core/index.ts b/packages/neo4j-driver-deno/lib/core/index.ts index a0c85b0c4..9feb8a5e2 100644 --- a/packages/neo4j-driver-deno/lib/core/index.ts +++ b/packages/neo4j-driver-deno/lib/core/index.ts @@ -94,7 +94,7 @@ import * as types from './types.ts' import * as json from './json.ts' import resultTransformers, { ResultTransformer } from './result-transformers.ts' import * as internal from './internal/index.ts' -import { Rule, Rules } from './mapping.highlevel.ts' +import { Rule, Rules, mapping } from './mapping.highlevel.ts' import { RulesFactories } from './mapping.rulesfactories.ts' /** @@ -174,7 +174,8 @@ const forExport = { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - RulesFactories + RulesFactories, + mapping } export { @@ -244,7 +245,8 @@ export { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - RulesFactories + RulesFactories, + mapping } export type { diff --git a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts index 35831c256..609e446c5 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts @@ -19,58 +19,73 @@ 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 + optional?: boolean + from?: string + convert?: (recordValue: any, field: string) => any + validate?: (recordValue: any, field: string) => void } export type Rules = Record -type Gettable = { get(key: string): V } +const rulesRegistry: Record = {} +export function register (constructor: GenericConstructor, rules: Rules): void { + rulesRegistry[constructor.toString()] = rules +} + +export const mapping = { + register +} -export function as (gettable: Gettable , constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { - const GenericConstructor = typeof constructorOrRules === 'function' ? constructorOrRules : Object - const theRules = typeof constructorOrRules === 'object' ? constructorOrRules : rules - const vistedKeys: string[] = [] +interface Gettable { get: (key: string) => V } - const obj = new GenericConstructor +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[] = [] - for (const [key, rule] of Object.entries(theRules ?? {})) { - vistedKeys.push(key) - _apply(gettable, obj, key, rule) - } + const obj = new GenericConstructor() - for (const key of Object.getOwnPropertyNames(obj)) { - if (!vistedKeys.includes(key)) { - _apply(gettable, obj, key, theRules?.[key]) - } + 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 -} + } + return obj as unknown as T +} -function _apply(gettable: Gettable, obj: T, key: string, rule?: Rule): void { - const value = gettable.get(rule?.from ?? key) - const field = `${obj.constructor.name}#${key}` - const processedValue = valueAs(value, field, rule) +function _apply (gettable: Gettable, obj: T, key: string, rule?: Rule): void { + const value = gettable.get(rule?.from ?? key) + const field = `${obj.constructor.name}#${key}` + const processedValue = valueAs(value, field, rule) - // @ts-ignore - obj[key] = processedValue ?? obj[key] + // @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 (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 } - if (typeof rule?.validate === 'function') { - rule.validate(value, field) - } - - return rule?.convert ? rule.convert(value, field) : value + return typeof constructorOrRules !== 'object' ? rulesRegistry[constructorOrRules.toString()] : undefined } - diff --git a/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts b/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts index 23648ab40..50298d5ff 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts @@ -19,199 +19,196 @@ import { Rule, valueAs } from './mapping.highlevel.ts' - -import { StandardDate, isNode, isPath, isRelationship, isUnboundRelationship } from './graph-types.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' - export const RulesFactories = Object.freeze({ - 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 - } - }, - asNumber (rule?: Rule & { acceptBigInt?: boolean }) { - return { - validate: (value: any, field: string) => { - 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 - } - }, - asBigInt (rule?: Rule & { acceptNumber?: boolean }) { - 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 - } - }, - asNode (rule?: Rule) { - return { - validate: (value: any, field: string) => { - if (!isNode(value)) { - throw new TypeError(`${field} should be a Node but received ${typeof value}`) - } - }, - ...rule - } - }, - asRelationship (rule?: Rule) { - return { - validate: (value: any, field: string) => { - if (!isRelationship(value)) { - throw new TypeError(`${field} should be a Relationship but received ${typeof value}`) - } - }, - ...rule - } - }, - asUnboundRelationship (rule?: Rule) { - return { - validate: (value: any, field: string) => { - if (!isUnboundRelationship(value)) { - throw new TypeError(`${field} should be a UnboundRelationship but received ${typeof value}`) - } - }, - ...rule - } - }, - asPath (rule?: Rule) { - return { - validate: (value: any, field: string) => { - if (!isPath(value)) { - throw new TypeError(`${field} should be a Path but received ${typeof value}`) - } - }, - ...rule - } - }, - asPoint (rule?: Rule) { - return { - validate: (value: any, field: string) => { - if (!isPoint(value)) { - throw new TypeError(`${field} should be a Point but received ${typeof value}`) - } - }, - ...rule - } - }, - asDuration (rule?: Rule & { toString?: boolean }) { - 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 - } - }, - asLocalTime (rule?: Rule & { toString?: boolean }) { - 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 - } - }, - asTime (rule?: Rule & { toString?: boolean }) { - 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 - } - }, - asDate (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { - 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 - } - }, - asLocalDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { - 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 - } - }, - asDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { - 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 - } - }, - asList (rule?: Rule & { apply?: Rule }) { - return { - validate: (value: any, field: string) => { - if (!Array.isArray(value)) { - throw new TypeError(`${field} should be a string 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 - } - + 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 + } + }, + asNumber (rule?: Rule & { acceptBigInt?: boolean }) { + return { + validate: (value: any, field: string) => { + 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 + } + }, + asBigInt (rule?: Rule & { acceptNumber?: boolean }) { + 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 + } + }, + asNode (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isNode(value)) { + throw new TypeError(`${field} should be a Node but received ${typeof value}`) + } + }, + ...rule + } + }, + asRelationship (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isRelationship(value)) { + throw new TypeError(`${field} should be a Relationship but received ${typeof value}`) + } + }, + ...rule + } + }, + asUnboundRelationship (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isUnboundRelationship(value)) { + throw new TypeError(`${field} should be a UnboundRelationship but received ${typeof value}`) + } + }, + ...rule + } + }, + asPath (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isPath(value)) { + throw new TypeError(`${field} should be a Path but received ${typeof value}`) + } + }, + ...rule } + }, + asPoint (rule?: Rule) { + return { + validate: (value: any, field: string) => { + if (!isPoint(value)) { + throw new TypeError(`${field} should be a Point but received ${typeof value}`) + } + }, + ...rule + } + }, + asDuration (rule?: Rule & { toString?: boolean }) { + 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 + } + }, + asLocalTime (rule?: Rule & { toString?: boolean }) { + 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 + } + }, + asTime (rule?: Rule & { toString?: boolean }) { + 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 + } + }, + asDate (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + 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 + } + }, + asLocalDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + 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 + } + }, + asDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + 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 + } + }, + asList (rule?: Rule & { apply?: Rule }) { + return { + validate: (value: any, field: string) => { + if (!Array.isArray(value)) { + throw new TypeError(`${field} should be a string 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 + } + } }) -type ConvertableToStdDateOrStr = { toStandardDate: () => StandardDate, toString: () => string } +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() - } +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 + } + return value } diff --git a/packages/neo4j-driver-deno/lib/core/record.ts b/packages/neo4j-driver-deno/lib/core/record.ts index 0dcae2b62..69da97bd8 100644 --- a/packages/neo4j-driver-deno/lib/core/record.ts +++ b/packages/neo4j-driver-deno/lib/core/record.ts @@ -139,7 +139,7 @@ class Record< as (genericConstructor: GenericConstructor): T as (genericConstructor: GenericConstructor, rules?: Rules): T as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): T { - return as(this, constructorOrRules, rules) + return as(this, constructorOrRules, rules) } /** diff --git a/packages/neo4j-driver-deno/lib/core/result-transformers.ts b/packages/neo4j-driver-deno/lib/core/result-transformers.ts index 5ff951f7d..386828098 100644 --- a/packages/neo4j-driver-deno/lib/core/result-transformers.ts +++ b/packages/neo4j-driver-deno/lib/core/result-transformers.ts @@ -169,7 +169,7 @@ class ResultTransformers { hydratedResultTransformer (rules: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> hydratedResultTransformer (genericConstructor: GenericConstructor, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> hydratedResultTransformer (constructorOrRules: GenericConstructor | Rules, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> { - return result => result.as(constructorOrRules as unknown as GenericConstructor, rules) + return async result => await result.as(constructorOrRules as unknown as GenericConstructor, rules) } } diff --git a/packages/neo4j-driver-deno/lib/core/result.ts b/packages/neo4j-driver-deno/lib/core/result.ts index b56635353..3c5ab0f98 100644 --- a/packages/neo4j-driver-deno/lib/core/result.ts +++ b/packages/neo4j-driver-deno/lib/core/result.ts @@ -220,7 +220,7 @@ class Result implements Promise (mapper: (r: Record) => O = r => r as unknown as R ): Promise> { + private _getOrCreatePromise (mapper: (r: Record) => O = r => r as unknown as R): Promise> { if (this._p == null) { this._p = new Promise((resolve, reject) => { const records: Array> = [] diff --git a/packages/neo4j-driver-deno/lib/mod.ts b/packages/neo4j-driver-deno/lib/mod.ts index 346b34fe6..78af028fd 100644 --- a/packages/neo4j-driver-deno/lib/mod.ts +++ b/packages/neo4j-driver-deno/lib/mod.ts @@ -102,7 +102,8 @@ import { UnboundRelationship, Rule, Rules, - RulesFactories + RulesFactories, + mapping } from './core/index.ts' // @deno-types=./bolt-connection/types/index.d.ts import { DirectConnectionProvider, RoutingConnectionProvider } from './bolt-connection/index.js' @@ -430,7 +431,8 @@ const forExport = { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - RulesFactories + RulesFactories, + mapping } export { @@ -498,7 +500,8 @@ export { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - RulesFactories + RulesFactories, + mapping } export type { QueryResult, diff --git a/packages/neo4j-driver-lite/src/index.ts b/packages/neo4j-driver-lite/src/index.ts index fc01bcd44..0999da693 100644 --- a/packages/neo4j-driver-lite/src/index.ts +++ b/packages/neo4j-driver-lite/src/index.ts @@ -102,7 +102,8 @@ import { UnboundRelationship, Rule, Rules, - RulesFactories + RulesFactories, + mapping } from 'neo4j-driver-core' import { DirectConnectionProvider, RoutingConnectionProvider } from 'neo4j-driver-bolt-connection' @@ -429,7 +430,8 @@ const forExport = { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - RulesFactories + RulesFactories, + mapping } export { @@ -497,7 +499,8 @@ export { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - RulesFactories + RulesFactories, + mapping } export type { QueryResult, 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", From 918989f26b45594da2001428a48873c686fa8b8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20Barc=C3=A9los?= Date: Wed, 8 Nov 2023 16:38:48 +0100 Subject: [PATCH 03/12] sync deno --- .../lib/core/mapping.highlevel.ts | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts index 609e446c5..82de717ab 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts @@ -30,11 +30,11 @@ export type Rules = Record const rulesRegistry: Record = {} export function register (constructor: GenericConstructor, rules: Rules): void { - rulesRegistry[constructor.toString()] = rules + rulesRegistry[constructor.toString()] = rules } export const mapping = { - register + register } interface Gettable { get: (key: string) => V } @@ -80,12 +80,11 @@ export function valueAs (value: unknown, field: string, rule?: Rule): unknown { 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 -} +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 +} From 4e8ac68bd1842d73dfb99fc776c783f73dff47ef Mon Sep 17 00:00:00 2001 From: MaxAake <61233757+MaxAake@users.noreply.github.com> Date: Fri, 31 Jan 2025 13:10:35 +0100 Subject: [PATCH 04/12] conflict resolution fix --- packages/core/src/result-transformers.ts | 6 ------ packages/neo4j-driver-deno/lib/core/result-transformers.ts | 6 ------ 2 files changed, 12 deletions(-) diff --git a/packages/core/src/result-transformers.ts b/packages/core/src/result-transformers.ts index fe84a1199..cde7515b1 100644 --- a/packages/core/src/result-transformers.ts +++ b/packages/core/src/result-transformers.ts @@ -24,12 +24,6 @@ import { GenericConstructor, Rules } from './mapping.highlevel' import { NumberOrInteger } from './graph-types' import Integer from './integer' -async function createEagerResultFromResult (result: Result): Promise> { - const { summary, records } = await result - const keys = await result.keys() - return new EagerResult(keys, records, summary) -} - type ResultTransformer = (result: Result) => Promise /** * Protocol for transforming {@link Result}. diff --git a/packages/neo4j-driver-deno/lib/core/result-transformers.ts b/packages/neo4j-driver-deno/lib/core/result-transformers.ts index 98d633c14..c2ae86a13 100644 --- a/packages/neo4j-driver-deno/lib/core/result-transformers.ts +++ b/packages/neo4j-driver-deno/lib/core/result-transformers.ts @@ -24,12 +24,6 @@ import { GenericConstructor, Rules } from './mapping.highlevel.ts' import { NumberOrInteger } from './graph-types.ts' import Integer from './integer.ts' -async function createEagerResultFromResult (result: Result): Promise> { - const { summary, records } = await result - const keys = await result.keys() - return new EagerResult(keys, records, summary) -} - type ResultTransformer = (result: Result) => Promise /** * Protocol for transforming {@link Result}. From d71a19c52e24b51d198c3e4cd6d1334675e14f73 Mon Sep 17 00:00:00 2001 From: MaxAake <61233757+MaxAake@users.noreply.github.com> Date: Mon, 10 Mar 2025 10:14:23 +0100 Subject: [PATCH 05/12] Documentation additions, import fixes and result.as fix --- packages/core/src/graph-types.ts | 21 +++ packages/core/src/mapping.highlevel.ts | 24 +++ packages/core/src/mapping.rulesfactories.ts | 163 ++++++++++++++++-- packages/core/src/result-transformers.ts | 36 +++- packages/core/src/result.ts | 53 +++++- .../neo4j-driver-deno/lib/core/graph-types.ts | 21 +++ .../lib/core/mapping.highlevel.ts | 25 +++ .../lib/core/mapping.rulesfactories.ts | 163 ++++++++++++++++-- .../lib/core/result-transformers.ts | 36 +++- packages/neo4j-driver-deno/lib/core/result.ts | 53 +++++- packages/neo4j-driver/src/index.js | 16 +- 11 files changed, 559 insertions(+), 52 deletions(-) diff --git a/packages/core/src/graph-types.ts b/packages/core/src/graph-types.ts index fbac2993d..1001d0486 100644 --- a/packages/core/src/graph-types.ts +++ b/packages/core/src/graph-types.ts @@ -83,6 +83,13 @@ 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 @@ -209,6 +216,13 @@ 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 @@ -339,6 +353,13 @@ 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 diff --git a/packages/core/src/mapping.highlevel.ts b/packages/core/src/mapping.highlevel.ts index 82de717ab..9f751685a 100644 --- a/packages/core/src/mapping.highlevel.ts +++ b/packages/core/src/mapping.highlevel.ts @@ -16,6 +16,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +/** + * constructor function of any class + */ export type GenericConstructor = new (...args: any[]) => T export interface Rule { @@ -29,6 +33,26 @@ export type Rules = Record const rulesRegistry: Record = {} +/** + * Registers a set of {@link Rules} to be used by {@link hydratedResultTransformer} 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.hydratedResultTransformer(Person, personClassRules) + * }) + * + * can instead be written: + * neo4j.mapping.register(Person, personClassRules) + * + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydratedResultTransformer(Person) + * }) + * + * + * @param {GenericConstructor} constructor The constructor function of the class to set rules for + * @param {Rules} rules The rules to set for the provided class + */ export function register (constructor: GenericConstructor, rules: Rules): void { rulesRegistry[constructor.toString()] = rules } diff --git a/packages/core/src/mapping.rulesfactories.ts b/packages/core/src/mapping.rulesfactories.ts index 629431668..f63ff44a8 100644 --- a/packages/core/src/mapping.rulesfactories.ts +++ b/packages/core/src/mapping.rulesfactories.ts @@ -18,12 +18,46 @@ */ 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. + */ export const RulesFactories = Object.freeze({ + /** + * Create a {@link Rule} that validates the value is a String. + * + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ asString (rule?: Rule): Rule { return { validate: (value, field) => { @@ -34,9 +68,18 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asNumber (rule?: Rule & { acceptBigInt?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link Number}. + * + * @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 to true 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}`) } @@ -50,7 +93,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asBigInt (rule?: Rule & { acceptNumber?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link BigInt}. + * + * @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')) { @@ -66,7 +115,23 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asNode (rule?: 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({}), + * } + * + * @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)) { @@ -76,7 +141,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asRelationship (rule?: 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)) { @@ -86,7 +157,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asUnboundRelationship (rule?: Rule) { + /** + * Create a {@link Rule} that validates the value is an {@link UnboundRelationship} + * + * @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)) { @@ -96,7 +173,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asPath (rule?: Rule) { + /** + * Create a {@link Rule} that validates the value is a {@link Path} + * + * @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)) { @@ -106,7 +189,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asPoint (rule?: Rule) { + /** + * Create a {@link Rule} that validates the value is a {@link Point} + * + * @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)) { @@ -116,7 +205,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asDuration (rule?: Rule & { toString?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link Duration} + * + * @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)) { @@ -127,7 +222,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asLocalTime (rule?: Rule & { toString?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link LocalTime} + * + * @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)) { @@ -138,7 +239,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asTime (rule?: Rule & { toString?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link Time} + * + * @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)) { @@ -149,7 +256,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asDate (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link Date} + * + * @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)) { @@ -160,7 +273,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asLocalDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link LocalDateTime} + * + * @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)) { @@ -171,7 +290,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link DateTime} + * + * @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)) { @@ -182,11 +307,17 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asList (rule?: Rule & { apply?: Rule }) { + /** + * Create a {@link Rule} that validates the value is a List. Optionally taking a rule for hydrating the contained values. + * + * @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 string but received ${typeof value}`) + throw new TypeError(`${field} should be a list but received ${typeof value}`) } }, convert: (list: any[], field: string) => { diff --git a/packages/core/src/result-transformers.ts b/packages/core/src/result-transformers.ts index cde7515b1..1c7cdde35 100644 --- a/packages/core/src/result-transformers.ts +++ b/packages/core/src/result-transformers.ts @@ -270,8 +270,42 @@ class ResultTransformers { hydratedResultTransformer (rules: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> hydratedResultTransformer (genericConstructor: GenericConstructor, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + /** + * Creates a {@link ResultTransformer} which maps the result to a hydrated object + * + * @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.hydratedResultTransformer(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.mapping.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.hydratedResultTransformer(Person) + * }) + * + * // A hydratedResultTransformer 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 + */ hydratedResultTransformer (constructorOrRules: GenericConstructor | Rules, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> { - return async result => await result.as(constructorOrRules as unknown as GenericConstructor, rules) + 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 bbab73d67..dcba71ee5 100644 --- a/packages/core/src/result.ts +++ b/packages/core/src/result.ts @@ -61,6 +61,8 @@ interface QueryResult { summary: ResultSummary } +export interface MappedResult extends Result> {} + /** * Interface to observe updates on the Result which is being produced. * @@ -122,6 +124,7 @@ class Result implements Promise implements Promise(rules: Rules): Promise<{ records: T[], summary: ResultSummary }> - as (genericConstructor: GenericConstructor, rules?: Rules): Promise<{ records: T[], summary: ResultSummary }> - as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): Promise<{ records: T[], summary: ResultSummary }> { + as (rules: Rules): MappedResult + as (genericConstructor: GenericConstructor, rules?: Rules): MappedResult + /** + * Maps the records of this result to a provided type 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 - return this._getOrCreatePromise(r => r.as(constructorOrRules, rules)) + this._mapper = r => r.as(constructorOrRules, rules) + // @ts-expect-error + return this } /** @@ -223,13 +258,13 @@ class Result implements Promise (mapper: (r: Record) => O = r => r as unknown as R): Promise> { + private _getOrCreatePromise (): Promise> { if (this._p == null) { this._p = new Promise((resolve, reject) => { const records: Array> = [] const observer = { onNext: (record: Record) => { - records.push(mapper(record) as unknown as Record) + records.push(this._mapper(record) as unknown as Record) }, onCompleted: (summary: ResultSummary) => { resolve({ records, summary }) @@ -580,7 +615,11 @@ class Result implements Promise { - observer._push({ done: false, value: record }) + 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 }) diff --git a/packages/neo4j-driver-deno/lib/core/graph-types.ts b/packages/neo4j-driver-deno/lib/core/graph-types.ts index 994397495..035828573 100644 --- a/packages/neo4j-driver-deno/lib/core/graph-types.ts +++ b/packages/neo4j-driver-deno/lib/core/graph-types.ts @@ -83,6 +83,13 @@ 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 @@ -209,6 +216,13 @@ 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 @@ -339,6 +353,13 @@ 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 diff --git a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts index 82de717ab..e8d16dc69 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts @@ -16,6 +16,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +/** + * constructor function of any class + */ export type GenericConstructor = new (...args: any[]) => T export interface Rule { @@ -29,6 +33,27 @@ export type Rules = Record const rulesRegistry: Record = {} + +/** + * Registers a set of {@link Rules} to be used by {@link hydratedResultTransformer} 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.hydratedResultTransformer(Person, personClassRules) + * }) + * + * can instead be written: + * neo4j.mapping.register(Person, personClassRules) + * + * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { + * resultTransformer: neo4j.resultTransformers.hydratedResultTransformer(Person) + * }) + * + * + * @param {GenericConstructor} constructor The constructor function of the class to set rules for + * @param {Rules} rules The rules to set for the provided class + */ export function register (constructor: GenericConstructor, rules: Rules): void { rulesRegistry[constructor.toString()] = rules } diff --git a/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts b/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts index 50298d5ff..e2c638a13 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts @@ -18,12 +18,46 @@ */ 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. + */ export const RulesFactories = Object.freeze({ + /** + * Create a {@link Rule} that validates the value is a String. + * + * @param {Rule} rule Configurations for the rule + * @returns {Rule} A new rule for the value + */ asString (rule?: Rule): Rule { return { validate: (value, field) => { @@ -34,9 +68,18 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asNumber (rule?: Rule & { acceptBigInt?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link Number}. + * + * @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 to true 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}`) } @@ -50,7 +93,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asBigInt (rule?: Rule & { acceptNumber?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link BigInt}. + * + * @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')) { @@ -66,7 +115,23 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asNode (rule?: 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({}), + * } + * + * @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)) { @@ -76,7 +141,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asRelationship (rule?: 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)) { @@ -86,7 +157,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asUnboundRelationship (rule?: Rule) { + /** + * Create a {@link Rule} that validates the value is an {@link UnboundRelationship} + * + * @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)) { @@ -96,7 +173,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asPath (rule?: Rule) { + /** + * Create a {@link Rule} that validates the value is a {@link Path} + * + * @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)) { @@ -106,7 +189,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asPoint (rule?: Rule) { + /** + * Create a {@link Rule} that validates the value is a {@link Point} + * + * @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)) { @@ -116,7 +205,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asDuration (rule?: Rule & { toString?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link Duration} + * + * @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)) { @@ -127,7 +222,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asLocalTime (rule?: Rule & { toString?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link LocalTime} + * + * @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)) { @@ -138,7 +239,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asTime (rule?: Rule & { toString?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link Time} + * + * @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)) { @@ -149,7 +256,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asDate (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link Date} + * + * @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)) { @@ -160,7 +273,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asLocalDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link LocalDateTime} + * + * @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)) { @@ -171,7 +290,13 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asDateTime (rule?: Rule & { toString?: boolean, toStandardDate?: boolean }) { + /** + * Create a {@link Rule} that validates the value is a {@link DateTime} + * + * @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)) { @@ -182,11 +307,17 @@ export const RulesFactories = Object.freeze({ ...rule } }, - asList (rule?: Rule & { apply?: Rule }) { + /** + * Create a {@link Rule} that validates the value is a List. Optionally taking a rule for hydrating the contained values. + * + * @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 string but received ${typeof value}`) + throw new TypeError(`${field} should be a list but received ${typeof value}`) } }, convert: (list: any[], field: string) => { diff --git a/packages/neo4j-driver-deno/lib/core/result-transformers.ts b/packages/neo4j-driver-deno/lib/core/result-transformers.ts index c2ae86a13..5421b870e 100644 --- a/packages/neo4j-driver-deno/lib/core/result-transformers.ts +++ b/packages/neo4j-driver-deno/lib/core/result-transformers.ts @@ -270,8 +270,42 @@ class ResultTransformers { hydratedResultTransformer (rules: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> hydratedResultTransformer (genericConstructor: GenericConstructor, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> + /** + * Creates a {@link ResultTransformer} which maps the result to a hydrated object + * + * @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.hydratedResultTransformer(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.mapping.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.hydratedResultTransformer(Person) + * }) + * + * // A hydratedResultTransformer 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 + */ hydratedResultTransformer (constructorOrRules: GenericConstructor | Rules, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> { - return async result => await result.as(constructorOrRules as unknown as GenericConstructor, rules) + 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 8eda67f50..6c2241ae9 100644 --- a/packages/neo4j-driver-deno/lib/core/result.ts +++ b/packages/neo4j-driver-deno/lib/core/result.ts @@ -61,6 +61,8 @@ interface QueryResult { summary: ResultSummary } +export interface MappedResult extends Result> {} + /** * Interface to observe updates on the Result which is being produced. * @@ -122,6 +124,7 @@ class Result implements Promise implements Promise(rules: Rules): Promise<{ records: T[], summary: ResultSummary }> - as (genericConstructor: GenericConstructor, rules?: Rules): Promise<{ records: T[], summary: ResultSummary }> - as (constructorOrRules: GenericConstructor | Rules, rules?: Rules): Promise<{ records: T[], summary: ResultSummary }> { + as (rules: Rules): MappedResult + as (genericConstructor: GenericConstructor, rules?: Rules): MappedResult + /** + * Maps the records of this result to a provided type 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._getOrCreatePromise(r => r.as(constructorOrRules, rules)) + return this } /** @@ -223,13 +258,13 @@ class Result implements Promise (mapper: (r: Record) => O = r => r as unknown as R): Promise> { + private _getOrCreatePromise (): Promise> { if (this._p == null) { this._p = new Promise((resolve, reject) => { const records: Array> = [] const observer = { onNext: (record: Record) => { - records.push(mapper(record) as unknown as Record) + records.push(this._mapper(record) as unknown as Record) }, onCompleted: (summary: ResultSummary) => { resolve({ records, summary }) @@ -580,7 +615,11 @@ class Result implements Promise { - observer._push({ done: false, value: record }) + 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 }) diff --git a/packages/neo4j-driver/src/index.js b/packages/neo4j-driver/src/index.js index 911ad9fcd..660ecf58b 100644 --- a/packages/neo4j-driver/src/index.js +++ b/packages/neo4j-driver/src/index.js @@ -78,7 +78,10 @@ import { notificationFilterMinimumSeverityLevel, staticAuthTokenManager, clientCertificateProviders, - resolveCertificateProvider + resolveCertificateProvider, + Rules, + RulesFactories, + mapping } from 'neo4j-driver-core' import { DirectConnectionProvider, @@ -282,7 +285,8 @@ const types = { LocalDateTime, LocalTime, Time, - Integer + Integer, + Rules } /** @@ -402,7 +406,9 @@ const forExport = { notificationSeverityLevel, notificationFilterDisabledCategory, notificationFilterMinimumSeverityLevel, - clientCertificateProviders + clientCertificateProviders, + RulesFactories, + mapping } export { @@ -474,6 +480,8 @@ export { notificationFilterDisabledCategory, notificationFilterDisabledClassification, notificationFilterMinimumSeverityLevel, - clientCertificateProviders + clientCertificateProviders, + RulesFactories, + mapping } export default forExport From cf7521da468a5acb177501c07a2fb500d290d248 Mon Sep 17 00:00:00 2001 From: MaxAake <61233757+MaxAake@users.noreply.github.com> Date: Mon, 10 Mar 2025 10:15:03 +0100 Subject: [PATCH 06/12] deno sync --- .../neo4j-driver-deno/lib/core/graph-types.ts | 6 +- .../lib/core/mapping.highlevel.ts | 11 ++-- .../lib/core/mapping.rulesfactories.ts | 60 +++++++++---------- .../lib/core/result-transformers.ts | 18 +++--- packages/neo4j-driver-deno/lib/core/result.ts | 24 ++++---- 5 files changed, 59 insertions(+), 60 deletions(-) diff --git a/packages/neo4j-driver-deno/lib/core/graph-types.ts b/packages/neo4j-driver-deno/lib/core/graph-types.ts index 035828573..15d88d3ef 100644 --- a/packages/neo4j-driver-deno/lib/core/graph-types.ts +++ b/packages/neo4j-driver-deno/lib/core/graph-types.ts @@ -85,7 +85,7 @@ class Node | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration * @param {Rules} [rules] {@link Rules} for the hydration * @returns {T} @@ -218,7 +218,7 @@ class Relationship | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration * @param {Rules} [rules] {@link Rules} for the hydration * @returns {T} @@ -355,7 +355,7 @@ 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} diff --git a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts index e8d16dc69..9f751685a 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts @@ -33,24 +33,23 @@ export type Rules = Record const rulesRegistry: Record = {} - /** * Registers a set of {@link Rules} to be used by {@link hydratedResultTransformer} 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.hydratedResultTransformer(Person, personClassRules) * }) - * + * * can instead be written: * neo4j.mapping.register(Person, personClassRules) - * + * * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, { * resultTransformer: neo4j.resultTransformers.hydratedResultTransformer(Person) * }) - * - * + * + * * @param {GenericConstructor} constructor The constructor function of the class to set rules for * @param {Rules} rules The rules to set for the provided class */ diff --git a/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts b/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts index e2c638a13..b13437ae8 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.rulesfactories.ts @@ -24,37 +24,37 @@ import { Date, DateTime, Duration, LocalDateTime, LocalTime, Time, isDate, isDat /** * @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. */ export const RulesFactories = Object.freeze({ /** * Create a {@link Rule} that validates the value is a String. - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -70,7 +70,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link Number}. - * + * * @param {Rule & { acceptBigInt?: boolean }} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -78,7 +78,7 @@ export const RulesFactories = Object.freeze({ 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 to true in driver config object`) + throw new TypeError('Number returned as Object. To use asNumber mapping, set disableLosslessIntegers or useBigInt to true 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}`) @@ -95,7 +95,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link BigInt}. - * + * * @param {Rule & { acceptNumber?: boolean }} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -117,7 +117,7 @@ export const RulesFactories = Object.freeze({ }, /** * 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 @@ -127,7 +127,7 @@ export const RulesFactories = Object.freeze({ * // Returns the movie node as a Node * movie: neo4j.RulesFactories.asNode({}), * } - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -143,7 +143,7 @@ export const RulesFactories = Object.freeze({ }, /** * 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 */ @@ -159,7 +159,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is an {@link UnboundRelationship} - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -175,7 +175,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link Path} - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -191,7 +191,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link Point} - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -207,7 +207,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link Duration} - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -224,7 +224,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link LocalTime} - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -241,7 +241,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link Time} - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -258,7 +258,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link Date} - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -275,7 +275,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link LocalDateTime} - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -292,7 +292,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a {@link DateTime} - * + * * @param {Rule} rule Configurations for the rule * @returns {Rule} A new rule for the value */ @@ -309,7 +309,7 @@ export const RulesFactories = Object.freeze({ }, /** * Create a {@link Rule} that validates the value is a List. Optionally taking a rule for hydrating the contained values. - * + * * @param {Rule & { apply?: Rule }} rule Configurations for the rule * @returns {Rule} A new rule for the value */ diff --git a/packages/neo4j-driver-deno/lib/core/result-transformers.ts b/packages/neo4j-driver-deno/lib/core/result-transformers.ts index 5421b870e..dc1ff9b66 100644 --- a/packages/neo4j-driver-deno/lib/core/result-transformers.ts +++ b/packages/neo4j-driver-deno/lib/core/result-transformers.ts @@ -272,32 +272,32 @@ class ResultTransformers { hydratedResultTransformer (genericConstructor: GenericConstructor, rules?: Rules): ResultTransformer<{ records: T[], summary: ResultSummary }> /** * Creates a {@link ResultTransformer} which maps the result to a hydrated object - * + * * @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.hydratedResultTransformer(Person, personClassRules) * }) - * - * // Alternatively, the rules can be registered in the mapping registry. + * + * // Alternatively, the rules can be registered in the mapping registry. * // This registry exists in global memory and will persist even between driver instances. - * + * * neo4j.mapping.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.hydratedResultTransformer(Person) * }) - * + * * // A hydratedResultTransformer 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 diff --git a/packages/neo4j-driver-deno/lib/core/result.ts b/packages/neo4j-driver-deno/lib/core/result.ts index 6c2241ae9..bc3300048 100644 --- a/packages/neo4j-driver-deno/lib/core/result.ts +++ b/packages/neo4j-driver-deno/lib/core/result.ts @@ -158,9 +158,9 @@ class Result implements Promise(genericConstructor: GenericConstructor, rules?: Rules): MappedResult /** * Maps the records of this result to a provided type 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. - * + * + * NOTE: This modifies the Result object itself, and can not be run on a Result that is already being consumed. + * * @example * class Person { * constructor ( @@ -173,22 +173,22 @@ class Result implements Promise { - * let txres = tx.run(`MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)<-[:ACTED_IN]-(c:Person) - * WHERE id(p) <> id(c) + * 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 + * + * @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") + 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)) + this._mapper = r => r.as(constructorOrRules, rules) // @ts-expect-error return this } From 009dd4240dca78d5edf9100fa8202333f2639322 Mon Sep 17 00:00:00 2001 From: MaxAake <61233757+MaxAake@users.noreply.github.com> Date: Mon, 10 Mar 2025 11:11:54 +0100 Subject: [PATCH 07/12] mapper undef check --- packages/core/src/result.ts | 6 +++++- packages/neo4j-driver-deno/lib/core/result.ts | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/core/src/result.ts b/packages/core/src/result.ts index dcba71ee5..5ea110266 100644 --- a/packages/core/src/result.ts +++ b/packages/core/src/result.ts @@ -264,7 +264,11 @@ class Result implements Promise> = [] const observer = { onNext: (record: Record) => { - records.push(this._mapper(record) as unknown as Record) + if (this._mapper != null) { + records.push(this._mapper(record) as unknown as Record) + } else { + records.push(record as unknown as Record) + } }, onCompleted: (summary: ResultSummary) => { resolve({ records, summary }) diff --git a/packages/neo4j-driver-deno/lib/core/result.ts b/packages/neo4j-driver-deno/lib/core/result.ts index bc3300048..9595ddc4e 100644 --- a/packages/neo4j-driver-deno/lib/core/result.ts +++ b/packages/neo4j-driver-deno/lib/core/result.ts @@ -264,7 +264,12 @@ class Result implements Promise> = [] const observer = { onNext: (record: Record) => { - records.push(this._mapper(record) as unknown as Record) + if(this._mapper != null) { + records.push(this._mapper(record) as unknown as Record) + } + else { + records.push(record as unknown as Record) + } }, onCompleted: (summary: ResultSummary) => { resolve({ records, summary }) From 777c3921a3fdbd4c9823ca07daf8fb49eacccc6e Mon Sep 17 00:00:00 2001 From: MaxAake <61233757+MaxAake@users.noreply.github.com> Date: Mon, 10 Mar 2025 11:12:20 +0100 Subject: [PATCH 08/12] deno sync --- packages/neo4j-driver-deno/lib/core/result.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/neo4j-driver-deno/lib/core/result.ts b/packages/neo4j-driver-deno/lib/core/result.ts index 9595ddc4e..dfc5ba4db 100644 --- a/packages/neo4j-driver-deno/lib/core/result.ts +++ b/packages/neo4j-driver-deno/lib/core/result.ts @@ -264,10 +264,9 @@ class Result implements Promise> = [] const observer = { onNext: (record: Record) => { - if(this._mapper != null) { + if (this._mapper != null) { records.push(this._mapper(record) as unknown as Record) - } - else { + } else { records.push(record as unknown as Record) } }, From 561456d0708fd2740bc1b33be451b213686633d1 Mon Sep 17 00:00:00 2001 From: MaxAake <61233757+MaxAake@users.noreply.github.com> Date: Tue, 11 Mar 2025 08:39:00 +0100 Subject: [PATCH 09/12] initialize mapper and add namemapping --- packages/core/src/mapping.highlevel.ts | 38 +++++++++++++++--- packages/core/src/result.ts | 3 +- .../lib/core/mapping.highlevel.ts | 40 ++++++++++++++++--- packages/neo4j-driver-deno/lib/core/result.ts | 3 +- 4 files changed, 72 insertions(+), 12 deletions(-) diff --git a/packages/core/src/mapping.highlevel.ts b/packages/core/src/mapping.highlevel.ts index 9f751685a..170b5ec30 100644 --- a/packages/core/src/mapping.highlevel.ts +++ b/packages/core/src/mapping.highlevel.ts @@ -31,8 +31,18 @@ export interface Rule { export type Rules = Record +interface nameMapper { + from: (name: string) => string + to: (name: string) => string +} + const rulesRegistry: Record = {} +let nameMapping: nameMapper = { + from: (name) => name, + to: (name) => name +} + /** * Registers a set of {@link Rules} to be used by {@link hydratedResultTransformer} for the provided class when no other rules are specified. This registry exists in global memory, not the driver instance. * @@ -57,8 +67,25 @@ export function register (constructor: GenericConstructo rulesRegistry[constructor.toString()] = rules } +export function setNameMapping (newMapping: nameMapper): void { + nameMapping = newMapping +} + +export const nameMappers = { + pascalToCamel: { + from: (name: String) => name.charAt(0).toLowerCase() + name.slice(1), + to: (name: String) => name.charAt(0).toUpperCase() + name.slice(1) + }, + camelToPascal: { + from: (name: String) => name.charAt(0).toUpperCase() + name.slice(1), + to: (name: String) => name.charAt(0).toLowerCase() + name.slice(1) + } +} + export const mapping = { - register + register, + setNameMapping, + nameMappers } interface Gettable { get: (key: string) => V } @@ -72,12 +99,13 @@ export function as (gettable: Gettable, constructorOrRul for (const [key, rule] of Object.entries(theRules ?? {})) { vistedKeys.push(key) - _apply(gettable, obj, key, rule) + _apply(gettable, obj, nameMapping.to(key), rule) } for (const key of Object.getOwnPropertyNames(obj)) { - if (!vistedKeys.includes(key)) { - _apply(gettable, obj, key, theRules?.[key]) + const mappedkey = nameMapping.from(key) + if (!vistedKeys.includes(mappedkey)) { + _apply(gettable, obj, key, theRules?.[mappedkey]) } } @@ -90,7 +118,7 @@ function _apply (gettable: Gettable, obj: T, key: string, rule?: R const processedValue = valueAs(value, field, rule) // @ts-expect-error - obj[key] = processedValue ?? obj[key] + obj[nameMapping.from(key)] = processedValue ?? obj[key] } export function valueAs (value: unknown, field: string, rule?: Rule): unknown { diff --git a/packages/core/src/result.ts b/packages/core/src/result.ts index 5ea110266..ffe3d286a 100644 --- a/packages/core/src/result.ts +++ b/packages/core/src/result.ts @@ -124,7 +124,7 @@ class Result implements Promise implements Promise +type nameMapper = { + from: (name: string) => string + to: (name: string) => string +} + const rulesRegistry: Record = {} + +let nameMapping: nameMapper = { + from: (name) => name, + to: (name) => name +} + + /** * Registers a set of {@link Rules} to be used by {@link hydratedResultTransformer} for the provided class when no other rules are specified. This registry exists in global memory, not the driver instance. * @@ -57,8 +69,25 @@ export function register (constructor: GenericConstructo rulesRegistry[constructor.toString()] = rules } +export function setNameMapping(newMapping: nameMapper): void { + nameMapping = newMapping +} + +export const nameMappers = { + pascalToCamel: { + from: (name:String) => name.charAt(0).toLowerCase() + name.slice(1), + to: (name:String) => name.charAt(0).toUpperCase() + name.slice(1) + }, + camelToPascal: { + from: (name:String) => name.charAt(0).toUpperCase() + name.slice(1), + to: (name:String) => name.charAt(0).toLowerCase() + name.slice(1) + }, +} + export const mapping = { - register + register, + setNameMapping, + nameMappers } interface Gettable { get: (key: string) => V } @@ -72,12 +101,13 @@ export function as (gettable: Gettable, constructorOrRul for (const [key, rule] of Object.entries(theRules ?? {})) { vistedKeys.push(key) - _apply(gettable, obj, key, rule) + _apply(gettable, obj, nameMapping.to(key), rule) } for (const key of Object.getOwnPropertyNames(obj)) { - if (!vistedKeys.includes(key)) { - _apply(gettable, obj, key, theRules?.[key]) + const mappedkey = nameMapping.from(key) + if (!vistedKeys.includes(mappedkey)) { + _apply(gettable, obj, key, theRules?.[mappedkey]) } } @@ -90,7 +120,7 @@ function _apply (gettable: Gettable, obj: T, key: string, rule?: R const processedValue = valueAs(value, field, rule) // @ts-expect-error - obj[key] = processedValue ?? obj[key] + obj[nameMapping.from(key)] = processedValue ?? obj[key] } export function valueAs (value: unknown, field: string, rule?: Rule): unknown { diff --git a/packages/neo4j-driver-deno/lib/core/result.ts b/packages/neo4j-driver-deno/lib/core/result.ts index dfc5ba4db..204d93d6d 100644 --- a/packages/neo4j-driver-deno/lib/core/result.ts +++ b/packages/neo4j-driver-deno/lib/core/result.ts @@ -124,7 +124,7 @@ class Result implements Promise implements Promise Date: Tue, 11 Mar 2025 08:39:44 +0100 Subject: [PATCH 10/12] deny sync --- .../lib/core/mapping.highlevel.ts | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts index 6c55ddafe..170b5ec30 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts @@ -31,20 +31,18 @@ export interface Rule { export type Rules = Record -type nameMapper = { +interface nameMapper { from: (name: string) => string to: (name: string) => string } const rulesRegistry: Record = {} - -let nameMapping: nameMapper = { +let nameMapping: nameMapper = { from: (name) => name, to: (name) => name } - /** * Registers a set of {@link Rules} to be used by {@link hydratedResultTransformer} for the provided class when no other rules are specified. This registry exists in global memory, not the driver instance. * @@ -69,19 +67,19 @@ export function register (constructor: GenericConstructo rulesRegistry[constructor.toString()] = rules } -export function setNameMapping(newMapping: nameMapper): void { +export function setNameMapping (newMapping: nameMapper): void { nameMapping = newMapping } export const nameMappers = { pascalToCamel: { - from: (name:String) => name.charAt(0).toLowerCase() + name.slice(1), - to: (name:String) => name.charAt(0).toUpperCase() + name.slice(1) + from: (name: String) => name.charAt(0).toLowerCase() + name.slice(1), + to: (name: String) => name.charAt(0).toUpperCase() + name.slice(1) }, camelToPascal: { - from: (name:String) => name.charAt(0).toUpperCase() + name.slice(1), - to: (name:String) => name.charAt(0).toLowerCase() + name.slice(1) - }, + from: (name: String) => name.charAt(0).toUpperCase() + name.slice(1), + to: (name: String) => name.charAt(0).toLowerCase() + name.slice(1) + } } export const mapping = { From 7ddb87ea0b920d9270154bd8e96e362537af7c83 Mon Sep 17 00:00:00 2001 From: MaxAake <61233757+MaxAake@users.noreply.github.com> Date: Wed, 12 Mar 2025 11:42:17 +0100 Subject: [PATCH 11/12] improved name mappers --- packages/core/src/mapping.highlevel.ts | 44 +++++++++---------- packages/core/src/mapping.nameconventions.ts | 43 ++++++++++++++++++ .../lib/core/mapping.highlevel.ts | 43 +++++++++--------- .../lib/core/mapping.nameconventions.ts | 43 ++++++++++++++++++ 4 files changed, 130 insertions(+), 43 deletions(-) create mode 100644 packages/core/src/mapping.nameconventions.ts create mode 100644 packages/neo4j-driver-deno/lib/core/mapping.nameconventions.ts diff --git a/packages/core/src/mapping.highlevel.ts b/packages/core/src/mapping.highlevel.ts index 170b5ec30..12725a881 100644 --- a/packages/core/src/mapping.highlevel.ts +++ b/packages/core/src/mapping.highlevel.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +import { NameConvention, nameConventions } from './mapping.nameconventions' + /** * constructor function of any class */ @@ -32,15 +34,15 @@ export interface Rule { export type Rules = Record interface nameMapper { - from: (name: string) => string - to: (name: string) => string + from: NameConvention | undefined + to: NameConvention | undefined } const rulesRegistry: Record = {} -let nameMapping: nameMapper = { - from: (name) => name, - to: (name) => name +const nameMapping: nameMapper = { + from: undefined, + to: undefined } /** @@ -67,25 +69,19 @@ export function register (constructor: GenericConstructo rulesRegistry[constructor.toString()] = rules } -export function setNameMapping (newMapping: nameMapper): void { - nameMapping = newMapping +export function setDatabaseNameMapping (newMapping: NameConvention): void { + nameMapping.from = newMapping } -export const nameMappers = { - pascalToCamel: { - from: (name: String) => name.charAt(0).toLowerCase() + name.slice(1), - to: (name: String) => name.charAt(0).toUpperCase() + name.slice(1) - }, - camelToPascal: { - from: (name: String) => name.charAt(0).toUpperCase() + name.slice(1), - to: (name: String) => name.charAt(0).toLowerCase() + name.slice(1) - } +export function setCodeNameMapping (newMapping: NameConvention): void { + nameMapping.to = newMapping } export const mapping = { register, - setNameMapping, - nameMappers + setDatabaseNameMapping, + setCodeNameMapping, + nameConventions } interface Gettable { get: (key: string) => V } @@ -99,11 +95,15 @@ export function as (gettable: Gettable, constructorOrRul for (const [key, rule] of Object.entries(theRules ?? {})) { vistedKeys.push(key) - _apply(gettable, obj, nameMapping.to(key), rule) + if (nameMapping.from !== undefined && nameMapping.to !== undefined) { + _apply(gettable, obj, nameMapping.from.encode(nameMapping.to.tokenize(key)), rule) + } else { + _apply(gettable, obj, key, rule) + } } for (const key of Object.getOwnPropertyNames(obj)) { - const mappedkey = nameMapping.from(key) + const mappedkey = (nameMapping.from !== undefined && nameMapping.to !== undefined) ? nameMapping.to.encode(nameMapping.from.tokenize(key)) : key if (!vistedKeys.includes(mappedkey)) { _apply(gettable, obj, key, theRules?.[mappedkey]) } @@ -116,9 +116,9 @@ function _apply (gettable: Gettable, obj: T, key: string, rule?: R const value = gettable.get(rule?.from ?? key) const field = `${obj.constructor.name}#${key}` const processedValue = valueAs(value, field, rule) - + const mappedkey = (nameMapping.from !== undefined && nameMapping.to !== undefined) ? nameMapping.to.encode(nameMapping.from.tokenize(key)) : key // @ts-expect-error - obj[nameMapping.from(key)] = processedValue ?? obj[key] + obj[mappedkey] = processedValue ?? obj[key] } export function valueAs (value: unknown, field: string, rule?: Rule): unknown { diff --git a/packages/core/src/mapping.nameconventions.ts b/packages/core/src/mapping.nameconventions.ts new file mode 100644 index 000000000..73c01aad8 --- /dev/null +++ b/packages/core/src/mapping.nameconventions.ts @@ -0,0 +1,43 @@ +export interface NameConvention { + tokenize: (name: string) => string[] + encode: (tokens: string[]) => string +} + +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 + } + }, + SNAKE_CAPS: { + 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.highlevel.ts b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts index 170b5ec30..fef101ab0 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +import { NameConvention, nameConventions } from './mapping.nameconventions.ts' + /** * constructor function of any class */ @@ -32,15 +34,15 @@ export interface Rule { export type Rules = Record interface nameMapper { - from: (name: string) => string - to: (name: string) => string + from: NameConvention | undefined + to: NameConvention | undefined } const rulesRegistry: Record = {} let nameMapping: nameMapper = { - from: (name) => name, - to: (name) => name + from: undefined, + to: undefined } /** @@ -67,25 +69,19 @@ export function register (constructor: GenericConstructo rulesRegistry[constructor.toString()] = rules } -export function setNameMapping (newMapping: nameMapper): void { - nameMapping = newMapping +export function setDatabaseNameMapping (newMapping: NameConvention): void { + nameMapping.from = newMapping } -export const nameMappers = { - pascalToCamel: { - from: (name: String) => name.charAt(0).toLowerCase() + name.slice(1), - to: (name: String) => name.charAt(0).toUpperCase() + name.slice(1) - }, - camelToPascal: { - from: (name: String) => name.charAt(0).toUpperCase() + name.slice(1), - to: (name: String) => name.charAt(0).toLowerCase() + name.slice(1) - } +export function setCodeNameMapping (newMapping: NameConvention): void { + nameMapping.to = newMapping } export const mapping = { register, - setNameMapping, - nameMappers + setDatabaseNameMapping, + setCodeNameMapping, + nameConventions, } interface Gettable { get: (key: string) => V } @@ -99,11 +95,16 @@ export function as (gettable: Gettable, constructorOrRul for (const [key, rule] of Object.entries(theRules ?? {})) { vistedKeys.push(key) - _apply(gettable, obj, nameMapping.to(key), rule) + if(nameMapping.from !== undefined && nameMapping.to !== undefined) { + _apply(gettable, obj, nameMapping.from.encode(nameMapping.to.tokenize(key)), rule) + } + else { + _apply(gettable, obj, key, rule) + } } for (const key of Object.getOwnPropertyNames(obj)) { - const mappedkey = nameMapping.from(key) + const mappedkey = (nameMapping.from !== undefined && nameMapping.to !== undefined) ? nameMapping.to.encode(nameMapping.from.tokenize(key)) : key if (!vistedKeys.includes(mappedkey)) { _apply(gettable, obj, key, theRules?.[mappedkey]) } @@ -116,9 +117,9 @@ function _apply (gettable: Gettable, obj: T, key: string, rule?: R const value = gettable.get(rule?.from ?? key) const field = `${obj.constructor.name}#${key}` const processedValue = valueAs(value, field, rule) - + const mappedkey = (nameMapping.from !== undefined && nameMapping.to !== undefined) ? nameMapping.to.encode(nameMapping.from.tokenize(key)) : key // @ts-expect-error - obj[nameMapping.from(key)] = processedValue ?? obj[key] + obj[mappedkey] = processedValue ?? obj[key] } export function valueAs (value: unknown, field: string, rule?: Rule): unknown { 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..26c54bd31 --- /dev/null +++ b/packages/neo4j-driver-deno/lib/core/mapping.nameconventions.ts @@ -0,0 +1,43 @@ +export type NameConvention = { + tokenize: (name: string) => Array + encode: (tokens: Array) => string +} + +export const nameConventions = { + "snake_case": { + tokenize: (name: string) => name.split("_"), + encode: (tokens: Array) => tokens.join("_") + }, + "kebab-case": { + tokenize: (name: string) => name.split("-"), + encode: (tokens: Array) => tokens.join("-") + }, + "PascalCase": { + tokenize: (name: string) => name.split(/(?=[A-Z])/).map((token) => token.toLowerCase()), + encode: (tokens: Array) => { + let name:string = "" + for (var 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: Array) => { + let name:string = "" + for (var [i, token] of tokens.entries()) { + if( i !== 0) { + token = token.charAt(0).toUpperCase() + token.slice(1) + } + name += token + } + return name + } + }, + "SNAKE_CAPS": { + tokenize: (name: string) => name.split("_").map((token) => token.toLowerCase()), + encode: (tokens: Array) => tokens.join("_").toUpperCase() + } +} From 65d2c56870db85c7591b05b855a7b5ae3ba251f2 Mon Sep 17 00:00:00 2001 From: MaxAake <61233757+MaxAake@users.noreply.github.com> Date: Wed, 12 Mar 2025 11:42:58 +0100 Subject: [PATCH 12/12] deno sync --- .../lib/core/mapping.highlevel.ts | 9 +-- .../lib/core/mapping.nameconventions.ts | 74 +++++++++---------- 2 files changed, 41 insertions(+), 42 deletions(-) diff --git a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts index fef101ab0..bd5d6a460 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.highlevel.ts @@ -40,7 +40,7 @@ interface nameMapper { const rulesRegistry: Record = {} -let nameMapping: nameMapper = { +const nameMapping: nameMapper = { from: undefined, to: undefined } @@ -81,7 +81,7 @@ export const mapping = { register, setDatabaseNameMapping, setCodeNameMapping, - nameConventions, + nameConventions } interface Gettable { get: (key: string) => V } @@ -95,10 +95,9 @@ export function as (gettable: Gettable, constructorOrRul for (const [key, rule] of Object.entries(theRules ?? {})) { vistedKeys.push(key) - if(nameMapping.from !== undefined && nameMapping.to !== undefined) { + if (nameMapping.from !== undefined && nameMapping.to !== undefined) { _apply(gettable, obj, nameMapping.from.encode(nameMapping.to.tokenize(key)), rule) - } - else { + } else { _apply(gettable, obj, key, rule) } } diff --git a/packages/neo4j-driver-deno/lib/core/mapping.nameconventions.ts b/packages/neo4j-driver-deno/lib/core/mapping.nameconventions.ts index 26c54bd31..73c01aad8 100644 --- a/packages/neo4j-driver-deno/lib/core/mapping.nameconventions.ts +++ b/packages/neo4j-driver-deno/lib/core/mapping.nameconventions.ts @@ -1,43 +1,43 @@ -export type NameConvention = { - tokenize: (name: string) => Array - encode: (tokens: Array) => string +export interface NameConvention { + tokenize: (name: string) => string[] + encode: (tokens: string[]) => string } export const nameConventions = { - "snake_case": { - tokenize: (name: string) => name.split("_"), - encode: (tokens: Array) => tokens.join("_") - }, - "kebab-case": { - tokenize: (name: string) => name.split("-"), - encode: (tokens: Array) => tokens.join("-") - }, - "PascalCase": { - tokenize: (name: string) => name.split(/(?=[A-Z])/).map((token) => token.toLowerCase()), - encode: (tokens: Array) => { - let name:string = "" - for (var 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: Array) => { - let name:string = "" - for (var [i, token] of tokens.entries()) { - if( i !== 0) { - token = token.charAt(0).toUpperCase() + token.slice(1) - } - name += token - } - return name + 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) } - }, - "SNAKE_CAPS": { - tokenize: (name: string) => name.split("_").map((token) => token.toLowerCase()), - encode: (tokens: Array) => tokens.join("_").toUpperCase() + name += token + } + return name } + }, + SNAKE_CAPS: { + tokenize: (name: string) => name.split('_').map((token) => token.toLowerCase()), + encode: (tokens: string[]) => tokens.join('_').toUpperCase() + } }