neo4j / neo4j-javascript-driver

Neo4j Bolt driver for JavaScript
https://neo4j.com/docs/javascript-manual/current/
Apache License 2.0
839 stars 148 forks source link

Introduce driver level Hydration and Dehydration hooks #1157

Open bigmontz opened 8 months ago

bigmontz commented 8 months ago

This hooks enable driver users to globaly map their own data types to Neo4j driver types and vice-versa.

Example:

import neo4j, { DateTime } from 'neo4j-driver'

const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'password'), {
    // converting types came from the Datebase
    hydrationHooks: {
        // converting neo4j.DateTime to ISO String, 
        // but you might also convert to some library
        DateTime: (datetime) => datetime.toString()
    },
    // Converting type which user supplied to neo4j types
    dehydrationHooks: [
        // Define a dehydration hook from javascript Date
        {
            // Checking if the type is instance of Date
            isTypeInstance: maybeStdDate => maybeStdDate instanceof Date,
            // Called when a types is Date and need to converted/dehydrated
            dehydrate: stdDate => DateTime.fromStandardDate(stdDate)
        }
    ]
})

const { records: [record]  } = await driver.executeQuery("RETURN $now AS now", { now: new Date()})
console.log(`Now is ${record.get('now')}`)

await driver.close()

The driver is able to hydrate Duration, LocalTime, LocalDateTime, Time, Date, DateTime and Point. Other types will not able to be hydrated since they are used by driver internals and the hydration step occurs while data is being received from the socket.

Dehydration, in other hand, can be done from any data type since it got converted to types which driver can understand.