Skip to content
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
10 changes: 7 additions & 3 deletions packages/feathers/fixtures/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@ export class ResponseTestService {
})
}

async *get(id: string) {
for (let i = 1; i <= 5; i++) {
yield { message: `Hello ${id} ${i}` }
async get(id: string) {
const generator = async function* () {
for (let i = 1; i <= 5; i++) {
yield { message: `Hello ${id} ${i}` }
}
}

return generator()
}

async options(_params: Params) {
Expand Down
6 changes: 3 additions & 3 deletions packages/feathers/src/client/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,11 @@ describe('fetch REST connector', function () {
await expect(() => service.internalMethod({})).rejects.toThrow(MethodNotAllowed)
})

it('supports event streams', async () => {
it('supports async iterable streams', async () => {
const messages: any[] = []
const stream = await app.service('test').get('test')

// TODO investigate need for additional await
for await (const data of await app.service('test').get('test')) {
for await (const data of stream) {
messages.push(data)
}

Expand Down
13 changes: 13 additions & 0 deletions packages/feathers/src/hooks/function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -485,4 +485,17 @@ describe('feathers/hooks function', () => {
assert.strictEqual(await fn('Dave'), 'Hello Dave')
assert.strictEqual(await fn(), 'Hello Bertho')
})

it('returning an async iterator directly errors', () => {
const iterable = async function* () {
yield 'Hello'
yield 'World'
}

const fn = hooks(iterable, [])

expect(() => fn()).rejects.toThrow(
'Function must return a Promise that resolves to an async iterable, not the iterable directly'
)
})
})
10 changes: 9 additions & 1 deletion packages/feathers/src/hooks/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,15 @@ export function functionHooks<F>(fn: F, managerOrMiddleware: HookOptions) {
// Runs the actual original method if `ctx.result` is not already set
hookChain.push((ctx, next) => {
if (!Object.prototype.hasOwnProperty.call(context, 'result')) {
return Promise.resolve(original.apply(this, ctx.arguments)).then((result) => {
const returnValue = original.apply(this, ctx.arguments)

if (returnValue[Symbol.asyncIterator]) {
throw new Error(
'Function must return a Promise that resolves to an async iterable, not the iterable directly'
)
}

return Promise.resolve(returnValue).then((result) => {
ctx.result = result

return next()
Expand Down
Loading