gcanti / io-ts

Runtime type system for IO decoding/encoding
https://gcanti.github.io/io-ts/
MIT License
6.68k stars 331 forks source link

[Question] Validate against data from database #675

Open maddiehosseini opened 1 year ago

maddiehosseini commented 1 year ago

🚀 Feature request

Current Behavior

I have a type named Contact which contains an accountNumber. Currently I'm only checking if the account number is within a specified hard-coded range:

interface AccountNumberBrand {
  readonly AccountNumber: unique symbol;
}
export const AccountNumber = t.brand(
  t.number,
  (n): n is t.Branded<number,AccountNumberBrand> =>
    n >= 0 && n <= 1000,
  'AccountNumber'
);

type AccountNumber = t.TypeOf<typeof AccountNumber>;

//-----------------------------

const Contact = t.type({
  AccountNumber: t.union([
    withMessage(
      AccountNumber,
      () => ContactValidationErrorType.InvalidAccountNumber
    ),
    t.undefined,
  ]),
});

Desired Behavior

I need to extend the validation to check if the account-number exists in the database or not. So I should be able to either pass the list of existing account numbers or a reference to the async function that gets the data from database.

Who does this impact? Who is this for?

Advanced users, typescript users

Describe alternatives you've considered

I can do the this validation in a separate function and have a 2-steps validation, but I prefer not to do it. Because other team members may later forget to use it and miss part of the validation logic.

Your environment

Software Version(s)
io-ts 2.2.13
TypeScript 4.7.4
mlegenhausen commented 1 year ago

This is out of scope of this library. io-ts is designed to do "pure" validations without side effects. The proposed 2-step validation approach is the one you should go with io-ts.