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

v4.2.5 transform won't give the transformed data when transform is not used on top-level rules #320

Open
stayknight opened this issue Aug 12, 2022 · 1 comment

Comments

@stayknight
Copy link

const Schema = require('async-validator').default

const descriptor = {
  body: {
    type: 'object',
    arr: {
      type: 'array',
      defaultField: { type: 'string' },
      transform(value) {
        console.log('transform: ', value)
        if (typeof value === 'string') {
          return value.split(',')
        }
        return value
      }
    }
  }
}
const data = {
  body: {
    arr: 'a,b',
    buf: Buffer.from([1, 2, 3, 4])
  }
}

const validator = new Schema(descriptor)
validator.validate(data, { first: true }, (errors, fields) => {
  if (errors) {
    console.error(errors)
  } else {
    console.log(fields)
  }
})

The output is:
{ body: { arr: 'a,b', buf: <Buffer 01 02 03 04> } }

The field body.arr is not transformed in the callback results.
But when arr field is on the top level of descriptor, it works fine.

@AllenYu0118
Copy link

descriptor arr 应该包裹在 fields 中,类似下面:

const descriptor: Rules = {
  body: {
    type: 'object',
    required: true,
    fields: {
      arr: {
        type: 'array',
        defaultField: { type: 'string' },
        transform(value) {
          if (typeof value === 'string') {
            return value.split(',');
          }
          return value;
        },
        validator: (_, value) => Array.isArray(value),
        message: 'arr 不是字符串或者数组类型',
      },
    },
  },
};

我提供了一个可以运行的列子,供参考 https://stackblitz.com/edit/typescript-7dtq2r?file=transform.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants