Skip to content

Question - async transform #72

@fxwss

Description

@fxwss

I have the following code:

export const updateUserValidator = vine.withMetaData<{ other: User }>().compile(
  vine.object({
    email: vine.string().email().optional(),
    password: vine.string().minLength(6).optional(),
    role: vine.string().in(['admin', 'user']).optional(),
    maxStreams: vine
      .number()
      .min(0)
      .withoutDecimals()
      .optional()
      .transform(async (value, field) => {
        const all = `user:${field.meta.other.id}:streams:*`
        const streams = await redis.keys(all)

        if (streams.length > value) {
          throw new Error(
            'Cannot set max streams to a value lower than the current number of streams'
          )
        }

        return value
      }),
  })
)

After validation i got:

const payload = await updateUserValidator.validate(ctx.request.all(), { meta: { other } })

// With the following type
const payload: {
    email: string | undefined;
    password: string | undefined;
    role: string | undefined;
    maxStreams: Promise<number>;
}

The thing is, i want the 'maxStreams' to be a number, not a Promise<number>, how could i do that without awaiting payload.maxStreams?

Any ideas?

Problably something like Field.awaited() would be cool

Example usage:

maxStreams: vine
      .number()
      .min(0)
      .withoutDecimals()
      .optional()
      .transform(async (value, field) => {
        const all = `user:${field.meta.other.id}:streams:*`
        const streams = await redis.keys(all)

        if (streams.length > value) {
          throw new Error(
            'Cannot set max streams to a value lower than the current number of streams'
          )
        }

        return value
      })
      .awaited()

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions