Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce Result, Record and Graph types mapping #1248

Draft
wants to merge 13 commits into
base: 6.x
Choose a base branch
from
49 changes: 49 additions & 0 deletions packages/core/src/graph-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/
import Integer from './integer'
import { stringify } from './json'
import { Rules, GenericConstructor, as } from './mapping.highlevel'

type StandardDate = Date
/**
Expand Down Expand Up @@ -82,6 +83,22 @@ class Node<T extends NumberOrInteger = Integer, P extends Properties = Propertie
this.elementId = _valueOrGetDefault(elementId, () => identity.toString())
}

/**
* Hydrates an object of a given type with the properties of the node
*
* @param {GenericConstructor<T> | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration
* @param {Rules} [rules] {@link Rules} for the hydration
* @returns {T}
*/
as <T extends {} = Object>(rules: Rules): T
as <T extends {} = Object>(genericConstructor: GenericConstructor<T>): T
as <T extends {} = Object>(genericConstructor: GenericConstructor<T>, rules?: Rules): T
as <T extends {} = Object>(constructorOrRules: GenericConstructor<T> | Rules, rules?: Rules): T {
return as({
get: (key) => this.properties[key]
}, constructorOrRules, rules)
}

/**
* @ignore
*/
Expand Down Expand Up @@ -199,6 +216,22 @@ class Relationship<T extends NumberOrInteger = Integer, P extends Properties = P
this.endNodeElementId = _valueOrGetDefault(endNodeElementId, () => end.toString())
}

/**
* Hydrates an object of a given type with the properties of the relationship
*
* @param {GenericConstructor<T> | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration
* @param {Rules} [rules] {@link Rules} for the hydration
* @returns {T}
*/
as <T extends {} = Object>(rules: Rules): T
as <T extends {} = Object>(genericConstructor: GenericConstructor<T>): T
as <T extends {} = Object>(genericConstructor: GenericConstructor<T>, rules?: Rules): T
as <T extends {} = Object>(constructorOrRules: GenericConstructor<T> | Rules, rules?: Rules): T {
return as({
get: (key) => this.properties[key]
}, constructorOrRules, rules)
}

/**
* @ignore
*/
Expand Down Expand Up @@ -320,6 +353,22 @@ class UnboundRelationship<T extends NumberOrInteger = Integer, P extends Propert
)
}

/**
* Hydrates an object of a given type with the properties of the relationship
*
* @param {GenericConstructor<T> | Rules} constructorOrRules Contructor for the desired type or {@link Rules} for the hydration
* @param {Rules} [rules] {@link Rules} for the hydration
* @returns {T}
*/
as <T extends {} = Object>(rules: Rules): T
as <T extends {} = Object>(genericConstructor: GenericConstructor<T>): T
as <T extends {} = Object>(genericConstructor: GenericConstructor<T>, rules?: Rules): T
as <T extends {} = Object>(constructorOrRules: GenericConstructor<T> | Rules, rules?: Rules): T {
return as({
get: (key) => this.properties[key]
}, constructorOrRules, rules)
}

/**
* @ignore
*/
Expand Down
14 changes: 11 additions & 3 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ import * as json from './json'
import resultTransformers, { ResultTransformer } from './result-transformers'
import ClientCertificate, { clientCertificateProviders, ClientCertificateProvider, ClientCertificateProviders, RotatingClientCertificateProvider, resolveCertificateProvider } from './client-certificate'
import * as internal from './internal' // todo: removed afterwards
import { Rule, Rules, mapping } from './mapping.highlevel'
import { RulesFactories } from './mapping.rulesfactories'

/**
* Object containing string constants representing predefined {@link Neo4jError} codes.
Expand Down Expand Up @@ -186,7 +188,9 @@ const forExport = {
notificationFilterDisabledClassification,
notificationFilterMinimumSeverityLevel,
clientCertificateProviders,
resolveCertificateProvider
resolveCertificateProvider,
RulesFactories,
mapping
}

export {
Expand Down Expand Up @@ -263,7 +267,9 @@ export {
notificationFilterDisabledClassification,
notificationFilterMinimumSeverityLevel,
clientCertificateProviders,
resolveCertificateProvider
resolveCertificateProvider,
RulesFactories,
mapping
}

export type {
Expand Down Expand Up @@ -294,7 +300,9 @@ export type {
ClientCertificate,
ClientCertificateProvider,
ClientCertificateProviders,
RotatingClientCertificateProvider
RotatingClientCertificateProvider,
Rule,
Rules
}

export default forExport
142 changes: 142 additions & 0 deletions packages/core/src/mapping.highlevel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/**
* 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 { NameConvention, nameConventions } from './mapping.nameconventions'

/**
* constructor function of any class
*/
export type GenericConstructor<T extends {}> = 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<string, Rule>

interface nameMapper {
from: NameConvention | undefined
to: NameConvention | undefined
}

const rulesRegistry: Record<string, Rules> = {}

const nameMapping: nameMapper = {
from: undefined,
to: undefined
}

/**
* 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 <T extends {} = Object> (constructor: GenericConstructor<T>, rules: Rules): void {
rulesRegistry[constructor.toString()] = rules
}

export function setDatabaseNameMapping (newMapping: NameConvention): void {
nameMapping.from = newMapping
}

export function setCodeNameMapping (newMapping: NameConvention): void {
nameMapping.to = newMapping
}

export const mapping = {
register,
setDatabaseNameMapping,
setCodeNameMapping,
nameConventions
}

interface Gettable { get: <V>(key: string) => V }

export function as <T extends {} = Object> (gettable: Gettable, constructorOrRules: GenericConstructor<T> | Rules, rules?: Rules): T {
const GenericConstructor = typeof constructorOrRules === 'function' ? constructorOrRules : Object
const theRules = getRules(constructorOrRules, rules)
const vistedKeys: string[] = []

const obj = new GenericConstructor()

for (const [key, rule] of Object.entries(theRules ?? {})) {
vistedKeys.push(key)
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 !== undefined && nameMapping.to !== undefined) ? nameMapping.to.encode(nameMapping.from.tokenize(key)) : key
if (!vistedKeys.includes(mappedkey)) {
_apply(gettable, obj, key, theRules?.[mappedkey])
}
}

return obj as unknown as T
}

function _apply<T extends {}> (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)
const mappedkey = (nameMapping.from !== undefined && nameMapping.to !== undefined) ? nameMapping.to.encode(nameMapping.from.tokenize(key)) : key
// @ts-expect-error
obj[mappedkey] = processedValue ?? obj[key]
}

export function valueAs (value: unknown, field: string, rule?: Rule): unknown {
if (rule?.optional === true && value == null) {
return value
}

if (typeof rule?.validate === 'function') {
rule.validate(value, field)
}

return ((rule?.convert) != null) ? rule.convert(value, field) : value
}
function getRules<T extends {} = Object> (constructorOrRules: Rules | GenericConstructor<T>, 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
}
43 changes: 43 additions & 0 deletions packages/core/src/mapping.nameconventions.ts
Original file line number Diff line number Diff line change
@@ -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()
}
}
Loading