You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add generics and type mapping to Result, Session.run and Transaction.run (#1010)
The new generic typing allow mapping the records of these running queries to type-mapped Record.
Given the following Person and Friendship definitions.
```typescript
interface Person {
age: Integer
name: string
}
interface Friendship {
since: Integer
}
interface PersonAndFriendship {
p: Node<number, Person>
f: Relationship<number, Friendship>
}
```
The new type-mapping allow safe access the properties of query which return `Record<Person>`
```typescript
const { records } = await session.run<Person>('MATCH (p:Person) RETURN p.name as name, p.age as age')
for (const person of records) {
const age: Integer = person.get('age')
const name: string = person.get('name')
// @ts-expect-error
const nameInt: Integer = person.get('name')
}
```
The type-mapping can be also extended for `Node` and `Relationship`.
```typescript
const { records } = await session.run<PersonAndFriendship>('MATCH (p:Person)-[f:Friendship]-() RETURN p, f')
for (const r of records) {
const person = r.get('p')
const age: Integer = person.properties.age
const name: string = person.properties.name
// @ts-expect-error
const nameInt: Integer = person.properties.name
// @ts-expect-error
const err: string = person.properties.err
const friendship = r.get('f')
const since: Integer = friendship.properties.since
// @ts-expect-error
const sinceString: string = friendship.properties.since
// @ts-expect-error
const err2: string = friendship.properties.err
}
```
The usage in combination with `executeRead` and `executeWrite` is also possible.
```typescript
const { records } = await session.executeRead(tx => tx.run<Person>('MATCH (p:Person) RETURN p.name as name, p.age as age'))
for (const person of records) {
const age: Integer = person.get('age')
const name: string = person.get('name')
// @ts-expect-error
const nameInt: Integer = person.get('name')
}
```
With some async iterator usage:
```typescript
const personList = await session.executeRead(async (tx) => {
const result = tx.run<Person>('MATCH (p:Person) RETURN p.name as name, p.age as age')
const objects: Person[] = []
// iterate while streaming the objects
for await (const record of result) {
objects.push(record.toObject())
}
return objects
})
for (const person of personList) {
const age: Integer = person.age
const name: string = person.name
// @ts-expect-error
const nameInt: Integer = person.name
// @ts-expect-error
const nome: string = person.nome
}
```
⚠️ This type definitions are not asserted in runtime. Thus mismatched type records coming from the database will not trigger type errors.
0 commit comments