Skip to content

Introduce resultTransformer.first #1200

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

Merged
merged 1 commit into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 51 additions & 6 deletions packages/core/src/result-transformers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,6 @@ import EagerResult from './result-eager'
import ResultSummary from './result-summary'
import { newError } from './error'

async function createEagerResultFromResult<Entries extends RecordShape> (result: Result): Promise<EagerResult<Entries>> {
const { summary, records } = await result
const keys = await result.keys()
return new EagerResult<Entries>(keys, records, summary)
}

type ResultTransformer<T> = (result: Result) => Promise<T>
/**
* Protocol for transforming {@link Result}.
Expand Down Expand Up @@ -162,6 +156,31 @@ class ResultTransformers {
})
}
}

/**
* Creates a {@link ResultTransformer} which collects the first record {@link Record} of {@link Result}
* and discard the rest of the records, if existent.
*
* @example
* // Using in executeQuery
* const maybeFirstRecord = await driver.executeQuery('MATCH (p:Person{ age: $age }) RETURN p.name as name', { age: 25 }, {
* resultTransformer: neo4j.resultTransformers.first()
* })
*
* @example
* // Using in other results
* const record = await neo4j.resultTransformers.first()(result)
*
*
* @template Entries The shape of the record.
* @returns {ResultTransformer<Record<Entries>|undefined>} The result transformer
* @see {@link Driver#executeQuery}
* @experimental This is a preview feature.
* @since 5.22.0
*/
first<Entries extends RecordShape = RecordShape>(): ResultTransformer<Record<Entries> | undefined> {
return first
}
}

/**
Expand All @@ -176,3 +195,29 @@ export default resultTransformers
export type {
ResultTransformer
}

async function createEagerResultFromResult<Entries extends RecordShape> (result: Result): Promise<EagerResult<Entries>> {
const { summary, records } = await result
const keys = await result.keys()
return new EagerResult<Entries>(keys, records, summary)
}

async function first<Entries extends RecordShape> (result: Result): Promise<Record<Entries> | undefined> {
// The async iterator is not used in the for await fashion
// because the transpiler is generating a code which
// doesn't call it.return when break the loop
// causing the method hanging when fetchSize > recordNumber.
const it = result[Symbol.asyncIterator]()
const { value, done } = await it.next()

try {
if (done === true) {
return undefined
}
return value
} finally {
if (it.return != null) {
await it.return()
}
}
}
94 changes: 94 additions & 0 deletions packages/core/test/result-transformers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,4 +267,98 @@ describe('resultTransformers', () => {
})
})
})

describe('.first', () => {
describe('with a valid result', () => {
it('should return an single Record', async () => {
const resultStreamObserverMock = new ResultStreamObserverMock()
const query = 'Query'
const params = { a: 1 }
const meta = { db: 'adb' }
const result = new Result(Promise.resolve(resultStreamObserverMock), query, params)
const keys = ['a', 'b']
const rawRecord1 = [1, 2]
resultStreamObserverMock.onKeys(keys)
resultStreamObserverMock.onNext(rawRecord1)
resultStreamObserverMock.onCompleted(meta)

const record = await resultTransformers.first()(result)

expect(record).toEqual(new Record(keys, rawRecord1))
})

it('it should return an undefined when empty', async () => {
const resultStreamObserverMock = new ResultStreamObserverMock()
const query = 'Query'
const params = { a: 1 }
const meta = { db: 'adb' }
const result = new Result(Promise.resolve(resultStreamObserverMock), query, params)
const keys = ['a', 'b']
resultStreamObserverMock.onKeys(keys)
resultStreamObserverMock.onCompleted(meta)

const record = await resultTransformers.first()(result)

expect(record).toEqual(undefined)
})

it('should return a type-safe single Record', async () => {
interface Car {
model: string
year: number
}
const resultStreamObserverMock = new ResultStreamObserverMock()
const query = 'Query'
const params = { a: 1 }
const meta = { db: 'adb' }
const result = new Result(Promise.resolve(resultStreamObserverMock), query, params)
const keys = ['model', 'year']
const rawRecord1 = ['Beautiful Sedan', 1987]

resultStreamObserverMock.onKeys(keys)
resultStreamObserverMock.onNext(rawRecord1)
resultStreamObserverMock.onCompleted(meta)
const record = await resultTransformers.first<Car>()(result)

expect(record).toEqual(new Record(keys, rawRecord1))

const car = record?.toObject()

expect(car?.model).toEqual(rawRecord1[0])
expect(car?.year).toEqual(rawRecord1[1])
})

it('should return an single Record', async () => {
const meta = { db: 'adb' }
const resultStreamObserverMock = new ResultStreamObserverMock()
const cancelSpy = jest.spyOn(resultStreamObserverMock, 'cancel')
cancelSpy.mockImplementation(() => resultStreamObserverMock.onCompleted(meta))

const query = 'Query'
const params = { a: 1 }
const result = new Result(Promise.resolve(resultStreamObserverMock), query, params)
const keys = ['a', 'b']
const rawRecord1 = [1, 2]
const rawRecord2 = [1, 2]
resultStreamObserverMock.onKeys(keys)
resultStreamObserverMock.onNext(rawRecord1)
resultStreamObserverMock.onNext(rawRecord2)

const record = await resultTransformers.first()(result)

await new Promise(resolve => setTimeout(resolve, 100))
expect(record).toEqual(new Record(keys, rawRecord1))
expect(cancelSpy).toHaveBeenCalledTimes(1)
})
})

describe('when results fail', () => {
it('should propagate the exception', async () => {
const expectedError = newError('expected error')
const result = new Result(Promise.reject(expectedError), 'query')

await expect(resultTransformers.first()(result)).rejects.toThrow(expectedError)
})
})
})
})
57 changes: 51 additions & 6 deletions packages/neo4j-driver-deno/lib/core/result-transformers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,6 @@ import EagerResult from './result-eager.ts'
import ResultSummary from './result-summary.ts'
import { newError } from './error.ts'

async function createEagerResultFromResult<Entries extends RecordShape> (result: Result): Promise<EagerResult<Entries>> {
const { summary, records } = await result
const keys = await result.keys()
return new EagerResult<Entries>(keys, records, summary)
}

type ResultTransformer<T> = (result: Result) => Promise<T>
/**
* Protocol for transforming {@link Result}.
Expand Down Expand Up @@ -162,6 +156,31 @@ class ResultTransformers {
})
}
}

/**
* Creates a {@link ResultTransformer} which collects the first record {@link Record} of {@link Result}
* and discard the rest of the records, if existent.
*
* @example
* // Using in executeQuery
* const maybeFirstRecord = await driver.executeQuery('MATCH (p:Person{ age: $age }) RETURN p.name as name', { age: 25 }, {
* resultTransformer: neo4j.resultTransformers.first()
* })
*
* @example
* // Using in other results
* const record = await neo4j.resultTransformers.first()(result)
*
*
* @template Entries The shape of the record.
* @returns {ResultTransformer<Record<Entries>|undefined>} The result transformer
* @see {@link Driver#executeQuery}
* @experimental This is a preview feature.
* @since 5.22.0
*/
first<Entries extends RecordShape = RecordShape>(): ResultTransformer<Record<Entries> | undefined> {
return first
}
}

/**
Expand All @@ -176,3 +195,29 @@ export default resultTransformers
export type {
ResultTransformer
}

async function createEagerResultFromResult<Entries extends RecordShape> (result: Result): Promise<EagerResult<Entries>> {
const { summary, records } = await result
const keys = await result.keys()
return new EagerResult<Entries>(keys, records, summary)
}

async function first<Entries extends RecordShape> (result: Result): Promise<Record<Entries> | undefined> {
// The async iterator is not used in the for await fashion
// because the transpiler is generating a code which
// doesn't call it.return when break the loop
// causing the method hanging when fetchSize > recordNumber.
const it = result[Symbol.asyncIterator]()
const { value, done } = await it.next()

try {
if (done === true) {
return undefined
}
return value
} finally {
if (it.return != null) {
await it.return()
}
}
}