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

Feature: sync resolvers #3504

Draft
wants to merge 2 commits into
base: dove
Choose a base branch
from
Draft
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
88 changes: 85 additions & 3 deletions packages/schema/src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
* @returns The property resolver function
*/
export const virtual = <T, V, C>(virtualResolver: VirtualResolver<T, V, C>) => {
const propertyResolver: PropertyResolver<T, V, C> = async (_value, obj, context, status) =>
const propertyResolver: PropertyResolver<T, V, C> = (_value, obj, context, status) =>
virtualResolver(obj, context, status)

propertyResolver[IS_VIRTUAL] = true
Expand Down Expand Up @@ -90,12 +90,12 @@
* @param status The current resolver status
* @returns The resolver property
*/
async resolveProperty<D, K extends keyof T>(
resolveProperty<D, K extends keyof T>(
name: K,
data: D,
context: C,
status: Partial<ResolverStatus<T, C>> = {}
): Promise<T[K]> {
): PromiseOrLiteral<T[K]> {
const resolver = this.options.properties[name]
const value = (data as any)[name]
const { path = [], stack = [] } = status || {}
Expand Down Expand Up @@ -178,6 +178,88 @@

return schema && validate === 'after' ? await schema.validate(result) : result
}

async _resolve<D>(_data: D, context: C, status?: Partial<ResolverStatus<T, C>>): Promise<T> {
const { properties: resolvers, schema, validate } = this.options
const payload = await this.convert(_data, context, status)

if (!Array.isArray(status?.properties) && this.propertyNames.length === 0) {
return payload as T
}

const data = schema && validate === 'before' ? await schema.validate(payload) : payload
const propertyList = (
Array.isArray(status?.properties)
? status?.properties
: // By default get all data and resolver keys but remove duplicates
[...new Set(Object.keys(data).concat(this.propertyNames as string[]))]
) as (keyof T)[]

const result: any = {}
const errors: any = {}
let hasErrors = false

const resolveProperties = () => {
return new Promise((resolve) => {
for (let index = 0; index < propertyList.length; index++) {
const name = propertyList[index]
const value = (data as any)[name]

const handleResolve = (resolvedValue: any) => {
if (resolvedValue !== undefined) {
result[name] = resolvedValue
}
if (index === propertyList.length - 1) {
resolve(null)
}
}

const handleReject = (error: any) => {
// TODO add error stacks
const convertedError =
typeof error.toJSON === 'function' ? error.toJSON() : { message: error.message || error }

errors[name] = convertedError
hasErrors = true

if (index === propertyList.length - 1) {
resolve(null)
}
}

if (!resolvers[name]) {
handleResolve(value)
continue
}

try {
const resolved = this.resolveProperty(name, data, context, status)
// @ts-ignore

Check failure on line 237 in packages/schema/src/resolver.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

Use "@ts-expect-error" instead of "@ts-ignore", as "@ts-ignore" will do nothing if the following line is error-free

Check failure on line 237 in packages/schema/src/resolver.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

Use "@ts-expect-error" instead of "@ts-ignore", as "@ts-ignore" will do nothing if the following line is error-free
if (typeof resolved.then === 'function') {
resolved
// @ts-ignore

Check failure on line 240 in packages/schema/src/resolver.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

Use "@ts-expect-error" instead of "@ts-ignore", as "@ts-ignore" will do nothing if the following line is error-free

Check failure on line 240 in packages/schema/src/resolver.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

Use "@ts-expect-error" instead of "@ts-ignore", as "@ts-ignore" will do nothing if the following line is error-free
.then(handleResolve)
.catch(handleReject)
} else {
handleResolve(resolved)
}
} catch (error: any) {
handleReject(error)
}
}
})
}

await resolveProperties()

if (hasErrors) {
const propertyName = status?.properties ? ` ${status.properties.join('.')}` : ''

throw new BadRequest('Error resolving data' + (propertyName ? ` ${propertyName}` : ''), errors)
}

return schema && validate === 'after' ? await schema.validate(result) : result
}
}

/**
Expand Down
46 changes: 46 additions & 0 deletions packages/schema/test/resolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,4 +217,50 @@ describe('@feathersjs/schema/resolver', () => {

assert.deepStrictEqual(resolved, { message: 'Hello' })
})

it('optimizes promises', async () => {
const count = 10000
const asyncResolvers = 1
const syncResolvers = 10
const runs = 10
const properties: { [key: string]: any } = {}

for (let i = 0; i < asyncResolvers; i++) {
properties[`async${i}`] = async (_value: any, data: any) => {
return data.id
}
}

for (let i = 0; i < syncResolvers; i++) {
properties[`sync${i}`] = (_value: any, data: any) => {
return data.id
}
}

const data = Array.from({ length: count }, (_, i) => {
return { id: i }
})

// Treats all resolvers as either a promise or a function.
for (let index = 0; index < runs; index++) {
const resolver = resolve({ properties })
const funcs = data.map((data) => {
return resolver._resolve(data, {})
})
console.time('sync' + index)
await Promise.all(funcs)
console.timeEnd('sync' + index)
}

// Treats all resolvers as promises.
for (let index = 0; index < runs; index++) {
const resolver = resolve({ properties })
const funcs = data.map((data) => {
return resolver.resolve(data, {})
})
console.time('async' + index)
await Promise.all(funcs)
console.timeEnd('async' + index)
}
})
})
Loading