jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

How to split string and validate MongoDB Object? #2146

Closed yaneony closed 11 months ago

yaneony commented 11 months ago

Hello!

Assume we have following URL: /blog/some-title-here-65798691bb7250b78bf4d30

The last part of URL is MongoDB ObjectID. I would like to split to the last part, check if it is ObjectID and convert it from string to ObjectID.

That's how far I've got:

  yup.addMethod(yup.mixed, 'objectId', function () {
    return this
      .transform((id) => {
        return id.substring(id.lastIndexOf('-') + 1);
      })
      .test('objectId', 'NOT ID', (id) => {
        return app.mongodb.objectId.isValid(id);
      })
      .transform((id) => {
        return new app.mongodb.objectId(id);
      });
  });

The problem is, i need to convert last part to ObjectID only if that one isValid, if such is not valid, no need for transformation and would like to see default message.

Thanks for help!

yaneony commented 11 months ago

The only thing I can't get working is transforming value after test.

jquense commented 11 months ago

transforms always occur before tests, if you want an objectId schema type i'd do something like the following

const objectId = () => mixed<ObjectID>({ type: 'objectId', check: (value): value is ObjectID => value && app.mongodb.objectId.isValid(value) })